answer
stringlengths
17
10.2M
package pt.up.fe.aiad.tests; import jade.core.AID; import org.junit.Test; import pt.up.fe.aiad.scheduler.ScheduleEvent; import pt.up.fe.aiad.scheduler.Serializer; import pt.up.fe.aiad.scheduler.agentbehaviours.ABTBehaviour; import pt.up.fe.aiad.scheduler.agentbehaviours.ADOPTBehaviour; import pt.up.fe.aiad.utils.TimeInterval; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.TreeSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SerializerTest { /* @Test public void testEventsJSON() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c1 = Calendar.getInstance(); c1.setTime(sdf.parse("10/10/2014")); Calendar c2 = Calendar.getInstance(); c2.setTime(sdf.parse("11/10/2014")); Calendar c3 = Calendar.getInstance(); c3.setTime(sdf.parse("20/10/2014")); Map<String, TimeInterval> events = new HashMap<>(); events.put("fazer_aiad", new TimeInterval(c1, c2)); events.put("entregar_aiad", new TimeInterval(c3, c3)); String eventsStr = Serializer.EventsToJSON(events); Map<String, TimeInterval> events2 = Serializer.EventsFromJSON(eventsStr); assertEquals(24*60*60, events2.get("fazer_aiad").getDuration()); assertEquals(0, events2.get("entregar_aiad").getDuration()); } @Test public void testEventsAgentViewJSON() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); AID agent1 = new AID("test1", true); AID agent2 = new AID("test2", true); Calendar c1 = Calendar.getInstance(); c1.setTime(sdf.parse("10/10/2014")); Calendar c2 = Calendar.getInstance(); c2.setTime(sdf.parse("11/10/2014")); Calendar c3 = Calendar.getInstance(); c3.setTime(sdf.parse("20/10/2014")); Calendar c4 = Calendar.getInstance(); c4.setTime(sdf.parse("12/10/2014")); Map<AID, Map<String, TimeInterval>> agentView = new HashMap<>(); Map<String, TimeInterval> events1 = new HashMap<>(); events1.put("a", new TimeInterval(c1, c2)); events1.put("b", new TimeInterval(c3, c3)); Map<String, TimeInterval> events2 = new HashMap<>(); events2.put("a", new TimeInterval(c1, c4)); events2.put("b", new TimeInterval(c3, c3)); agentView.put(agent1, events1); agentView.put(agent2, events2); String eventsStr = Serializer.EventsAgentViewToJSON(agentView); Map<AID, Map<String, TimeInterval>> agentView2 = Serializer.EventsAgentViewFromJSON(eventsStr); assertEquals(2*agentView2.get(agent1).get("a").getDuration(), agentView2.get(agent2).get("a").getDuration()); }*/ @Test public void testEventProposalJSON() { AID agent1 = new AID("tést1", true); AID agent2 = new AID("test2", true); AID agent3 = new AID("test3", true); AID agent4 = new AID("test4", true); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); try { c1.setTime(sdf.parse("10/10/2014")); c2.setTime(sdf.parse("11/10/2014")); } catch (ParseException e) { e.printStackTrace(); } TreeSet<AID> ags = new TreeSet<>(); ags.add(agent1);ags.add(agent2);ags.add(agent3);ags.add(agent4); ScheduleEvent ev1 = new ScheduleEvent("cenas", 30*60, ags, new TimeInterval(c1, c2)); String json = Serializer.EventProposalToJSON(ev1); ScheduleEvent ev2 = Serializer.EventProposalFromJSON(json); assertEquals(json,Serializer.EventProposalToJSON(ev2)); } @Test public void testNoGoodJSON() { ABTBehaviour.NoGood ng = new ABTBehaviour.NoGood(); Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); Calendar c3 = Calendar.getInstance(); c3.set(2004, Calendar.JANUARY, 31, 18, 35); TimeInterval t1 = new TimeInterval(c1, c2); TimeInterval t2 = new TimeInterval(c2, c3); ng.v = t1; ng.cond = new HashMap<>(); ng.cond.put("test1", t1); ng.cond.put("test2", t2); ng.tag = new TreeSet<>(); ng.tag.add("test3"); ng.tag.add("test4"); ng.cost = 3; ng.exact = true; String json = Serializer.NoGoodToJSON(ng); ABTBehaviour.NoGood ng2 = Serializer.NoGoodFromJSON(json); assertEquals(ng2.v, ng.v); assertEquals(ng2.cond.get("test1"), ng.cond.get("test1")); assertEquals(ng2.cond.get("test2"), ng.cond.get("test2")); assertTrue(ng2.tag.containsAll(ng.tag) && ng.tag.containsAll(ng2.tag)); assertEquals(ng2.cost, ng.cost); assertEquals(ng2.exact, ng.exact); } @Test public void testVariableJSON() { ABTBehaviour.Variable var = new ABTBehaviour.Variable(); Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); var.v = new TimeInterval(c1, c2); var.agent = "test"; String json = Serializer.VariableToJSON(var); ABTBehaviour.Variable var2 = Serializer.VariableFromJSON(json); assertEquals(var2.v, var.v); assertEquals(var2.agent, var.agent); } @Test public void testCostJSON() { ADOPTBehaviour.Cost cost = new ADOPTBehaviour.Cost(); Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); Calendar c3 = Calendar.getInstance(); c3.set(2004, Calendar.JANUARY, 31, 18, 35); TimeInterval t1 = new TimeInterval(c1, c2); TimeInterval t2 = new TimeInterval(c2, c3); cost.sender= "Agent1@192.168.23.52:1099/JADE-Dãncing"; cost.context = new HashMap<>(); cost.context.put("Agent1@192.168.23.52:1099/JADE-Swimming", t1); cost.context.put("Agent2@192.168.23.52:1099/JADE-Dãncing", t2); cost.lb = 3; cost.ub = 400; String json = Serializer.CostToJSON(cost); ADOPTBehaviour.Cost cost2 = Serializer.CostFromJSON(json); assertEquals(cost.sender, cost2.sender); assertEquals(cost.lb, cost2.lb); assertEquals(cost.ub, cost2.ub); assertEquals(t1, cost2.context.get("Agent1@192.168.23.52:1099/JADE-Swimming")); assertEquals(t2, cost2.context.get("Agent2@192.168.23.52:1099/JADE-Dãncing")); } @Test public void testValueJSON() { ADOPTBehaviour.Value value = new ADOPTBehaviour.Value(); Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); TimeInterval t1 = new TimeInterval(c1, c2); value.sender = "Agent1@192.168.23.52:1099/JADE-Dancing"; value.chosenValue = t1; String json = Serializer.ValueToJSON(value); ADOPTBehaviour.Value value2 = Serializer.ValueFromJSON(json); assertEquals(value.sender, value2.sender); assertEquals(value.chosenValue, value2.chosenValue); } @Test public void testThresholdJSON() { ADOPTBehaviour.Threshold t = new ADOPTBehaviour.Threshold(); Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); Calendar c3 = Calendar.getInstance(); c3.set(2004, Calendar.JANUARY, 31, 18, 35); TimeInterval t1 = new TimeInterval(c1, c2); TimeInterval t2 = new TimeInterval(c2, c3); t.t= 2345; t.context = new HashMap<>(); t.context.put("Agent1@192.168.23.52:1099/JADE-Swimming", t1); t.context.put("Agent2@192.168.23.52:1099/JADE-Dancing", t2); String json = Serializer.ThresholdToJSON(t); ADOPTBehaviour.Threshold thr2 = Serializer.ThresholdFromJSON(json); assertEquals(thr2.t, thr2.t); assertEquals(t1, t.context.get("Agent1@192.168.23.52:1099/JADE-Swimming")); assertEquals(t2, t.context.get("Agent2@192.168.23.52:1099/JADE-Dancing")); } @Test public void testContextJSON() { Calendar c1 = Calendar.getInstance(); c1.set(2004, Calendar.JANUARY, 30, 18, 30); Calendar c2 = Calendar.getInstance(); c2.set(2004, Calendar.JANUARY, 30, 18, 51); Calendar c3 = Calendar.getInstance(); c3.set(2004, Calendar.JANUARY, 31, 18, 35); TimeInterval t1 = new TimeInterval(c1, c2); TimeInterval t2 = new TimeInterval(c2, c3); HashMap<String, TimeInterval> context = new HashMap<>(); context.put("Agent1@192.168.23.52:1099/JADE-Swimming", t1); context.put("Agent2@192.168.23.52:1099/JADE-Dancing", t2); String json = Serializer.ContextToJSON(context); HashMap<String, TimeInterval> context2 = Serializer.ContextFromJSON(json); assertEquals(t1, context2.get("Agent1@192.168.23.52:1099/JADE-Swimming")); assertEquals(t2, context2.get("Agent2@192.168.23.52:1099/JADE-Dancing")); } }
package is.ru.hugb.WebUI; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.Keys; public class TestWebUI extends SeleniumTestWrapper { @Test public void testTitleMatches() { driver.get(baseUrl); assertEquals("Tic Tac Toe", driver.getTitle()); } @Test public void testPickMode() throws Exception { driver.get(baseUrl); /* Remove Thread.sleep... */ Thread.sleep(1000); assertEquals("1", "1"); Thread.sleep(3500); /* ... finish test! */ } @Test public void testXWin() throws Exception { driver.get(baseUrl); /* Remove Thread.sleep... */ Thread.sleep(1000); driver.findElement(By.id("0")).click(); Thread.sleep(500); driver.findElement(By.id("3")).click(); Thread.sleep(500); driver.findElement(By.id("1")).click(); Thread.sleep(500); driver.findElement(By.id("4")).click(); Thread.sleep(500); driver.findElement(By.id("2")).click(); Thread.sleep(500); assertEquals("X is the WINNER!", driver.findElement(By.id("gameInfo")).getAttribute("innerHTML")); /* ... finish test! */ } }
package simulators; import addons.protocolchangers.FixedTimeProtocolChanger; import io.reporters.Reporter; import network.Network; import protocols.BGPProtocol; import protocols.Protocol; import simulation.Engine; import simulators.data.FullDeploymentDataCollector; import java.io.IOException; /** * The initial deployment simulator simulates a network with the detection already activated for all nodes from * the start to the end of the simulation. */ public class FullDeploymentSimulator extends Simulator { protected long deployTime; private Protocol deployProtocol; protected FullDeploymentDataCollector fullDeploymentDataCollector; FullDeploymentSimulator(Engine engine, Network network, int destinationId, Protocol deployProtocol, FullDeploymentDataCollector fullDeploymentDataCollector, int deployTime) { super(engine, network, destinationId, new BGPProtocol()); this.deployProtocol = deployProtocol; this.fullDeploymentDataCollector = fullDeploymentDataCollector; this.deployTime = deployTime; this.fullDeploymentDataCollector.register(engine); } /** * Executes one simulation. Should be overridden by subclasses in order to add additional operations * prior or after simulation. By default activates the debug report if enabled and calls the simulate() method * of the engine. */ @Override public void simulate() { // setup protocol changer new FixedTimeProtocolChanger(engine, state, deployTime) { @Override public void onTimeToChange() { deployProtocol.reset(); changeAllProtocols(deployProtocol); fullDeploymentDataCollector.setDeployed(true); } }; fullDeploymentDataCollector.clear(); super.simulate(); } /** * Calls the reporter's generate() method to generate a report with the collected stats. * * @param reporter reporter to generate report. * @throws IOException if an error with the output file occurs. */ @Override public void report(Reporter reporter) throws IOException { fullDeploymentDataCollector.dump(reporter); } }
package gamelogic; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.stage.WindowEvent; import logic.Controller; import java.util.ArrayList; import java.util.List; public class MainWindow { private List<Circle> playerMarkers = new ArrayList<>(); private Stage stage; private double screenWidth, screenHeight; private BooleanProperty player1Turn = new SimpleBooleanProperty(true); private GameBoard gameBoard; private Controller controller; private GameArray gameArray; private ScrollPane gamePane; private Button chatButton; private BorderPane rootPane; private HBox startBox; private StackPane connectPane; private HBox connectBox; public MainWindow(Stage stage, Controller controller) { this.controller = controller; screenWidth = 600; screenHeight = 600; this.stage = stage; stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { /** * System exit closes all threads and connections. */ controller.quit(); } }); this.stage.setScene(initStartScreen()); // this.stage.setScene(initGameBoard()); this.stage.show(); } private Scene initStartScreen() { rootPane = new BorderPane(); Scene startScene = new Scene(rootPane, screenWidth, screenHeight); TextField ip = new TextField(); ip.setPromptText("Enter IP"); Button connectButton = new Button("Connect"); connectBox = new HBox(); connectBox.getChildren().addAll(ip, connectButton); connectBox.setAlignment(Pos.CENTER); connectPane = new StackPane(); connectPane.getChildren().add(connectBox); connectPane.setPrefSize(screenWidth, screenHeight - (screenHeight*0.1)); connectPane.setStyle("-fx-background-color: #ff0000"); rootPane.setCenter(connectPane); rootPane.setBottom(chatBox()); connectButton.setOnAction(connect -> { controller.connect(ip.getText()); }); startBox = new HBox(); Button startButton = new Button("START GAME!"); startBox.setAlignment(Pos.CENTER); startButton.setOnAction(start -> { player1Turn.setValue(controller.startGame()); System.out.println(player1Turn.getValue()); }); startBox.getChildren().add(startButton); connectPane.getChildren().add(startBox); startBox.setVisible(false); return startScene; } public HBox chatBox() { TextField chatMsg = new TextField(); chatMsg.setPromptText("chat"); chatMsg.setMinWidth(screenWidth - (screenWidth*0.2)); chatButton = new Button("Send msg"); chatButton.setDisable(true); chatButton.setMinWidth(screenWidth - (screenWidth*0.8)); HBox chatBox = new HBox(); chatBox.getChildren().addAll(chatMsg, chatButton); return chatBox; } public void connected(boolean conn) { if (conn) { Platform.runLater(() -> { chatButton.setDisable(false); connectBox.setVisible(false); startBox.setVisible(true); }); } else { Platform.runLater(() -> { chatButton.setDisable(true); connectBox.setVisible(true); startBox.setVisible(false); }); } } public void startGame(boolean start) { player1Turn.setValue(start); } /** * Initiates the Gameboard * * @return A Scene with a GridPane */ private Scene initGameBoard() { gameBoard = new GameBoard(screenWidth, screenHeight, 3); gameArray = new GameArray(gameBoard.getRows()); gamePane = new ScrollPane(); gamePane.setContent(gameBoard); gameBoard.addEventHandler(MouseEvent.MOUSE_CLICKED, addMouseListener()); Scene gameScene = new Scene(gamePane, screenWidth, screenHeight); return gameScene; } private void viewController(int col, int row) { if(!checkDoubles(col, row)) { drawMarker(col, row); player1Turn.setValue(!player1Turn.getValue()); } if(isFull()) { playerMarkers.forEach(marker -> { marker.radiusProperty().bind(gameBoard.getCellSizeProperty().divide(2)); }); gameBoard.addEventHandler(MouseEvent.MOUSE_CLICKED, addMouseListener()); } } private boolean isFull() { if(playerMarkers.size()==(gameBoard.getRows()*gameBoard.getRows())) { // Increase the gameboard's size gameBoard.incGameBoard(); gameArray.growBoard(GridPane.getColumnIndex(playerMarkers.get(playerMarkers.size()-1)), GridPane.getRowIndex(playerMarkers.get(playerMarkers.size()-1))); int[][] tempGrid = gameArray.getGameGrid(); playerMarkers.clear(); gameBoard = new GameBoard(screenWidth, screenHeight, tempGrid[0].length); gamePane.setContent(gameBoard); for (int x = 0; x<tempGrid.length; x++) { for(int y = 0; y<tempGrid[x].length; y++) { if (tempGrid[x][y] == 1) { Circle playerMarker = new PlayerMarker().placeMarker(1); gameBoard.add(playerMarker, x, y); playerMarkers.add(playerMarker); } else if(tempGrid[x][y] == 2) { Circle playerMarker = new PlayerMarker().placeMarker(2); gameBoard.add(playerMarker, x, y); playerMarkers.add(playerMarker); } } } return true; } return false; } private boolean checkDoubles(int col, int row) { for (Circle circle : playerMarkers) { if (GridPane.getColumnIndex(circle) - col == 0 && GridPane.getRowIndex(circle) - row == 0) { return true; } } return false; } private void drawMarker(int col, int row) { if (!checkDoubles(col, row)) { if (player1Turn.getValue()) { Circle marker = new PlayerMarker().placeMarker(1); gameBoard.add(marker, col, row); gameBoard.addMarker(marker, col, row); playerMarkers.add(marker); gameArray.addMarker(1, col, row); } else { Circle marker = new PlayerMarker().placeMarker(2); gameBoard.add(marker, col, row); gameBoard.addMarker(marker, col, row); playerMarkers.add(marker); gameArray.addMarker(2, col, row); } playerMarkers.forEach(marker -> { marker.radiusProperty().bind(gameBoard.getCellSizeProperty().divide(2)); }); } } private EventHandler<MouseEvent> addMouseListener() { return new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getEventType() == MouseEvent.MOUSE_CLICKED) { int clickCol = (int) Math.round(((e.getX() - (e.getX() % gameBoard.getCellSize())) / gameBoard.getCellSize())); int clickRow = (int) Math.round(((e.getY() - (e.getY() % gameBoard.getCellSize())) / gameBoard.getCellSize())); viewController(clickCol, clickRow); } } }; } }
package de.vogel612.ct; import static org.hamcrest.Matcher.*; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class TrieTests { private CompressedTrie cut; @Before public void setup() { cut = new CompressedTrie(); } @Test public void emptyTrie_returnsNoMatches() { assertTrue(cut.matches("asdf").isEmpty()); } @Test public void filledTree_containsWord() { cut.add("test"); assertTrue(cut.contains("test")); } @Test public void filledTree_containsAllWords() { cut.add("asdf"); cut.add("test"); cut.add("random"); assertTrue(cut.containsAll(Arrays.asList("test", "random"))); } @Test public void filledTree_containsAny() { cut.add("asdf"); cut.add("test"); cut.add("random"); assertTrue(cut.containsAny(Arrays.asList("foo", "bar", "test"))); } @Test public void filledTree_containsNone() { cut.add("asdf"); cut.add("test"); cut.add("random"); assertFalse(cut.containsAny(Arrays.asList("foo", "bar", "quux"))); } @Test public void filledTree_containsSome() { cut.add("asdf"); cut.add("test"); cut.add("random"); Collection<String> testItems = Arrays.asList("foo", "bar", "quux", "test"); assertFalse(cut.containsAll(testItems)); assertTrue(cut.containsAny(testItems)); } @Test public void removeNode_changesContains() { cut.add("test"); assertTrue(cut.contains("test")); boolean result = cut.remove("test"); assertFalse(cut.contains("test")); assertTrue(result); } @Test public void removeNonexistingNode_returnsFalse() { assertFalse(cut.remove("random")); } @Test public void removeAll_removesAllRelevantNodes() { Collection<String> items = Arrays.asList("test", "foo", "bar", "quux"); cut.addAll(items); assertTrue(cut.containsAll(items)); boolean result = cut.removeAll(items); assertFalse(cut.containsAny(items)); assertTrue(result); } @Test public void removeAll_returnsTrue_onMissingNodes() { cut.add("test"); assertTrue(cut.contains("test")); boolean result = cut.removeAll(Arrays.asList("test", "random")); assertFalse(cut.contains("test")); assertTrue(result); } @Test public void copyConstructor() { Collection<String> items = Arrays.asList("test", "foo", "bar", "quux"); cut = new CompressedTrie(items); assertTrue(cut.containsAll(items)); } @Test public void matchesTesting() { cut.add("test"); cut.add("testing"); cut.add("twitter"); cut.add("twerk"); Collection<String> expected = Arrays.asList("test", "testing", "twitter", "twerk"); List<String> actual = cut.matches(""); assertTrue(actual.containsAll(expected)); expected = Arrays.asList("test", "testing"); actual = cut.matches("tes"); assertTrue(actual.containsAll(expected)); expected = Arrays.asList("twitter", "twerk"); actual = cut.matches("tw"); assertTrue(actual.containsAll(expected)); } @Test public void testSize() { assertEquals(0, cut.size()); cut.add("something"); cut.add("more"); assertEquals(2, cut.size()); cut.add("more"); assertEquals(2, cut.size()); } @Test public void testClear() { final List<String> items = Arrays.asList("something", "more", "random"); cut.addAll(items); assertEquals(items.size(), cut.size()); cut.clear(); assertTrue(cut.isEmpty()); assertFalse(cut.containsAny(items)); } @Test public void testEmpty() { assertTrue(cut.isEmpty()); cut.add("something"); assertFalse(cut.isEmpty()); } @Test public void contains_returnsFalse_forEmptyTrie() { assertFalse(cut.contains("something")); assertFalse(cut.contains(2)); } @Test public void remove_returnsFalse_forNonStrings() { assertFalse(cut.remove(2)); } @Test public void retainAll() { List<String> base = Arrays.asList("something", "random", "and", "some", "other", "items"); List<String> others = Arrays.asList("something", "less", "nice", "and", "some", "cranky", "stuff"); List<String> intersection = new ArrayList<>(base); intersection.retainAll(others); List<String> distinction = new ArrayList<>(base); distinction.removeAll(others); cut.addAll(base); assertTrue(cut.containsAll(base)); cut.retainAll(others); assertTrue(cut.containsAll(intersection)); assertEquals(cut.size(), intersection.size()); } }
package fr.ritaly.graphml4j; import java.io.StringWriter; public class Main { public static void main(String[] args) throws Exception { final StringWriter stringWriter = new StringWriter(); GraphMLWriter writer = new GraphMLWriter(stringWriter); // Customize the rendering final NodeStyle nodeStyle = writer.getNodeStyle(); nodeStyle.setBorderType(LineType.LINE); nodeStyle.setBorderWidth(2.0f); nodeStyle.setFillColor("#CCCCCC"); nodeStyle.setFontSize(13); nodeStyle.setHeight(60.0f); nodeStyle.setWidth(60.0f); nodeStyle.setShape(Shape.ROUNDED_RECTANGLE); nodeStyle.setTextAlignment(Alignment.CENTER); writer.setNodeStyle(nodeStyle); final EdgeStyle edgeStyle = writer.getEdgeStyle(); edgeStyle.setColor("#000000"); edgeStyle.setSmoothed(true); edgeStyle.setSourceArrow(Arrow.CIRCLE); edgeStyle.setTargetArrow(Arrow.DELTA); edgeStyle.setType(LineType.LINE); edgeStyle.setWidth(2.0f); writer.setEdgeStyle(edgeStyle); // Generate the graph writer.graph(); writer.group("TEST"); String prevNodeId = null; for (int i = 0; i < 5; i++) { final String nodeId = writer.node(Integer.toString(i)); if ((i > 0) && (i < 4)) { writer.edge(prevNodeId, nodeId); } prevNodeId = nodeId; } writer.closeGroup(); writer.closeGraph(); System.out.println(stringWriter.toString()); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.logic.commands.EditCommand; import seedu.address.testutil.TestTask; public class FindCommandTest extends TaskManagerGuiTest { @Test public void find_nonEmptyList() { assertFindResult("find Mark"); // no results assertFindResult("find Meier", td.benson, td.daniel); // multiple results //find after deleting one result commandBox.runCommand("delete 1"); public void find_byKeywords() { assertFindResult("find Meier", td.benson, td.daniel); // find by name, multiple results assertFindResult("find friends", td.alice, td.benson); // find by tags, multiple results assertFindResult("find find", td.alice, td.benson, td.fiona); // find by description, multiple results // find after adding one task commandBox.runCommand(td.benson.getAddCommand()); assertFindResult("find Meier", td.benson, td.daniel, td.benson); //find after deleting one result commandBox.runCommand("delete 3"); assertFindResult("find Meier", td.benson, td.daniel); //find after editing one task int targetIndex = 2; String detailsToEdit = "Bobby"; commandBox.runCommand(EditCommand.COMMAND_WORD + " " + targetIndex + " " + detailsToEdit); assertFindResult("find Meier", td.daniel); } @Test @Test public void find_emptyList() { commandBox.runCommand("clear"); assertFindResult("find Jean"); // no results } @Test public void find_invalidCommand_fail() { commandBox.runCommand("findgeorge"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); } private void assertFindResult(String command, TestTask... expectedHits) { commandBox.runCommand(command); assertListSize(expectedHits.length); assertResultMessage(expectedHits.length + " tasks listed!"); assertTrue(taskListPanel.isListMatching(expectedHits)); } }
package guitests; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.SaveCommand; //@@author A0138961W public class SaveCommandTest extends TaskBossGuiTest { @Test public void save() { //invalid filepath commandBox.runCommand("save C://user/desktop/^*+ assertResultMessage(SaveCommand.MESSAGE_INVALID_FILEPATH); //invalid filepath using short command commandBox.runCommand("sv C://user/desktop/^*+ assertResultMessage(SaveCommand.MESSAGE_INVALID_FILEPATH); //valid filepath commandBox.runCommand("save C://user/desktop/taskboss"); assertResultMessage(SaveCommand.MESSAGE_SUCCESS); //valid filepath using short command commandBox.runCommand("sv C://user/desktop/taskboss"); assertResultMessage(SaveCommand.MESSAGE_SUCCESS); //invalid command commandBox.runCommand("saveC://user/desktop/taskboss"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); //empty filepath commandBox.runCommand("save"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE)); //missing filepath using short command commandBox.runCommand("sv"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE)); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import guitests.guihandles.HelpWindowHandle; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.logic.undoredomanager.UndoRedoManager; import seedu.address.model.task.Address; import seedu.address.model.task.Description; import seedu.address.model.task.Name; import seedu.address.model.task.Time; import seedu.address.testutil.TaskBuilder; import seedu.address.testutil.TestTask; import seedu.address.testutil.TestUtil; import java.util.Date; public class UndoCommandTest extends AddressBookGuiTest{ public static final int STACK_SIZE = UndoRedoManager.STACK_LIMIT; @Test public void undo() { //add and undo one person TestTask[] currentList = td.getTypicalPersons(); commandBox.runCommand(td.hoon.getAddCommand()); assertUndoSuccess(currentList); //undo on max limit TestTask generatedName = new TestTask(); generatedName = generateTasks(generatedName,65); //generate letter A as Task commandBox.runCommand(generatedName.getAddCommand()); currentList = TestUtil.addPersonsToList(currentList,generatedName); TestTask[] expectedList = currentList; undo_max(currentList, expectedList); //ensure undo fail on Max Limit + 1 assertUndoSuccess(currentList); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); //undo on a sequence A,B,undo,C,undo,undo expectedList = currentList; undo_sequence(currentList, expectedList); //ensure undo fails on select command commandBox.runCommand("select 1"); commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); //ensure undo fails on clear command commandBox.runCommand("clear"); commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); //ensure undo fails on help command commandBox.runCommand("help"); HelpWindowHandle hwh = commandBox.runHelpCommand(); hwh.closeWindow(); commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); //ensure undo fails on find command commandBox.runCommand("find george"); commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); } private void undo_max(TestTask[] currentList, TestTask[] expectedList) { TestTask generatedName = new TestTask(); for (int i = 66; i < 66 + STACK_SIZE; i++) { //start from letter B generatedName = generateTasks(generatedName,i); commandBox.runCommand(generatedName.getAddCommand()); currentList = TestUtil.addPersonsToList(currentList,generatedName); } for (int j = 0; j < STACK_SIZE; j++) { commandBox.runCommand("undo"); } assertTrue(personListPanel.isListMatching(expectedList)); } private void undo_sequence(TestTask[] currentList, TestTask[] expectedList){ int seq1 = 2; int seq2 = 3; int undos = 1; TestTask generatedName = new TestTask(); for (int i = 66; i < 66 + seq1; i++) { //start from letter B generatedName = generateTasks(generatedName,i); commandBox.runCommand(generatedName.getAddCommand()); currentList = TestUtil.addPersonsToList(currentList,generatedName); } commandBox.runCommand("undo"); for (int j = 66 + seq1; j < 66 + seq1 + seq2; j++) { generatedName = generateTasks(generatedName,j); commandBox.runCommand(generatedName.getAddCommand()); currentList = TestUtil.addPersonsToList(currentList,generatedName); } for (int k = 0; k < seq1 + seq2 - undos; k++) { commandBox.runCommand("undo"); } assertTrue(personListPanel.isListMatching(expectedList)); commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_UNDOABLE_COMMAND); } private TestTask generateTasks(TestTask generatedName,int i){ try { generatedName = new TaskBuilder().withName(Character.toString((char)i)) .withAddress("311, Clementi Ave 2, #02-25") .withEmail("johnd's description").withPhone("11-10-2016") .withTags("owesMoney", "friends").withPeriod("10:00AM").build(); } catch (IllegalValueException e) { assert false : "impossible"; } return generatedName; } private void assertUndoSuccess(TestTask[] currentList) { commandBox.runCommand("undo"); assertTrue(personListPanel.isListMatching(currentList)); } }
package io.scif.img; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.After; import org.junit.Test; import org.scijava.Context; import io.scif.config.SCIFIOConfig; import io.scif.config.SCIFIOConfig.ImgMode; import io.scif.io.ByteArrayHandle; import io.scif.services.LocationService; import net.imagej.ImgPlus; import net.imglib2.RandomAccess; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.type.numeric.integer.UnsignedByteType; /** * Tests for the {@link ImgSaver} class. * * @author Mark Hiner */ public class ImgSaverTest { private final String id = "testImg&lengths=512,512,5&axes=X,Y,Time.fake"; private final String out = "test.tif"; private final Context ctx = new Context(); private final LocationService locationService = ctx.getService( LocationService.class); @After public void cleanup() { final File f = new File(out); if (f.exists()) f.delete(); } /** * Write an image to memory using the {@link ImgSaver} and verify that the * given {@link ImgPlus} is not corrupted during the process. */ @Test public void testImgPlusIntegrity() throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); final ByteArrayHandle bah = new ByteArrayHandle(); locationService.mapFile(out, bah); final SCIFIOImgPlus<?> openImg = o.openImgs(id, config).get(0); final String source = openImg.getSource(); s.saveImg(out, openImg); assertEquals(source, openImg.getSource()); } /** * Test that ImgSaver writes each plane of a multi-plane PlanarImg correctly */ @Test public void testPlanarPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane CellImg correctly */ @Test public void testSlowPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.CELL); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane ArrayImg correctly */ @Test public void testArrayPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.ARRAY); testPlaneSavingForConfig(config); } // -- Helper methods -- private void testPlaneSavingForConfig(final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); // write the image SCIFIOImgPlus<UnsignedByteType> openImg = o.openImgs(id, new UnsignedByteType(), config).get(0); s.saveImg(out, openImg); // re-read the written image and check dimensions openImg = o.<UnsignedByteType> openImgs(out, new UnsignedByteType()).get(0); // fakes start with 10 0's, then pixel value == plane index.. // so we have to skip along the x-axis a bit int[] pos = { 11, 0, 0 }; for (int i = 0; i < 5; i++) { pos[2] = i; RandomAccess<UnsignedByteType> randomAccess = openImg.randomAccess(); randomAccess.setPosition(pos); assertEquals(i, randomAccess.get().getRealDouble(), 0.0001); } } }
package ocelot; import org.junit.BeforeClass; import org.junit.Test; import static ocelot.Opcode.*; import static org.junit.Assert.*; import org.junit.Ignore; /** * * @author ben */ public class TestIntArithmetic { private static InterpMain im; @BeforeClass public static void setup() { im = new InterpMain(); } // General form of a simple test case should be: // 1. Set up a byte array of the opcodes to test // 1.a Ensure that this ends with an opcode from the RETURN family // 2. Pass to an InterpMain instance // 3. Look at the return value @Test public void int_divide_works() { byte[] buf = {ICONST_5.B(), ICONST_3.B(), IDIV.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type is int", JVMType.I, res.type); assertEquals("Return value should be 1", 1, (int) res.value); byte[] buf1 = {ICONST_2.B(), ICONST_2.B(), IDIV.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf1, new InterpLocalVars()); assertEquals("Return type is int", JVMType.I, res.type); assertEquals("Return value should be 1", 1, (int) res.value); byte[] buf2 = {BIPUSH.B(), (byte)17, BIPUSH.B(), (byte)5, IREM.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf2, new InterpLocalVars()); assertEquals("Return type is int", JVMType.I, res.type); assertEquals("Return value should be 2", 2, (int) res.value); } @Test public void int_arithmetic_works() { byte[] buf = {ICONST_1.B(), ICONST_1.B(), IADD.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 2", 2, (int) res.value); byte[] buf2 = {ICONST_1.B(), ICONST_M1.B(), IADD.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf2, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 0", 0, (int) res.value); byte[] buf3 = {ICONST_2.B(), ICONST_M1.B(), IMUL.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf3, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be -2", -2, (int) res.value); } @Test public void iconst_store_iinc_load() { byte[] buf = {ICONST_1.B(), ISTORE.B(), (byte) 1, IINC.B(), (byte) 1, (byte) 1, ILOAD.B(), (byte) 1, IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 2", 2, (int) res.value); } @Test public void iconst_dup() { byte[] buf = {ICONST_1.B(), DUP.B(), IADD.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 2", 2, (int) res.value); byte[] buf2 = {ICONST_1.B(), DUP.B(), IADD.B(), DUP.B(), IADD.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf2, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 4", 4, (int) res.value); } @Test public void iconst_dup_nop_pop() { byte[] buf = {ICONST_1.B(), DUP.B(), NOP.B(), POP.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 1", 1, (int) res.value); byte[] buf2 = {ICONST_1.B(), DUP.B(), NOP.B(), POP.B(), POP.B(), RETURN.B()}; res = im.execMethod("", "main:()V", buf2, new InterpLocalVars()); assertNull("Return should be null", res); } @Test public void iconst_dup_x1() { byte[] buf = {ICONST_1.B(), ICONST_2.B(), DUP_X1.B(), IADD.B(), IADD.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buf, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 5", 5, (int) res.value); byte[] buf2 = {ICONST_1.B(), ICONST_2.B(), DUP_X1.B(), IADD.B(), DUP_X1.B(), IADD.B(), IADD.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buf2, new InterpLocalVars()); assertEquals("Return type should be int", JVMType.I, res.type); assertEquals("Return value should be 8", 8, (int) res.value); } @Test @Ignore public void TestIntIfEqPrim() { byte[] buffy = {ICONST_1.B(), ICONST_1.B(), IADD.B(), ICONST_2.B(), IF_ICMPEQ.B(), (byte) 0, (byte) 11, ICONST_4.B(), GOTO.B(), (byte) 0, (byte) 12, ICONST_3.B(), IRETURN.B()}; JVMValue res = im.execMethod("", "main:()V", buffy, new InterpLocalVars()); assertEquals(JVMType.I, res.type); assertEquals(2, ((int) res.value)); byte[] buffy2 = {ICONST_1.B(), ICONST_1.B(), IADD.B(), ICONST_3.B(), IF_ICMPEQ.B(), (byte) 0, (byte) 11, ICONST_4.B(), GOTO.B(), (byte) 0, (byte) 12, ICONST_3.B(), IRETURN.B()}; res = im.execMethod("", "main:()V", buffy2, new InterpLocalVars()); assertEquals(JVMType.I, res.type); assertEquals(2, ((int) res.value)); } }
package datamanagement; public interface IStudentUnitRecord { public Integer getStudentID(); public String getUnitCode(); public void setAsg1(float mark); public float getAsg1(); public void setAsg2(float mark); public float getAsg2(); public void setExam(float mark); public float getExam(); public float getTotal(); }
package dbscryptolib; import dbsstringlib.StringSplitter; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import java.util.Base64; /** * Implement encryption by key generated from file and key * * @author Frank Schwab, DB Systel GmbH * @version 2.3.1 */ public class FileAndKeyEncryption implements AutoCloseable { /* * Private constants */ /** * Boundaries for valid format ids */ private static final byte FORMAT_ID_MIN = 1; private static final byte FORMAT_ID_MAX = 5; /** * HMAC algorithm to be used */ private static final String HMAC_256_ALGORITHM_NAME = "HmacSHA256"; /** * Length of key for HMAC algorithm */ private static final int HMAC_256_BYTE_LENGTH = 32; /** * Encryption algorithm */ private static final String AES_ALGORITHM_NAME = "AES"; /** * Encryption specification with algorithm, mode and padding * * <p> * The index of the string in the array corresponds to the format id * </p> */ private static final String[] ENCRYPTION_SPECIFICATION = {"Invalid", AES_ALGORITHM_NAME + "/CFB/NoPadding", AES_ALGORITHM_NAME + "/CTR/NoPadding", AES_ALGORITHM_NAME + "/CTR/NoPadding", AES_ALGORITHM_NAME + "/CBC/NoPadding", AES_ALGORITHM_NAME + "/CBC/NoPadding"}; /** * String encoding to be used for encrypted data strings */ private static final String STRING_ENCODING_FOR_DATA = "UTF-8"; /** * Separator character in key representation */ private static final String PARTS_SEPARATOR = "$"; /** * Maximum key file size */ private static final int MAX_KEYFILE_SIZE = 10000000; /** * Prefix salt for key modification with a "subject" */ private static final byte[] PREFIX_SALT = {(byte) 84, (byte) 117}; // i.e "Tu" /** * Postfix salt for key modification with a "subject" */ private static final byte[] POSTFIX_SALT = {(byte) 112, (byte) 87}; // i.e. "pW" /** * Instance of HMAC calculator * <p> * This is placed here so the expensive instantiation of the Mac class is * done only once. * <p> * Unfortunately it can not be made final as the constructor of this class * may throw an exception. */ private Mac HMAC_INSTANCE; /** * Instance of SecureRandom pseudo random number generator (PRNG) * <p> * This is placed here so the expensive instantiation of the SecureRandom class is * done only once. * <p> */ private SecureRandom SECURE_RANDOM_INSTANCE; /** * Helper class to store encryption parameters */ private class EncryptionParts { public byte formatId; public byte[] iv; public byte[] encryptedData; public byte[] checksum; public void zap() { formatId = (byte) 0; if (iv != null) Arrays.fill(iv, (byte) 0); if (encryptedData != null) Arrays.fill(encryptedData, (byte) 0); if (checksum != null) Arrays.fill(checksum, (byte) 0); } } /* * Instance variables */ private ProtectedByteArray m_EncryptionKey; private ProtectedByteArray m_HMACKey; /* * Private methods */ /** * Get instance of HMAC * * @return HMAC instance * @throws NoSuchAlgorithmException if the specified HMAC algorithm is not implemented */ private Mac getHMACInstance() throws NoSuchAlgorithmException { if (HMAC_INSTANCE == null) HMAC_INSTANCE = Mac.getInstance(HMAC_256_ALGORITHM_NAME); return HMAC_INSTANCE; } /** * Get instance of SecureRandom * * @return SecureRandom instance */ private SecureRandom getSecureRandomInstance() { if (SECURE_RANDOM_INSTANCE == null) SECURE_RANDOM_INSTANCE = SecureRandomFactory.getSensibleSingleton(); return SECURE_RANDOM_INSTANCE; } /* * Check methods */ private void checkHMACKey(final byte[] aHMACKey) throws IllegalArgumentException { if (aHMACKey.length != HMAC_256_BYTE_LENGTH) throw new IllegalArgumentException("The HMAC key does not have a length of " + Integer.toString(HMAC_256_BYTE_LENGTH) + " bytes"); } private void checkKeyFileSize(final Path keyFile) throws IllegalArgumentException, IOException { final long keyFileSize = Files.size(keyFile); if (keyFileSize <= 0) throw new IllegalArgumentException("Key file is empty"); if (keyFileSize > MAX_KEYFILE_SIZE) throw new IllegalArgumentException("Key file is larger than " + Integer.toString(MAX_KEYFILE_SIZE) + " bytes"); } private EncryptionParts getPartsFromPrintableString(final String encryptionText) throws IllegalArgumentException { final String[] parts = StringSplitter.split(encryptionText, PARTS_SEPARATOR); // Use my own string splitter to avoid Java's RegEx inefficiency // parts = encryptionText.split("\\Q$\\E"); // This should have been just "$". But Java stays true to it's motto: Why make it simple when there's a complicated way to do it? final EncryptionParts result = new EncryptionParts(); try { result.formatId = Byte.parseByte(parts[0]); } catch (final NumberFormatException e) { throw new IllegalArgumentException("Invalid format id"); } if ((result.formatId >= FORMAT_ID_MIN) && (result.formatId <= FORMAT_ID_MAX)) { if (parts.length == 4) { Base64.Decoder b64Decoder = Base64.getDecoder(); result.iv = b64Decoder.decode(parts[1]); result.encryptedData = b64Decoder.decode(parts[2]); result.checksum = b64Decoder.decode(parts[3]); } else throw new IllegalArgumentException("Number of '$' separated parts in encrypted text is not 4"); } else throw new IllegalArgumentException("Unknown format id"); return result; } /** * Return unpadded string bytes depending on format id * * @param formatId Format id of data * @param paddedDecryptedStringBytes Byte array of padded decrypted bytes * @return Unpadded decrypted bytes */ private byte[] getUnpaddedStringBytes(final byte formatId, final byte[] paddedDecryptedStringBytes) { // Formats 1 and 2 use padding. Formats 3 and 4 use blinding. if (formatId >= 3) return ByteArrayBlinding.unBlindByteArray(paddedDecryptedStringBytes); else return ArbitraryTailPadding.removePadding(paddedDecryptedStringBytes); } /** * Get SecureSecretKeySpec with respect to a subject * * @param hmacKey The key to use for HMAC calculation * @param baseKey The key the subject key is derived from as a byte array * @param forAlgorithmName Algorithm name for the SecureSecretKeySpec to create * @param subjectBytes The subject as a byte array * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) * @return SecureSecretKeySpec with the specified subject */ private SecureSecretKeySpec getSecretKeySpecForKeyWithSubject(final ProtectedByteArray hmacKey, final ProtectedByteArray baseKey, final String forAlgorithmName, final byte[] subjectBytes) throws InvalidKeyException, NoSuchAlgorithmException { final Mac hmac = getHMACInstance(); final byte[] hmacKeyBytes = hmacKey.getData(); final SecureSecretKeySpec hmacKeySpec = new SecureSecretKeySpec(hmacKeyBytes, HMAC_256_ALGORITHM_NAME); Arrays.fill(hmacKeyBytes, (byte) 0); hmac.init(hmacKeySpec); final byte[] baseKeyBytes = baseKey.getData(); hmac.update(baseKeyBytes); Arrays.fill(baseKeyBytes, (byte) 0); hmac.update(PREFIX_SALT); hmac.update(subjectBytes); final byte[] computedKey = hmac.doFinal(POSTFIX_SALT); final SecureSecretKeySpec result = new SecureSecretKeySpec(computedKey, forAlgorithmName); Arrays.fill(computedKey, (byte) 0); return result; } /** * Get default SecureSecretKeySpec for key * * @param baseKey The key to wrap in a SecureSecretKeySpec * @param forAlgorithmName Algorithm name for the SecureSecretKeySpec to create * @return SecureSecretKeySpec of specified key */ private SecureSecretKeySpec getDefaultSecretKeySpecForKey(final ProtectedByteArray baseKey, final String forAlgorithmName) { final byte[] baseKeyBytes = baseKey.getData(); final SecureSecretKeySpec result = new SecureSecretKeySpec(baseKeyBytes, forAlgorithmName); Arrays.fill(baseKeyBytes, (byte) 0); return result; } /** * Get default SecureSecretKeySpec for encryption * @return SecureSecretKeySpec for default encryption key */ private SecureSecretKeySpec getDefaultSecretKeySpecForEncryption() { return getDefaultSecretKeySpecForKey(this.m_EncryptionKey, AES_ALGORITHM_NAME); } /** * Get default SecureSecretKeySpec for HMAC calculation * @return SecureSecretKeySpec for default HMAC key */ private SecureSecretKeySpec getDefaultSecretKeySpecForHMAC() { return getDefaultSecretKeySpecForKey(this.m_HMACKey, HMAC_256_ALGORITHM_NAME); } /** * Get encryption key depending on whether a subject is present or not * * @param subjectBytes The subject as a byte array (may have length 0) * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private SecureSecretKeySpec getSecretKeySpecForEncryptionDependingOnSubject(final byte[] subjectBytes) throws InvalidKeyException, NoSuchAlgorithmException { if (subjectBytes.length > 0) return getSecretKeySpecForKeyWithSubject(this.m_HMACKey, this.m_EncryptionKey, AES_ALGORITHM_NAME, subjectBytes); else return getDefaultSecretKeySpecForEncryption(); } /** * Get HMAC key depending on whether a subject is present or not * * @param subjectBytes The subject as a byte array (may have length 0) * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private SecureSecretKeySpec getSecretKeySpecForHMACDependingOnSubject(final byte[] subjectBytes) throws InvalidKeyException, NoSuchAlgorithmException { if (subjectBytes.length > 0) return getSecretKeySpecForKeyWithSubject(this.m_EncryptionKey, this.m_HMACKey, HMAC_256_ALGORITHM_NAME, subjectBytes); else return getDefaultSecretKeySpecForHMAC(); } private String rawDataDecryption(final EncryptionParts encryptionParts, final byte[] subjectBytes) throws BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { // "encryptionParts.formatId" has been checked in "decryptData" and does not need to be checked here final String encryptionSpecification = ENCRYPTION_SPECIFICATION[encryptionParts.formatId]; final Cipher aesCipher = Cipher.getInstance(encryptionSpecification); final SecureSecretKeySpec decryptionKey = getSecretKeySpecForEncryptionDependingOnSubject(subjectBytes); aesCipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(encryptionParts.iv)); final byte[] paddedDecryptedStringBytes = aesCipher.doFinal(encryptionParts.encryptedData); decryptionKey.close(); final byte[] unpaddedDecryptedStringBytes = getUnpaddedStringBytes(encryptionParts.formatId, paddedDecryptedStringBytes); Arrays.fill(paddedDecryptedStringBytes, (byte) 0); final String result = new String(unpaddedDecryptedStringBytes, STRING_ENCODING_FOR_DATA); Arrays.fill(unpaddedDecryptedStringBytes, (byte) 0); return result; } /** * Calculate capacity of StringBuilder for encryption parts * <p> * The size of the final string is 4 + SumOf(ceil(ArrayLength * 4 / 3)). * <p> * This is a complicated expression which is overestimated by the easier * expression 4 + SumOfArrayLengths * 3 / 2 * * @param encryptionParts Encryption parts to calculate the capacity for * @return Slightly overestimated capacity of the StringBuilder for the * supplied encryption parts */ private int calculateStringBuilderCapacityForEncryptionParts(final EncryptionParts encryptionParts) { final int arrayLengths = encryptionParts.iv.length + encryptionParts.encryptedData.length + encryptionParts.checksum.length; return 4 + arrayLengths + (arrayLengths >> 1); } /** * Build a printable string from the encrypted parts * * @param encryptionParts Parts to be printed * @return Printable string of the encrypted parts */ private String makePrintableStringFromEncryptionParts(final EncryptionParts encryptionParts) { Base64.Encoder b64Encoder = Base64.getEncoder().withoutPadding(); StringBuilder myStringBuilder = new StringBuilder(calculateStringBuilderCapacityForEncryptionParts(encryptionParts)); myStringBuilder.append(Byte.toString(encryptionParts.formatId)); myStringBuilder.append(PARTS_SEPARATOR); myStringBuilder.append(b64Encoder.encodeToString(encryptionParts.iv)); myStringBuilder.append(PARTS_SEPARATOR); myStringBuilder.append(b64Encoder.encodeToString(encryptionParts.encryptedData)); myStringBuilder.append(PARTS_SEPARATOR); myStringBuilder.append(b64Encoder.encodeToString(encryptionParts.checksum)); return myStringBuilder.toString(); } /** * Calculate the HMAC of the encrypted parts * * @param encryptionParts Encrypted parts to calculate the checksum for * @return Checksum of the encrypted parts * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private byte[] getChecksumForEncryptionParts(final EncryptionParts encryptionParts, final byte[] subjectBytes) throws InvalidKeyException, NoSuchAlgorithmException { final Mac hmac = getHMACInstance(); if (encryptionParts.formatId >= 5) hmac.init(getSecretKeySpecForHMACDependingOnSubject(subjectBytes)); else hmac.init(getDefaultSecretKeySpecForHMAC()); hmac.update(encryptionParts.formatId); hmac.update(encryptionParts.iv); return hmac.doFinal(encryptionParts.encryptedData); } /** * Check the checksum of the encrypted parts that have been read * * @param encryptionParts Parts to be checked * @throws DataIntegrityException if the HMAC of the parts is not correct * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private void checkChecksumForEncryptionParts(final EncryptionParts encryptionParts, final byte[] subjectBytes) throws DataIntegrityException, InvalidKeyException, NoSuchAlgorithmException { final byte[] calculatedChecksum = getChecksumForEncryptionParts(encryptionParts, subjectBytes); if (!SafeArrays.constantTimeEquals(calculatedChecksum, encryptionParts.checksum)) throw new DataIntegrityException("Checksum does not match data"); } private EncryptionParts rawDataEncryption(final String sourceString, final byte[] subjectBytes) throws BadPaddingException, IllegalArgumentException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { EncryptionParts result = new EncryptionParts(); // Set format id result.formatId = FORMAT_ID_MAX; final byte[] sourceBytes = sourceString.getBytes(STRING_ENCODING_FOR_DATA); final String encryptionSpecification = ENCRYPTION_SPECIFICATION[result.formatId]; final Cipher aesCipher = Cipher.getInstance(encryptionSpecification); // Ensure that blinded array needs at least 2 AES blocks, so the length of the encrypted data // can not be inferred to be no longer than block size - 3 bytes (= 13 bytes for AES). final byte[] unpaddedEncodedStringBytes = ByteArrayBlinding.buildBlindedByteArray(sourceBytes, aesCipher.getBlockSize() + 1); Arrays.fill(sourceBytes, (byte) 0); final byte[] paddedEncodedStringBytes = RandomPadding.addPadding(unpaddedEncodedStringBytes, aesCipher.getBlockSize()); Arrays.fill(unpaddedEncodedStringBytes, (byte) 0); // Get a random iv result.iv = new byte[aesCipher.getBlockSize()]; getSecureRandomInstance().nextBytes(result.iv); final SecureSecretKeySpec encryptionKey = getSecretKeySpecForEncryptionDependingOnSubject(subjectBytes); // Encrypt the source string with the iv aesCipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(result.iv)); result.encryptedData = aesCipher.doFinal(paddedEncodedStringBytes); Arrays.fill(paddedEncodedStringBytes, (byte) 0); encryptionKey.close(); return result; } /** * Get HMAC value of a byte array * * @param key The key for the HMAC * @param data The data to be hashed * @return HMAC value of the specified data with specified key * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private byte[] getHmacValueForBytes(final byte[] key, final byte[] data) throws InvalidKeyException, NoSuchAlgorithmException { final Mac hmac = getHMACInstance(); byte[] result = null; try (SecureSecretKeySpec hmacKey = new SecureSecretKeySpec(key, HMAC_256_ALGORITHM_NAME)) { hmac.init(hmacKey); result = hmac.doFinal(data); } catch (final Exception e) { throw e; // Rethrow any exception. hmacKey will have been closed by try-with-resources. } return result; } /** * Set the keys of this instance from a key file and a HMAC key * * @param hmacKey HMAC key to be used * @param keyFile Key file to be used * @throws InvalidKeyException if the key is not valid for the HMAC algorithm (must never happen) * @throws IOException if there is an error reading the key file * @throws NoSuchAlgorithmException if there is no HMAC-256 algorithm (must never happen) */ private void setKeysFromKeyAndFile(final byte[] hmacKey, final Path keyFile) throws InvalidKeyException, IOException, NoSuchAlgorithmException { final byte[] hmacOfKeyFile = getHmacValueForBytes(hmacKey, Files.readAllBytes(keyFile)); // 1. half of file HMAC is used as the encryption key of this instance byte[] keyPart = Arrays.copyOfRange(hmacOfKeyFile, 0, 16); this.m_EncryptionKey = new ProtectedByteArray(keyPart); Arrays.fill(keyPart, (byte) 0); // 2. half of file HMAC is used as the HMAC key of this instance keyPart = Arrays.copyOfRange(hmacOfKeyFile, 16, 32); Arrays.fill(hmacOfKeyFile, (byte) 0); this.m_HMACKey = new ProtectedByteArray(keyPart); Arrays.fill(keyPart, (byte) 0); } /* * Public methods */ public FileAndKeyEncryption(final byte[] hmacKey, final String keyFilePath) throws IllegalArgumentException, InvalidKeyException, IOException, NoSuchAlgorithmException { checkHMACKey(hmacKey); final Path keyFile = Paths.get(keyFilePath); checkKeyFileSize(keyFile); setKeysFromKeyAndFile(hmacKey, keyFile); } public String encryptData(final String stringToEncrypt, final String subject) throws BadPaddingException, IllegalArgumentException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { final byte[] subjectBytes = subject.getBytes(STRING_ENCODING_FOR_DATA); EncryptionParts encryptionParts = rawDataEncryption(stringToEncrypt, subjectBytes); encryptionParts.checksum = getChecksumForEncryptionParts(encryptionParts, subjectBytes); String result = makePrintableStringFromEncryptionParts(encryptionParts); encryptionParts.zap(); return result; } public String encryptData(final String stringToEncrypt) throws BadPaddingException, IllegalArgumentException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { return encryptData(stringToEncrypt, ""); } public String decryptData(final String stringToDecrypt, final String subject) throws BadPaddingException, DataIntegrityException, IllegalArgumentException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { final byte[] subjectBytes = subject.getBytes(STRING_ENCODING_FOR_DATA); final EncryptionParts encryptionParts = getPartsFromPrintableString(stringToDecrypt); checkChecksumForEncryptionParts(encryptionParts, subjectBytes); final String result = rawDataDecryption(encryptionParts, subjectBytes); encryptionParts.zap(); return result; } public String decryptData(final String stringToDecrypt) throws BadPaddingException, DataIntegrityException, IllegalArgumentException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException { return decryptData(stringToDecrypt, ""); } /* * Method for AutoCloseable interface */ /** * Secure deletion of keys * <p> * This method is idempotent and never throws an exception. * </p> */ @Override public void close() { this.m_EncryptionKey.close(); this.m_HMACKey.close(); } }
package de.bitdroid.flooding.ods; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import com.google.android.gms.gcm.GoogleCloudMessaging; import de.bitdroid.flooding.R; import de.bitdroid.flooding.utils.Log; final class GcmUtils { private static final String PATH_NOTIFICATIONS = "notifications", PATH_REGISTER = "register", PATH_UNREGISTER = "unregister"; private static final String PARAM_CLIENTID = "regId", PARAM_SOURCE = "source"; private static final String PREFS_NAME = "GcmUtilities"; private static final String PREFS_KEY_CLIENTID = "clientId", PREFS_KEY_APP_VERSION = "appVersion"; static void registerSource(Context context, OdsSource source) throws GcmException { sourceRegistrationHelper(context, source, true); } static void unregisterSource(Context context, OdsSource source) throws GcmException { sourceRegistrationHelper(context, source, false); } private static void sourceRegistrationHelper( Context context, OdsSource source, boolean register) throws GcmException { if (context == null || source == null) throw new NullPointerException("params cannot be null"); try { // register with google String clientId = getClientId(context); if (clientId == null) { clientId = GoogleCloudMessaging .getInstance(context) .register(getSenderId(context)); SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putString(PREFS_KEY_CLIENTID, clientId); editor.putInt(PREFS_KEY_APP_VERSION, getAppVersion(context)); editor.commit(); } // register on ods server RestCall.Builder builder = new RestCall.Builder( RestCall.RequestType.POST, OdsSourceManager.getInstance(context).getOdsServerName()) .parameter(PARAM_CLIENTID, clientId) .parameter(PARAM_SOURCE, source.getSourceId()) .path(PATH_NOTIFICATIONS); if (register) builder.path(PATH_REGISTER); else builder.path(PATH_UNREGISTER); builder.build().execute(); } catch (IOException io) { Log.warning(android.util.Log.getStackTraceString(io)); throw new GcmException(io); } catch (RestException re) { Log.warning(android.util.Log.getStackTraceString(re)); throw new GcmException(re); } SharedPreferences.Editor editor = getSharedPreferences(context).edit(); if (register) editor.putString(source.toString(), ""); else { SharedPreferences prefs = getSharedPreferences(context); if (prefs.getAll().size() == 2) editor.clear(); else editor.remove(source.toString()); } editor.commit(); } static boolean isSourceRegistered(Context context, OdsSource source) { if (context == null || source == null) throw new NullPointerException("params cannot be null"); return getSharedPreferences(context).contains(source.toString()); } static Set<OdsSource> getRegisteredSources(Context context) { Set<OdsSource> sources = new HashSet<OdsSource>(); Map<String,?> values = getSharedPreferences(context).getAll(); for (String key : values.keySet()) { if (key.equals(PREFS_KEY_CLIENTID) || key.equals(PREFS_KEY_APP_VERSION)) continue; sources.add(OdsSource.fromString(key)); } return sources; } private static SharedPreferences getSharedPreferences(Context context) { return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } private static String getSenderId(Context context) { return context.getString(R.string.GOOGLE_API_KEY); } private static String getClientId(Context context) { SharedPreferences prefs = getSharedPreferences(context); int savedVersion = prefs.getInt(PREFS_KEY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (savedVersion < currentVersion) return null; return prefs.getString(PREFS_KEY_CLIENTID, null); } private static int getAppVersion(Context context) { try { PackageInfo info = context .getPackageManager() .getPackageInfo(context.getPackageName(), 0); return info.versionCode; } catch (NameNotFoundException nnfe) { throw new RuntimeException(nnfe); } } private GcmUtils() { } }
package de.kisi.android; import java.util.List; import org.json.JSONArray; import com.manavo.rest.RestCallback; import de.kisi.android.model.Lock; import de.kisi.android.model.Place; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class PlaceViewFragment extends Fragment { private RelativeLayout layout; private final long delay = 5000; static PlaceViewFragment newInstance(int index) { // Fragments must not have a custom constructor PlaceViewFragment f = new PlaceViewFragment(); Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } int index = getArguments().getInt("index"); final Place l = ((KisiMain)getActivity()).locations.valueAt(index); layout = (RelativeLayout) inflater.inflate(R.layout.locationthreedoors, container, false); if ( l.getLocks() == null ) { KisiApi api = new KisiApi(this.getActivity()); api.setCallback(new RestCallback() { public void success(Object obj) { JSONArray data = (JSONArray)obj; l.setLocks(data); setupButtons(l.getLocks()); } }); api.setLoadingMessage(null); api.get("places/" + String.valueOf(l.getId()) + "/locks"); } else { setupButtons(l.getLocks()); } return layout; } public void setupButtons(List<Lock> locks) { int[] buttons = {R.id.buttonThreeDoorOne, R.id.buttonThreeDoorTwo, R.id.buttonThreeDoorThree}; Typeface font = Typeface.createFromAsset(getActivity().getApplicationContext().getAssets(),"Roboto-Light.ttf"); int i = 0; for ( final Lock lock : locks ) { if ( i >= buttons.length ) { Log.d("waring", "more locks then buttons!"); break; } final Button button = (Button) layout.findViewById(buttons[i]); // ToDo localize? button.setText("Unlock"+ "\n"+lock.getName()); button.setVisibility(View.VISIBLE); i++; button.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Log.d("pressed", "opening door " + String.valueOf(lock.getName())); KisiApi api = new KisiApi(getActivity()); api.setCallback(new RestCallback() { public void success(Object obj) { Toast.makeText(getActivity(), "Lock was opened successfully", Toast.LENGTH_LONG).show(); //change button design buttonToUnlock(button); } }); api.setLoadingMessage("Opening lock..."); api.post("places/" + String.valueOf(lock.getPlaceId()) + "/locks/" + String.valueOf(lock.getId()) + "/access" ); } }); } // set unused buttons to gone, so the automatic layout works for ( ; i < buttons.length; i++) { Button button = (Button) layout.findViewById(buttons[i]); button.setVisibility(View.GONE); } } public void buttonToUnlock(Button button){ //save button design final Drawable currentBackground = button.getBackground(); final String currentString = (String) button.getText(); final Button currentButton = button; //change to unlocked design currentButton.setBackground(getActivity().getResources().getDrawable(R.drawable.unlocked)); // ToDo localize? currentButton.setText("Unlocked!"); currentButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.unlock, 0, 0, 0); //disable click currentButton.setClickable(false); Handler handler = new Handler(); handler.postDelayed(new Runnable(){ public void run(){ //after delay back to old design re-enable click currentButton.setBackground(currentBackground); currentButton.setText(currentString); currentButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.lock, 0, 0, 0); currentButton.setClickable(true); } }, delay); } }
package edu.ucsd.sbrg.bigg; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.SQLException; import java.text.MessageFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; import org.identifiers.registry.RegistryUtilities; import org.sbml.jsbml.CVTerm; import org.sbml.jsbml.Compartment; import org.sbml.jsbml.Model; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBO; import org.sbml.jsbml.Species; import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCModelPlugin; import org.sbml.jsbml.ext.fbc.FBCSpeciesPlugin; import org.sbml.jsbml.ext.fbc.GeneProduct; import org.sbml.jsbml.ext.groups.Group; import org.sbml.jsbml.ext.groups.GroupsConstants; import org.sbml.jsbml.ext.groups.GroupsModelPlugin; import org.sbml.jsbml.util.Pair; import de.zbit.util.Utils; import edu.ucsd.sbrg.util.SBMLUtils; public class BiGGAnnotation { private BiGGDB bigg; private SBMLPolisher polisher; /** * A {@link Logger} for this class. */ public static final transient Logger logger = Logger.getLogger(BiGGAnnotation.class.getName()); /** * Default model notes. */ private String modelNotes = "ModelNotes.html"; protected Map<String, String> replacements; private String documentNotesFile = "SBMLDocumentNotes.html"; /** * @param bigg * @param polisher */ public BiGGAnnotation(BiGGDB bigg, SBMLPolisher polisher) { this.bigg = bigg; this.polisher = polisher; } /** * @param doc * @return * @throws IOException * @throws XMLStreamException */ public SBMLDocument annotate(SBMLDocument doc) throws XMLStreamException, IOException { Model model = doc.getModel(); replacements = new HashMap<>(); if (!doc.isSetModel()) { logger.info( "This SBML document does not contain a model. Nothing to do."); return doc; } annotate(model); if (replacements.containsKey("${title}")) { doc.appendNotes(parseNotes(documentNotesFile, replacements)); } model.appendNotes(parseNotes(modelNotes, replacements)); return doc; } /** * @param model */ public void annotatePublications(Model model) { try { List<Pair<String, String>> publications = bigg.getPublications(model.getId()); if (publications.size() > 0) { String resources[] = new String[publications.size()]; int i = 0; for (Pair<String, String> publication : publications) { resources[i++] = polisher.createURI(publication.getKey(), publication.getValue()); } model.addCVTerm( new CVTerm(CVTerm.Qualifier.BQM_IS_DESCRIBED_BY, resources)); } } catch (SQLException exc) { logger.severe(MessageFormat.format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } } /** * @param model */ public void annotateListOfCompartments(Model model) { for (int i = 0; i < model.getCompartmentCount(); i++) { annotateCompartment(model.getCompartment(i)); } } /** * @param compartment */ private void annotateCompartment(Compartment compartment) { BiGGId biggId = new BiGGId(compartment.getId()); if (bigg.isCompartment(biggId.getAbbreviation())) { compartment.addCVTerm(new CVTerm(CVTerm.Qualifier.BQB_IS, polisher.createURI("bigg.compartment", biggId))); compartment.setSBOTerm(SBO.getCompartment()); // physical compartment if (!compartment.isSetName()) { compartment.setName(bigg.getCompartmentName(biggId)); } } } /** * @param model */ public void annotateListOfSpecies(Model model) { for (int i = 0; i < model.getSpeciesCount(); i++) { annotateSpecies(model.getSpecies(i)); } } /** * @param model */ @SuppressWarnings("deprecation") public void annotateSpecies(Species species) { BiGGId biggId = polisher.extractBiGGId(species.getId()); if (biggId != null) { CVTerm cvTerm = new CVTerm(CVTerm.Qualifier.BQB_IS); if (!species.isSetName() || species.getName().equals( biggId.getAbbreviation() + "_" + biggId.getCompartmentCode())) { try { species.setName(polisher.polishName(bigg.getComponentName(biggId))); } catch (SQLException exc) { logger.severe(MessageFormat.format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } } if (bigg.isMetabolite(biggId.getAbbreviation())) { cvTerm.addResource(polisher.createURI("bigg.metabolite", biggId)); } String type = bigg.getComponentType(biggId); if (type != null) { switch (type) { case "metabolite": species.setSBOTerm(SBO.getSimpleMolecule()); break; case "protein": species.setSBOTerm(SBO.getProtein()); break; default: if (polisher.omitGenericTerms) { species.setSBOTerm(SBO.getMaterialEntity()); } break; } } try { TreeSet<String> linkOut = bigg.getComponentResources(biggId, polisher.includeAnyURI); // convert to set to remove possible duplicates; TreeSet should // respect current order for (String resource : linkOut) { cvTerm.addResource(resource); } } catch (SQLException exc) { logger.severe(MessageFormat.format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } if (cvTerm.getResourceCount() > 0) { species.addCVTerm(cvTerm); } if ((species.getCVTermCount() > 0) && !species.isSetMetaId()) { species.setMetaId(species.getId()); } FBCSpeciesPlugin fbcSpecPlug = (FBCSpeciesPlugin) species.getPlugin(FBCConstants.shortLabel); if (!fbcSpecPlug.isSetChemicalFormula()) { try { fbcSpecPlug.setChemicalFormula( bigg.getChemicalFormula(biggId, species.getModel().getId())); } catch (IllegalArgumentException exc) { logger.severe(MessageFormat.format("Invalid chemical formula: {0}", Utils.getMessage(exc))); } } Integer charge = bigg.getCharge(biggId.getAbbreviation(), species.getModel().getId()); if (species.isSetCharge()) { if ((charge != null) && (charge != species.getCharge())) { logger.warning(MessageFormat.format( "Charge {0,number,integer} in BiGG Models contradicts attribute value {1,number,integer} on species ''{2}''.", charge, species.getCharge(), species.getId())); } species.unsetCharge(); } if ((charge != null) && (charge != 0)) { // If charge is set and charge = 0 -> this can mean it is // only a default! fbcSpecPlug.setCharge(charge); } } } /** * @param model */ public void annotateListOfReactions(Model model) { for (int i = 0; i < model.getReactionCount(); i++) { annotateReaction(model.getReaction(i)); } } /** * @param reaction */ private void annotateReaction(Reaction reaction) { String id = reaction.getId(); if (!reaction.isSetSBOTerm()) { if (bigg.isPseudoreaction(id)) { reaction.setSBOTerm(631); } else if (!polisher.omitGenericTerms) { reaction.setSBOTerm(375); // generic process } } BiGGId biggId = polisher.extractBiGGId(id); CVTerm cvTerm = new CVTerm(CVTerm.Qualifier.BQB_IS); if (biggId != null) { if (bigg.isReaction(reaction.getId())) { cvTerm.addResource(polisher.createURI("bigg.reaction", biggId)); } } if (!reaction.isSetMetaId() && (reaction.getCVTermCount() > 0)) { reaction.setMetaId(id); } if (id.startsWith("R_")) { id = id.substring(2); } String name = bigg.getReactionName(id); if ((name != null) && !name.equals(reaction.getName())) { reaction.setName(polisher.polishName(name)); } SBMLUtils.parseGPR(reaction, bigg.getGeneReactionRule(id, reaction.getModel().getId()), polisher.omitGenericTerms); Model model = reaction.getModel(); List<String> subsystems = bigg.getSubsystems(model.getId(), biggId.getAbbreviation()); if (subsystems.size() > 0) { String groupKey = "GROUP_FOR_NAME"; if (model.getUserObject(groupKey) == null) { model.putUserObject(groupKey, new HashMap<String, Group>()); } @SuppressWarnings("unchecked") Map<String, Group> groupForName = (Map<String, Group>) model.getUserObject(groupKey); for (String subsystem : subsystems) { Group group; if (groupForName.containsKey(subsystem)) { group = groupForName.get(subsystem); } else { GroupsModelPlugin groupsModelPlugin = (GroupsModelPlugin) model.getPlugin(GroupsConstants.shortLabel); group = groupsModelPlugin.createGroup( "g" + (groupsModelPlugin.getGroupCount() + 1)); group.setName(subsystem); group.setKind(Group.Kind.partonomy); group.setSBOTerm(633); // subsystem groupForName.put(subsystem, group); } SBMLUtils.createSubsystemLink(reaction, group.createMember()); } } try { TreeSet<String> linkOut = bigg.getReactionResources(biggId, polisher.includeAnyURI); for (String resource : linkOut) { cvTerm.addResource(resource); } } catch (SQLException exc) { logger.severe(MessageFormat.format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } if (cvTerm.getResourceCount() > 0) { reaction.addCVTerm(cvTerm); } if ((reaction.getCVTermCount() > 0) && !reaction.isSetMetaId()) { reaction.setMetaId(reaction.getId()); } } /** * @param model */ public void annotateListOfGeneProducts(Model model) { if (model.isSetPlugin(FBCConstants.shortLabel)) { FBCModelPlugin fbcModelPlug = (FBCModelPlugin) model.getPlugin(FBCConstants.shortLabel); for (GeneProduct geneProduct : fbcModelPlug.getListOfGeneProducts()) { annotateGeneProduct(geneProduct); } } } /** * @param geneProduct */ private void annotateGeneProduct(GeneProduct geneProduct) { String label = null; String id = geneProduct.getId(); if (geneProduct.isSetLabel() && !geneProduct.getLabel().equalsIgnoreCase("None")) { label = geneProduct.getLabel(); } else if (geneProduct.isSetId()) { label = id; } if (label == null) { return; } // label is stored without "G_" prefix in bigg if (label.startsWith("G_")) { label = label.substring(2); } CVTerm termIs = new CVTerm(CVTerm.Qualifier.BQB_IS); CVTerm termEncodedBy = new CVTerm(CVTerm.Qualifier.BQB_IS_ENCODED_BY); for (String resource : bigg.getGeneIds(label)) { // get Collection part from uri without url prefix - all uris should String collection = RegistryUtilities.getDataCollectionPartFromURI(resource); if (collection == null || collection.length() < 4) { continue; } collection = collection.substring(collection.indexOf("org/") + 4, collection.length() - 1); switch (collection) { case "interpro": case "pdb": case "uniprot": termIs.addResource(resource); break; default: termEncodedBy.addResource(resource); } } if (termIs.getResourceCount() > 0) { geneProduct.addCVTerm(termIs); } if (termEncodedBy.getResourceCount() > 0) { geneProduct.addCVTerm(termEncodedBy); } if (geneProduct.getCVTermCount() > 0) { geneProduct.setMetaId(id); } // we successfully found information by using the id, so this needs to // be the label if (geneProduct.getLabel().equalsIgnoreCase("None")) { geneProduct.setLabel(label); } String geneName = bigg.getGeneName(label); if (geneName != null) { if (geneName.isEmpty()) { logger.fine( MessageFormat.format("No gene name found in BiGG for label ''{0}''.", geneProduct.getName())); } else if (geneProduct.isSetName() && !geneProduct.getName().equals(geneName)) { logger.warning(MessageFormat.format( "Updating gene product name from ''{0}'' to ''{1}''.", geneProduct.getName(), geneName)); } geneProduct.setName(geneName); } } /** * @param model */ public void annotate(Model model) { String organism = bigg.getOrganism(model.getId()); Integer taxonId = bigg.getTaxonId(model.getId()); if (taxonId != null) { model.addCVTerm(new CVTerm(CVTerm.Qualifier.BQB_HAS_TAXON, polisher.createURI("taxonomy", taxonId))); } // Note: date is probably not accurate. // Date date = bigg.getModelCreationDate(model.getId()); // if (date != null) { // History history = model.createHistory(); // history.setCreatedDate(date); String name = polisher.getDocumentTitlePattern(); name = name.replace("[biggId]", model.getId()); name = name.replace("[organism]", organism); replacements.put("${title}", name); replacements.put("${organism}", organism); replacements.put("${bigg_id}", model.getId()); replacements.put("${year}", Integer.toString(Calendar.getInstance().get(Calendar.YEAR))); replacements.put("${bigg.timestamp}", MessageFormat.format("{0,date}", bigg.getBiGGVersion())); replacements.put("${species_table}", ""); // XHTMLBuilder.table(header, // data, "Species", attributes)); if (!model.isSetName()) { model.setName(organism); } if (bigg.isModel(model.getId())) { model.addCVTerm(new CVTerm(CVTerm.Qualifier.BQM_IS, polisher.createURI("bigg.model", model.getId()))); } if (!model.isSetMetaId() && (model.getCVTermCount() > 0)) { model.setMetaId(model.getId()); } annotatePublications(model); annotateListOfCompartments(model); annotateListOfSpecies(model); annotateListOfReactions(model); annotateListOfGeneProducts(model); } /** * @param location * relative path to the resource from this class. * @param replacements * @returnConstants.URL_PREFIX + " like '%%identifiers.org%%'" * @throws IOException */ private String parseNotes(String location, Map<String, String> replacements) throws IOException { StringBuilder sb = new StringBuilder(); try (InputStream is = getClass().getResourceAsStream(location); InputStreamReader isReader = new InputStreamReader( (is != null) ? is : new FileInputStream(new File(location))); BufferedReader br = new BufferedReader(isReader)) { String line; boolean start = false; while (br.ready() && ((line = br.readLine()) != null)) { if (line.matches("\\s*<body.*")) { start = true; } if (!start) { continue; } if (line.matches(".*\\$\\{.*\\}.*")) { for (String key : replacements.keySet()) { line = line.replace(key, replacements.get(key)); } } sb.append(line); sb.append('\n'); if (line.matches("\\s*</body.*")) { break; } } } catch (IOException exc) { throw exc; } return sb.toString(); } /** * @return the modelNotes */ public File getModelNotesFile() { return new File(modelNotes); } /** * @param modelNotes * the modelNotes to set */ public void setModelNotesFile(File modelNotes) { this.modelNotes = modelNotes.getAbsolutePath(); } /** * @param documentNotesFile */ public void setDocumentNotesFile(File documentNotesFile) { this.documentNotesFile = documentNotesFile.getAbsolutePath(); } }
package flounder.devices; import flounder.framework.*; import flounder.logger.*; import org.lwjgl.glfw.*; import static org.lwjgl.glfw.GLFW.*; /** * A module used for the creation, updating and destruction of the keyboard keys. */ public class FlounderKeyboard extends IModule { private static final FlounderKeyboard INSTANCE = new FlounderKeyboard(); public static final String PROFILE_TAB_NAME = "Keyboard"; private int keyboardKeys[]; private int keyboardChar; private GLFWKeyCallback callbackKey; private GLFWCharCallback callbackChar; /** * Creates a new GLFW keyboard manager. */ public FlounderKeyboard() { super(ModuleUpdate.UPDATE_PRE, PROFILE_TAB_NAME, FlounderLogger.class, FlounderDisplay.class); } @Override public void init() { this.keyboardKeys = new int[GLFW_KEY_LAST + 1]; this.keyboardChar = 0; // Sets the keyboards callbacks. glfwSetKeyCallback(FlounderDisplay.getWindow(), callbackKey = new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (key < 0 || key > GLFW_KEY_LAST) { FlounderLogger.error("Invalid action attempted with key " + key); } else { keyboardKeys[key] = action; } } }); glfwSetCharCallback(FlounderDisplay.getWindow(), callbackChar = new GLFWCharCallback() { @Override public void invoke(long window, int codepoint) { keyboardChar = codepoint; } }); } @Override public void update() { } @Override public void profile() { } /** * Gets whether or not a particular key is currently pressed. * <p>GLFW Actions: GLFW_PRESS, GLFW_RELEASE, GLFW_REPEAT</p> * * @param key The key to test. * * @return If the key is currently pressed. */ public static boolean getKey(int key) { return INSTANCE.keyboardKeys[key] != GLFW_RELEASE; } /** * Gets the current user input, ASCII Dec value. * * @return The current keyboard char. */ public static int getKeyboardChar() { return INSTANCE.keyboardChar; } @Override public IModule getInstance() { return INSTANCE; } @Override public void dispose() { callbackKey.free(); callbackChar.free(); } }
package model.experiment.workspace; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.bind.DataBindingException; import javax.xml.bind.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import controller.lambda.HashCoder; import controller.lambda.Predicates; import debug.Debug; import model.experiment.sample.Sample; import model.experiment.sample.SampleFactory; import model.experiment.signalID.SignalIdentifier; @XmlAccessorType(XmlAccessType.NONE) public class Workspace { final static String defaultWorkspace = "workspace.xml"; private static Workspace instance = null; public synchronized static Workspace getInstance() { if (instance == null) { Debug.println( "Opening instance"); instance = open(); } return instance; } public synchronized static Workspace open() { Debug.println( "Opening default workspace [static Workspace.open()]"); Workspace opened = null; try { opened = open(defaultWorkspace); } catch (Exception ignore) { System.out.println( "Could not open " + defaultWorkspace); } if (opened == null) { Debug.println( "There was no workspace file, creating new one"); opened = new Workspace(); opened.save(); } return opened; } public synchronized static Workspace open( String filename) { Debug.println( "Opening workspace [static Workspace.open(" + filename + ")]"); File f = new File(filename); if (!f.exists()) return null; return JAXB.unmarshal( new File(filename), Workspace.class); } public synchronized static void save( String filename, Workspace w) { w.save(filename); } private transient Sample sample; @XmlElement private File samplefile; @XmlElementWrapper(nillable = true) private List<SignalIdentifier> signalIDs; private Workspace() { Debug.println( "Workpsace contructor called"); } public Sample getSample() { if (sample == null) { if (samplefile != null) { Debug.println( "Opening sample xml file " + samplefile); try { sample = SampleFactory.forXML( samplefile .toString()); } catch (DataBindingException e) { Debug.println("Ошибка сбора данных из файла образца: " + e.getLocalizedMessage()); } if (sample == null) { samplefile = null; } } } return sample; } public File getSampleFile() { return samplefile; } public List<SignalIdentifier> getSignalIDs() { if (signalIDs == null) { signalIDs = new ArrayList<>(); } return signalIDs; } public synchronized void save() { save(defaultWorkspace); } public synchronized void save( String filename) { Debug.println( "Сохраняю рабочее пространство " + filename); JAXB.marshal(this, new File(filename)); } public Sample setSample( Sample newsample) { sample = newsample; return sample; } public File setSampleFile( File newsamplefile) { samplefile = newsamplefile; save(); return samplefile; } @Override public boolean equals(Object o) { return Predicates.areEqual(Workspace.class, this, o, Arrays.asList(Workspace::getSampleFile, Workspace::getSignalIDs)); } @Override public int hashCode() { return HashCoder.hashCode(samplefile, signalIDs); } }
package net.somethingdreadful.MAL; import org.apache.commons.lang3.text.WordUtils; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; public class DetailView extends SherlockFragmentActivity implements DetailsBasicFragment.IDetailsBasicAnimeFragment, EpisodesPickerDialogFragment.DialogDismissedListener, MangaProgressDialogFragment.MangaDialogDismissedListener { MALManager mManager; Context context; int recordID; ActionBar actionBar; AnimeRecord mAr; MangaRecord mMr; String recordType; DetailsBasicFragment bfrag; FragmentManager fm; EpisodesPickerDialogFragment epd; MangaProgressDialogFragment mpdf; TextView SynopsisView; TextView RecordTypeView; TextView RecordStatusView; TextView MyStatusView; TextView ProgressCounterView; ImageView CoverImageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_view); bfrag = (DetailsBasicFragment) getSupportFragmentManager().findFragmentById(R.id.DetailsFragment); context = getApplicationContext(); mManager = new MALManager(context); fm = getSupportFragmentManager(); //Get the recordID, passed in from the calling activity recordID = getIntent().getIntExtra("net.somethingdreadful.MAL.recordID", 1); //Get the recordType, also passed from calling activity //Record type will determine how the detail view lays out itself recordType = getIntent().getStringExtra("net.somethingdreadful.MAL.recordType"); // Set up the action bar. actionBar = getSupportActionBar(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayHomeAsUpEnabled(true); // final FrameLayout layout = (FrameLayout) bfrag.getView().findViewById(R.id.backgroundContainer); // ViewTreeObserver viewTreeObserver = layout.getViewTreeObserver(); // if (viewTreeObserver.isAlive()) { // viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { // public void onGlobalLayout() { // layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); // int synopsisOffset = layout.getHeight(); // synopsisOffset -= layout.findViewById(R.id.SynopsisLabel).getHeight(); // System.out.println(synopsisOffset); // LayoutParams params = (LayoutParams) layout.findViewById(R.id.SynopsisLabel).getLayoutParams(); // params.setMargins(0, synopsisOffset, 0, 0); // layout.findViewById(R.id.SynopsisLabel).setLayoutParams(params); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_detail_view, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_SetWatched: showProgressDialog(); break; case R.id.SetStatus_InProgress: setStatus(1); break; case R.id.SetStatus_Complete: setStatus(2); break; case R.id.SetStatus_OnHold: setStatus(3); break; case R.id.SetStatus_Dropped: setStatus(4); break; case R.id.SetStatus_Planned: setStatus(5); break; } return true; } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); if("anime".equals(recordType)) { if (mAr.getDirty() == 1) { writeDetails(mAr); } } else { if (mMr.getDirty() == 1) { writeDetails(mMr); } } } //Called after the basic fragment is finished it's setup, populate data into it public void basicFragmentReady() { CoverImageView = (ImageView) bfrag.getView().findViewById(R.id.detailCoverImage); SynopsisView = (TextView) bfrag.getView().findViewById(R.id.Synopsis); RecordStatusView = (TextView) bfrag.getView().findViewById(R.id.itemStatusContent); RecordTypeView = (TextView) bfrag.getView().findViewById(R.id.itemTypeContent); MyStatusView = (TextView) bfrag.getView().findViewById(R.id.itemMyStatusContent); ProgressCounterView = (TextView) bfrag.getView().findViewById(R.id.itemProgressCounterContent); getDetails(recordID); } public void getDetails(int id) { new getDetailsTask().execute(); } public void showProgressDialog() // Just a function to keep logic out of the switch statement { if ("anime".equals(recordType)) { showEpisodesWatchedDialog(); } else { showMangaProgressDialog(); } } public void showEpisodesWatchedDialog() { //Standard code for setting up a dialog fragment //Note we use setStyle to change the theme, the default light styled dialog didn't look good so we use the dark dialog epd = new EpisodesPickerDialogFragment(); epd.setStyle(DialogFragment.STYLE_NORMAL, R.style.Theme_Sherlock_Dialog); epd.show(fm, "fragment_EditEpisodesWatchedDialog"); } public void showMangaProgressDialog() //TODO Create MangaProgressFragment, will have both chapter and volume pickers { //Standard code for setting up a dialog fragment // Toast.makeText(context, "TODO: Make a MangaProgressFragment", Toast.LENGTH_SHORT).show(); mpdf = new MangaProgressDialogFragment(); mpdf.setStyle(DialogFragment.STYLE_NORMAL, R.style.Theme_Sherlock_Dialog); mpdf.show(fm, "fragment_EditMangaProgressDialog"); } public class getDetailsTask extends AsyncTask<Void, Boolean, GenericMALRecord> { int mID; MALManager mmManager; ActionBar bar; ImageDownloader imageDownloader = new ImageDownloader(context); String internalType; @Override protected void onPreExecute() { mID = recordID; mmManager = mManager; internalType = recordType; } @Override protected GenericMALRecord doInBackground(Void... arg0) { if ("anime".equals(internalType)) { mAr = mmManager.getAnimeRecordFromDB(mID); //Basically I just use publishProgress as an easy way to display info we already have loaded sooner //This way, I can let the database work happen on the background thread and then immediately display it while //the synopsis loads if it hasn't previously been downloaded. publishProgress(true); if (mAr.getSynopsis() == null) { mAr = mmManager.updateWithDetails(mID, mAr); } return mAr; } else { mMr = mmManager.getMangaRecordFromDB(mID); //Basically I just use publishProgress as an easy way to display info we already have loaded sooner //This way, I can let the database work happen on the background thread and then immediately display it while //the synopsis loads if it hasn't previously been downloaded. publishProgress(true); if (mMr.getSynopsis() == null) { mMr = mmManager.updateWithDetails(mID, mMr); } return mMr; } } @Override protected void onProgressUpdate(Boolean... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); if ("anime".equals(internalType)) { actionBar.setTitle(mAr.getName()); CoverImageView.setImageDrawable(new BitmapDrawable(imageDownloader.returnDrawable(context, mAr.getImageUrl()))); RecordStatusView.setText(WordUtils.capitalize(mAr.getRecordStatus())); RecordTypeView.setText(mAr.getRecordType()); MyStatusView.setText(WordUtils.capitalize(mAr.getMyStatus())); if(mAr.getMyStatus().equals(AnimeRecord.STATUS_COMPLETED)) { bfrag.getView().findViewById(R.id.itemProgressCounterLabel).setVisibility(View.GONE); ProgressCounterView.setVisibility(View.GONE); } else { ProgressCounterView.setText(mManager.watchedCounterBuilder(mAr.getPersonalProgress(), Integer.parseInt(mAr.getTotal()))); } } else { actionBar.setTitle(mMr.getName()); CoverImageView.setImageDrawable(new BitmapDrawable(imageDownloader.returnDrawable(context, mMr.getImageUrl()))); RecordStatusView.setText(WordUtils.capitalize(mMr.getRecordStatus())); RecordTypeView.setText(mMr.getRecordType()); MyStatusView.setText(WordUtils.capitalize(mMr.getMyStatus())); if(mMr.getMyStatus().equals(MangaRecord.STATUS_COMPLETED)) { bfrag.getView().findViewById(R.id.itemProgressCounterLabel).setVisibility(View.GONE); ProgressCounterView.setVisibility(View.GONE); } else { ProgressCounterView.setText(mManager.watchedCounterBuilder(mMr.getPersonalProgress(), Integer.parseInt(mMr.getTotal()))); } } } @Override protected void onPostExecute(GenericMALRecord gr) { SynopsisView.setText(gr.getSpannedSynopsis(), TextView.BufferType.SPANNABLE); } } public class writeDetailsTask extends AsyncTask<GenericMALRecord, Void, Boolean> { MALManager internalManager; GenericMALRecord internalGr; String internalType; @Override protected void onPreExecute() { internalManager = mManager; internalType = recordType; } @Override protected Boolean doInBackground(GenericMALRecord... gr) { boolean result; if ("anime".equals(internalType)) { internalManager.saveItem((AnimeRecord) gr[0], false); result = internalManager.writeDetailsToMAL(gr[0], internalManager.TYPE_ANIME); } else { internalManager.saveItem((MangaRecord) gr[0], false); result = internalManager.writeDetailsToMAL(gr[0], internalManager.TYPE_MANGA); } if (result == true) { gr[0].setDirty(gr[0].CLEAN); if ("anime".equals(internalType)) { internalManager.saveItem((AnimeRecord) gr[0], false); } else { internalManager.saveItem((MangaRecord) gr[0], false); } } return result; } } //Dialog returns new value, do something with it public void onDialogDismissed(int newValue) { if ("anime".equals(recordType)) { if (newValue == mAr.getPersonalProgress()) { } else { if (Integer.parseInt(mAr.getTotal()) != 0) { if (newValue == Integer.parseInt(mAr.getTotal())) { mAr.setMyStatus(mAr.STATUS_COMPLETED); } if (newValue == 0) { mAr.setMyStatus(mAr.STATUS_PLANTOWATCH); } } mAr.setEpisodesWatched(newValue); mAr.setDirty(mAr.DIRTY); ProgressCounterView.setText(mManager.watchedCounterBuilder(newValue, Integer.parseInt(mAr.getTotal()))); } } } //Create new write task and run it public void writeDetails(GenericMALRecord gr) { new writeDetailsTask().execute(gr); } public void setStatus(int pickValue) { if ("anime".equals(recordType)) { switch (pickValue) { case 1: setAnimeStatus(mAr.STATUS_WATCHING); break; case 2: setAnimeStatus(mAr.STATUS_COMPLETED); break; case 3: setAnimeStatus(mAr.STATUS_ONHOLD); break; case 4: setAnimeStatus(mAr.STATUS_DROPPED); break; case 5: setAnimeStatus(mAr.STATUS_PLANTOWATCH); break; } } else { switch (pickValue) { case 1: setMangaStatus(mMr.STATUS_WATCHING); break; case 2: setMangaStatus(mMr.STATUS_COMPLETED); break; case 3: setMangaStatus(mMr.STATUS_ONHOLD); break; case 4: setMangaStatus(mMr.STATUS_DROPPED); break; case 5: setMangaStatus(mMr.STATUS_PLANTOWATCH); break; } } } public void setAnimeStatus(String status) { mAr.setMyStatus(status); mAr.setDirty(mAr.DIRTY); MyStatusView.setText(WordUtils.capitalize(status)); } public void setMangaStatus(String status) { mMr.setMyStatus(status); mMr.setDirty(mAr.DIRTY); MyStatusView.setText(WordUtils.capitalize(status)); } public void onMangaDialogDismissed(int newChapterValue, int newVolumeValue) { if ("manga".equals(recordType)) { if (newChapterValue == mMr.getPersonalProgress()) { } else { if (Integer.parseInt(mMr.getTotal()) != 0) { if (newChapterValue == Integer.parseInt(mMr.getTotal())) { mMr.setMyStatus(mMr.STATUS_COMPLETED); } if (newChapterValue == 0) { mMr.setMyStatus(mMr.STATUS_PLANTOWATCH); } } mMr.setPersonalProgress(newChapterValue); mMr.setDirty(mMr.DIRTY); ProgressCounterView.setText(mManager.watchedCounterBuilder(newChapterValue, Integer.parseInt(mMr.getTotal()))); } if (newVolumeValue == mMr.getVolumeProgress()) { } else { mMr.setVolumesRead(newVolumeValue); mMr.setDirty(mMr.DIRTY); } } } }
package nl.b3p.viewer.config.app; import java.util.*; import javax.persistence.*; import javax.servlet.http.HttpServletRequest; import nl.b3p.viewer.config.security.Authorizations; import nl.b3p.viewer.config.security.User; import nl.b3p.viewer.config.services.BoundingBox; import nl.b3p.viewer.config.services.GeoService; import org.apache.commons.beanutils.BeanUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @Entity @Table( uniqueConstraints= @UniqueConstraint(columnNames={"name", "version"}) ) public class Application { @Id private Long id; @Basic(optional=false) private String name; @Column(length=30) private String version; @Lob private String layout; @ElementCollection @JoinTable(joinColumns=@JoinColumn(name="application")) @Lob @MapKeyColumn(columnDefinition="varchar2(255)") private Map<String,String> details = new HashMap<String,String>(); @ManyToOne private User owner; @Embedded @AttributeOverrides({ @AttributeOverride(name = "crs.name", column = @Column(name="start_crs")), @AttributeOverride(name = "minx", column = @Column(name="start_minx")), @AttributeOverride(name = "maxx", column = @Column(name="start_maxx")), @AttributeOverride(name = "miny", column = @Column(name="start_miny")), @AttributeOverride(name = "maxy", column = @Column(name="start_maxy")) }) private BoundingBox startExtent; @Embedded @AttributeOverrides({ @AttributeOverride(name = "crs.name", column = @Column(name="max_crs")), @AttributeOverride(name = "minx", column = @Column(name="max_minx")), @AttributeOverride(name = "maxx", column = @Column(name="max_maxx")), @AttributeOverride(name = "miny", column = @Column(name="max_miny")), @AttributeOverride(name = "maxy", column = @Column(name="max_maxy")) }) private BoundingBox maxExtent; private boolean authenticatedRequired ; @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY) private Level root; @OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, mappedBy="application") private Set<ConfiguredComponent> components = new HashSet<ConfiguredComponent>(); @Basic(optional=false) @Temporal(TemporalType.TIMESTAMP) private Date authorizationsModified = new Date(); // <editor-fold defaultstate="collapsed" desc="getters and setters"> public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getLayout() { return layout; } public void setLayout(String layout) { this.layout = layout; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } public boolean isAuthenticatedRequired() { return authenticatedRequired; } public void setAuthenticatedRequired(boolean authenticatedRequired) { this.authenticatedRequired = authenticatedRequired; } public Set<ConfiguredComponent> getComponents() { return components; } public void setComponents(Set<ConfiguredComponent> components) { this.components = components; } public BoundingBox getMaxExtent() { return maxExtent; } public void setMaxExtent(BoundingBox maxExtent) { this.maxExtent = maxExtent; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public Level getRoot() { return root; } public void setRoot(Level root) { this.root = root; } public BoundingBox getStartExtent() { return startExtent; } public void setStartExtent(BoundingBox startExtent) { this.startExtent = startExtent; } public Date getAuthorizationsModified() { return authorizationsModified; } public void setAuthorizationsModified(Date authorizationsModified) { this.authorizationsModified = authorizationsModified; } //</editor-fold> public String getNameWithVersion() { String n = getName(); if(getVersion() != null) { n += " v" + getVersion(); } return n; } public static class TreeCache { List<Level> levels; Map<Level,List<Level>> childrenByParent; List<ApplicationLayer> applicationLayers; public List<ApplicationLayer> getApplicationLayers() { return applicationLayers; } public List<Level> getChildren(Level l) { List<Level> children = childrenByParent.get(l); if(children == null) { return Collections.EMPTY_LIST; } else { return children; } } public List<Level> getLevels() { return levels; } } @Transient private TreeCache treeCache; public TreeCache loadTreeCache() { if(treeCache == null) { // XXX Oracle specific, use recursive CTE for other dialects // Retrieve level tree structure in single query treeCache = new TreeCache(); treeCache.levels = Stripersist.getEntityManager().createNativeQuery( "select * from level_ start with id = :rootId connect by parent = prior id", Level.class) .setParameter("rootId", root.getId()) .getResultList(); // Prevent n+1 queries for each level Stripersist.getEntityManager().createQuery("from Level l " + "left join fetch l.layers " + "where l in (:levels) ") .setParameter("levels", treeCache.levels) .getResultList(); treeCache.childrenByParent = new HashMap(); treeCache.applicationLayers = new ArrayList(); for(Level l: treeCache.levels) { treeCache.applicationLayers.addAll(l.getLayers()); if(l.getParent() != null) { List<Level> parentChildren = treeCache.childrenByParent.get(l.getParent()); if(parentChildren == null) { parentChildren = new ArrayList<Level>(); treeCache.childrenByParent.put(l.getParent(), parentChildren); } parentChildren.add(l); } } } return treeCache; } public void authorizationsModified() { authorizationsModified = new Date(); } /** * Create a JSON representation for use in browser to start this application * @return */ public String toJSON(HttpServletRequest request) throws JSONException { JSONObject o = new JSONObject(); o.put("id", id); o.put("name", name); if(layout != null) { o.put("layout", new JSONObject(layout)); } JSONObject d = new JSONObject(); o.put("details", d); for(Map.Entry<String,String> e: details.entrySet()) { d.put(e.getKey(), e.getValue()); } if(startExtent != null) { o.put("startExtent", startExtent.toJSONObject()); } if(maxExtent != null) { o.put("maxExtent", maxExtent.toJSONObject()); } /* TODO check readers */ if(root != null) { o.put("rootLevel", root.getId().toString()); loadTreeCache(); // Prevent n+1 queries for each level Stripersist.getEntityManager().createQuery("from Level l " + "left join fetch l.documents " + "where l in (:levels) ") .setParameter("levels", treeCache.levels) .getResultList(); if(!treeCache.applicationLayers.isEmpty()) { // Prevent n+1 queries for each ApplicationLayer Stripersist.getEntityManager().createQuery("from ApplicationLayer al " + "left join fetch al.details " + "where al in (:alayers) ") .setParameter("alayers", treeCache.applicationLayers) .getResultList(); } JSONObject levels = new JSONObject(); o.put("levels", levels); JSONObject appLayers = new JSONObject(); o.put("appLayers", appLayers); JSONArray selectedContent = new JSONArray(); o.put("selectedContent", selectedContent); List selectedObjects = new ArrayList(); walkAppTreeForJSON(levels, appLayers, selectedObjects, root, false, request); Collections.sort(selectedObjects, new Comparator() { @Override public int compare(Object lhs, Object rhs) { Integer lhsIndex, rhsIndex; if(lhs instanceof Level) { lhsIndex = ((Level)lhs).getSelectedIndex(); } else { lhsIndex = ((ApplicationLayer)lhs).getSelectedIndex(); } if(rhs instanceof Level) { rhsIndex = ((Level)rhs).getSelectedIndex(); } else { rhsIndex = ((ApplicationLayer)rhs).getSelectedIndex(); } return lhsIndex.compareTo(rhsIndex); } }); for(Object obj: selectedObjects) { JSONObject j = new JSONObject(); if(obj instanceof Level) { j.put("type", "level"); j.put("id", ((Level)obj).getId().toString()); } else { j.put("type", "appLayer"); j.put("id", ((ApplicationLayer)obj).getId().toString()); } selectedContent.put(j); } Map<GeoService,Set<String>> usedLayersByService = new HashMap<GeoService,Set<String>>(); visitLevelForUsedServicesLayers(root, usedLayersByService, request); if(!usedLayersByService.isEmpty()) { JSONObject services = new JSONObject(); o.put("services", services); for(Map.Entry<GeoService,Set<String>> entry: usedLayersByService.entrySet()) { GeoService gs = entry.getKey(); Set<String> usedLayers = entry.getValue(); services.put(gs.getId().toString(), gs.toJSONObject(false, usedLayers)); } } } // Prevent n+1 query for ConfiguredComponent.details Stripersist.getEntityManager().createQuery( "from ConfiguredComponent cc left join fetch cc.details where application = :this") .setParameter("this", this) .getResultList(); JSONObject c = new JSONObject(); o.put("components", c); for(ConfiguredComponent comp: components) { if(Authorizations.isConfiguredComponentAuthorized(comp, request)) { c.put(comp.getName(), comp.toJSON()); } } return o.toString(4); } private void walkAppTreeForJSON(JSONObject levels, JSONObject appLayers, List selectedContent, Level l, boolean parentIsBackground, HttpServletRequest request) throws JSONException { if(!Authorizations.isLevelReadAuthorized(this, l, request)) { System.out.printf("Level %d %s unauthorized\n", l.getId(), l.getName()); return; } JSONObject o = l.toJSONObject(false, this, request); o.put("background", l.isBackground() || parentIsBackground); levels.put(l.getId().toString(), o); if(l.getSelectedIndex() != null) { selectedContent.add(l); } for(ApplicationLayer al: l.getLayers()) { if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) { //System.out.printf("Application layer %d (service #%s %s layer %s) in level %d %s unauthorized\n", al.getId(), al.getService().getId(), al.getService().getName(), al.getLayerName(), l.getId(), l.getName()); continue; } JSONObject p = al.toJSONObject(); p.put("background", l.isBackground() || parentIsBackground); p.put("editAuthorized", Authorizations.isAppLayerWriteAuthorized(this, al, request)); appLayers.put(al.getId().toString(), p); if(al.getSelectedIndex() != null) { selectedContent.add(al); } } List<Level> children = treeCache.childrenByParent.get(l); if(children != null) { JSONArray jsonChildren = new JSONArray(); o.put("children", jsonChildren); for(Level child: children) { jsonChildren.put(child.getId().toString()); walkAppTreeForJSON(levels, appLayers, selectedContent, child, l.isBackground(), request); } } } private void visitLevelForUsedServicesLayers(Level l, Map<GeoService,Set<String>> usedLayersByService, HttpServletRequest request) { if(!Authorizations.isLevelReadAuthorized(this, l, request)) { return; } for(ApplicationLayer al: l.getLayers()) { if(!Authorizations.isAppLayerReadAuthorized(this, al, request)) { continue; } GeoService gs = al.getService(); Set<String> usedLayers = usedLayersByService.get(gs); if(usedLayers == null) { usedLayers = new HashSet<String>(); usedLayersByService.put(gs, usedLayers); } usedLayers.add(al.getLayerName()); } List<Level> children = treeCache.childrenByParent.get(l); if(children != null) { for(Level child: children) { visitLevelForUsedServicesLayers(child, usedLayersByService, request); } } } public Boolean isMashup(){ if(this.getDetails().containsKey("isMashup")){ String mashupValue = this.getDetails().get("isMashup"); Boolean mashup = Boolean.valueOf(mashupValue); return mashup; }else{ return false; } } public Application deepCopy() throws Exception { Application copy = (Application) BeanUtils.cloneBean(this); copy.setId(null); // user reference is not deep copied, of course copy.setDetails(new HashMap<String,String>(details)); if(startExtent != null) { copy.setStartExtent(startExtent.clone()); } if(maxExtent != null) { copy.setMaxExtent(maxExtent.clone()); } copy.setComponents(new HashSet<ConfiguredComponent>()); for(ConfiguredComponent cc: components) { copy.getComponents().add(cc.deepCopy(copy)); } if(root != null) { copy.setRoot(root.deepCopy(null)); } return copy; } public void setMaxWidth(String maxWidth) { this.details.put("maxWidth", maxWidth); } public void setMaxHeight(String maxHeight) { this.details.put("maxHeight", maxHeight); } }
package org.biojava.bio.gui.glyph; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; /** * A Glyph that paints an arrow shape within the bounds. The * <code>setDirection</code> method allows the decision of the direction, to * which the arrow points. * * @author Mark Southern * @author <a href="mailto:andreas.draeger@uni-tuebingen.de">Andreas Dr&auml;ger</a> * @since 1.5 */ public class ArrowGlyph implements Glyph { private Paint fillPaint; private Paint outerPaint; private Rectangle2D.Float bounds; private Shape arrowShape; /** * Creates a new <code>ArrowGlyph</code>, which is filled with the color * blue by default. */ public ArrowGlyph() { this(Color.BLUE, Color.BLACK); } /** * Creates a new <code>ArrowGlyph</code>, which is filled with the given * color. * * @param fillPaint Paint properties to fill this arrow. * @param outerPaint Paint properties of the outer border of this arrow. */ public ArrowGlyph(Paint fillPaint, Paint outerPaint) { this.fillPaint = fillPaint; this.outerPaint = outerPaint; this.bounds = new Rectangle2D.Float(0, 0, 0, 0); } /** * This constructs an arrow in the given bounds, which is colored blue. * * @param bounds */ public ArrowGlyph(Rectangle2D.Float bounds) { this(bounds, Color.BLUE, Color.BLACK); } /** * Constructor which sets both the size of this arrow and its color. * * @param bounds * @param fillPaint */ public ArrowGlyph(Rectangle2D.Float bounds, Paint fillPaint, Paint outerPaint) { this(fillPaint, outerPaint); setBounds(bounds); } /* * (non-Javadoc) * * @see org.biojava.bio.gui.glyph.Glyph#getBounds() */ public Rectangle2D.Float getBounds() { return bounds; } /* * (non-Javadoc) * * @see org.biojava.bio.gui.glyph.Glyph#setBounds(java.awt.geom.Rectangle2D.Float) */ public void setBounds(Rectangle2D.Float r) { if (bounds.equals(r)) return; bounds = r; } /** * This method allows you to decide in which direction the arrow has to point. * The definition of directions is equal to the definition of * {@see StrandedFeature}. * * @param direction * A +1 means to the right, -1 to the left an 0 (and any other value) * produces a rectangular shape without arrows at its end. */ public void setDirection(int direction) { float q1 = bounds.height * 0.25F; float q2 = bounds.height * 0.5F; float q3 = bounds.height * 0.75F; float arrowHeadSize = bounds.height; GeneralPath p = new GeneralPath(); switch (direction) { case +1: // to the right if ((bounds.width - arrowHeadSize) > 0) { p.moveTo(bounds.x, bounds.y + q1); p.lineTo(bounds.x + bounds.width - arrowHeadSize, bounds.y + q1); p.lineTo(bounds.x + bounds.width - arrowHeadSize, bounds.y); p.lineTo(bounds.x + bounds.width, bounds.y + q2); p.lineTo(bounds.x + bounds.width - arrowHeadSize, bounds.y + bounds.height); p.lineTo(bounds.x + bounds.width - arrowHeadSize, bounds.y + q3); p.lineTo(bounds.x, bounds.y + q3); } else { p.moveTo(bounds.x, bounds.y); p.lineTo(bounds.x + bounds.width, bounds.y + q2); p.lineTo(bounds.x, bounds.y + bounds.height); } break; case -1: // to the left if ((bounds.width - arrowHeadSize) > 0) { p.moveTo(bounds.x + bounds.width, bounds.y + q1); p.lineTo(bounds.x + arrowHeadSize, bounds.y + q1); p.lineTo(bounds.x + arrowHeadSize, bounds.y); p.lineTo(bounds.x, bounds.y + q2); p.lineTo(bounds.x + arrowHeadSize, bounds.y + bounds.height); p.lineTo(bounds.x + arrowHeadSize, bounds.y + q3); p.lineTo(bounds.x + bounds.width, bounds.y + q3); } else { p.moveTo(bounds.x + bounds.width, bounds.y); p.lineTo(bounds.x + bounds.width, bounds.y + bounds.height); p.lineTo(bounds.x, bounds.y + q2); } break; default: // unknown // we cannot draw an arrow, we should draw a rectangle shape instead. p.moveTo(bounds.x, bounds.y + q1); p.lineTo(bounds.x + bounds.width, bounds.y + q1); p.lineTo(bounds.x + bounds.width, bounds.y + q3); p.lineTo(bounds.x, bounds.y + q3); break; } p.closePath(); arrowShape = p; } public void render(Graphics2D g) { if ((bounds.height > 0) && (bounds.width > 0) && (arrowShape == null)) setDirection(0); if (arrowShape != null) { g.setPaint(fillPaint); g.fill(arrowShape); g.setPaint(outerPaint); g.draw(arrowShape); } } /** * Returns the paint properties of this glyph. * * @return the fillPaint */ public Paint getFillPaint() { return fillPaint; } /** * Allows you to set the paint properties of this glyph. * * @param fillPaint */ public void setFillPaint(Paint fillPaint) { this.fillPaint = fillPaint; } /** * Returns the paint properties of the outer line of this glyph. * * @return the outerPaint */ public Paint getOuterPaint() { return outerPaint; } /** * Allows setting the paint properties of the outer line of this glyph to the * given value. * * @param outerPaint */ public void setOuterPaint(Paint outerPaint) { this.outerPaint = outerPaint; } }
package org.biojava.bio.symbol; import java.util.List; import java.util.ArrayList; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.Feature; import org.biojava.bio.BioException; import org.biojava.utils.ChangeVetoException; /** * Class to perform arbitrary regex-like searches on * any FiniteAlphabet. * <p> * The API is still in flux. * * @author David Huen * @since 1.4 */ public class PatternSearch { private static class MatchState implements Cloneable { private int patternPos = 0; private int symListPos = 1; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException cne) { ////System.err.println("unexpected exception!"); cne.printStackTrace(); } return null; } private void resetPattern() { patternPos = 0; } } /** * Class to describe a regex-like pattern. The pattern * is a list of other patterns or Symbols in the target * FiniteAlphabet. These are added to the list with * addSymbol and addPattern calls. The pattern can be * reiterated a number of times (deafult is once). */ public static class Pattern { private List patternList; private FiniteAlphabet alfa; private int min = 1; private int max = 1; private String label; private SymbolTokenization symToke = null; /** * @param label A String describing the Pattern. * @param alfa The FiniteAlphabet the Pattern is defined over. */ public Pattern(String label, FiniteAlphabet alfa) { this.alfa = alfa; this.label = label; patternList = new ArrayList(); } /** * Add a Symbol to the end of the Pattern. */ public void addSymbol(Symbol sym) throws IllegalAlphabetException { if (!alfa.contains(sym)) throw new IllegalAlphabetException(sym.getName() + " is not in Alphabet " + alfa.getName()); patternList.add(sym); } /** * Add a Pattern to the end of the Pattern. */ public void addPattern(Pattern pattern) throws IllegalAlphabetException { if (alfa != pattern.getAlphabet()) throw new IllegalAlphabetException(pattern.getAlphabet().getName() + " is not compatible with Alphabet " + alfa.getName()); patternList.add(pattern); } public Alphabet getAlphabet() { return alfa; } public int getMin() { return min; } public int getMax() { return max; } public String getLabel() { return label; } /** * Minimum number of times the Pattern is to be matched. */ public void setMin(int min) throws IllegalArgumentException { if (min < 0) throw new IllegalArgumentException("number of repeats must be non-negative."); else this.min = min; } /** * Maximum number of times the Pattern is to be matched. */ public void setMax(int max) { if (max < 0) throw new IllegalArgumentException("number of repeats must be non-negative."); else this.max = max; } private List getPatternList() { return patternList; } public String toString() { try { return toString(Pattern.this); } catch (Exception e) { e.printStackTrace(); return ""; } } private String stringify() throws BioException, IllegalSymbolException { if (symToke == null) symToke = alfa.getTokenization("token"); StringBuffer s = new StringBuffer(); for (int i=0; i < patternList.size(); i++) { Object currElem = patternList.get(i); if (currElem instanceof Symbol) { //System.out.println("symbol is " + ((Symbol) currElem).getName()); s.append(symToke.tokenizeSymbol((Symbol) currElem)); } else if (currElem instanceof Pattern) { s.append(toString((Pattern) currElem)); } } return s.toString(); } private String toString(Pattern p) throws BioException, IllegalSymbolException { StringBuffer s = new StringBuffer(); boolean hasCount = (p.getMin() != 1) || (p.getMax() != 1); boolean needParen = hasCount || (p.getPatternList().size() > 1); if (needParen) s.append('('); s.append(p.stringify()); if (needParen) s.append(')'); if (hasCount) { s.append('{'); s.append(Integer.toString(p.getMin())); s.append(','); s.append(Integer.toString(p.getMax())); s.append('}'); } return s.toString(); } } /** * Attempts to match a pattern starting at specified position in SymbolList. * @param p Pattern to match. * @param sl SymbolList to find match in. * @param pos position to look for match at. */ public static boolean match(Pattern p, SymbolList sl, int pos) { MatchState state = new MatchState(); state.symListPos = pos; return match(p, sl, state); } /** * Annotates the sequence with Features marking where matches to * the specified sequence were encountered. * @param p Pattern to match. * @param seq Sequence to find match in. * @param ft Feature.Template to be used in creating the Feature. */ public static void match(Pattern p, Sequence seq, Feature.Template ft) throws BioException, IllegalAlphabetException, ChangeVetoException { // check that the alphabets are compatible if (p.getAlphabet() != seq.getAlphabet()) throw new IllegalAlphabetException("alphabets are not compatible."); // mark out all hits with a Location object MatchState state = new MatchState(); for (int i=1; i <= seq.length(); i++) { state.symListPos = i; state.resetPattern(); if (match(p, seq, state)) { // add an annotation to mark the site Location loc = new RangeLocation(i, state.symListPos - 1); ft.location = loc; seq.createFeature(ft); } } } /** * Compute the extent from matching the Pattern to the specified position. * @param p Pattern to match. * @param sl SymbolList to find match in. * @param pos position to look for match at. * @return RangeLocation if a match was achieved, null if not. */ public static RangeLocation getMatchRange(Pattern p, SymbolList sl, int pos) { MatchState state = new MatchState(); state.symListPos = pos; if (match(p, sl, state)) { return new RangeLocation(pos, state.symListPos - 1); } else return null; } private static boolean match(Pattern p, SymbolList sl, MatchState state) { //System.out.println("match called with " + p.getLabel() + " " + state.patternPos + " " + state.symListPos); // record own state MatchState myState = (MatchState) state.clone(); // we have switched pattern so we need to rewind the pattern pointer. myState.resetPattern(); // do the required number of prematches (min -1) for (int i = 1; i < p.getMin(); i++) { //System.out.println("aligning required iteration " + i + " of pattern."); if (!matchOnce(p, sl, myState)) return false; // go back to start of pattern again myState.resetPattern(); } // we now attempt to find a single case of a successful for (int i = p.getMin(); i <= p.getMax(); i++) { //System.out.print("aligning iteration " + i + " of pattern: "); if (matchOnce(p, sl, myState)) { //System.out.println("found match!"); // extend matched sequence to all we have matched. state.symListPos = myState.symListPos; // state.patternPos was already incremented prior // to calling this method. return true; } //System.out.println("failed!"); } return false; } /** * matches the pattern once to the SymbolList starting at the * positions specified within the MatchState object for SymbolList * and Pattern. */ private static boolean matchOnce(Pattern p, SymbolList sl, MatchState state) { //System.out.println("matchOnce called with " + p.getLabel() + " " + state.patternPos + " " + state.symListPos); // record own state MatchState myState = (MatchState) state.clone(); // match all symbols till the first Pattern. // ambigs on sl result in immediate failure. List pList = p.getPatternList(); Object currMatchElement = null; // only to suppress compilation error. boolean matchNotFinished; while ((matchNotFinished = (myState.patternPos < pList.size())) && !((currMatchElement = pList.get(myState.patternPos)) instanceof Pattern) ) { //System.out.println("in symbol matching loop."); // no more symbols for matching, pattern fails! if (myState.symListPos > sl.length()) return false; // matching symbols //System.out.println("matching " + ((Symbol) currMatchElement).getName() + " " + sl.symbolAt(myState.symListPos).getName()); if (!matchSymbols((Symbol) currMatchElement, sl.symbolAt(myState.symListPos))) return false; myState.symListPos++; myState.patternPos++; } ////System.out.println("left initial symbols loop. " + myState.symListPos + " " + myState.patternPos); // all available symbols matched. Success! if (!matchNotFinished) { ////System.out.println("no further matching to be done."); state.patternPos = myState.patternPos; state.symListPos = myState.symListPos; return true; } // finished all Symbol matches, do we have a Pattern to match? if (currMatchElement instanceof Pattern) { if (!matchExtend(p, sl, myState)) return false; } // update the MatchState accordingly state.patternPos = myState.patternPos; state.symListPos = myState.symListPos; return true; } /** * extends a match that begins with a Pattern. */ private static boolean matchExtend(Pattern p, SymbolList sl, MatchState state) { //System.out.println("matchExtend called with " + p.getLabel() + " " + state.patternPos + " " + state.symListPos); // save the state MatchState globalState = (MatchState) state.clone(); MatchState patternState = (MatchState) state.clone(); patternState.resetPattern(); // extend the match beginning with the initial Pattern // do the required number of prematches (min -1) Pattern thisP = (Pattern) p.patternList.get(state.patternPos); for (int i = 1; i < thisP.getMin(); i++) { ////System.out.println("matchExtend: prematch iteration " + i + " of pattern."); if (!matchOnce(thisP, sl, patternState)) return false; // go back to start of pattern again patternState.resetPattern(); } // do required terminal matches for (int i = thisP.getMin(); i <= thisP.getMin(); i++) { ////System.out.println("matchExtend: match iteration " + i + " of pattern."); if (!matchOnce(thisP, sl, patternState)) return false; // we have now got a required match for initial pattern done. // if the subsequent extension fails, I may need to add // another match for initial pattern. // advance global match past initial pattern. MatchState tryState = (MatchState) globalState.clone(); tryState.patternPos++; tryState.symListPos = patternState.symListPos; ////System.out.println("extending match. " + globalState.patternPos + " " + globalState.symListPos); if (matchOnce(p, sl, tryState)) { // successful match of rest of pattern! state.symListPos = tryState.symListPos; return true; } // go back to start of pattern again patternState.resetPattern(); } return false; } private static boolean matchSymbols(Symbol source, Symbol target) { // an ambiguous target symbol leads to an immediate mismatch if (!(target instanceof AtomicSymbol)) return false; // is the source ambiguous? if (target instanceof AtomicSymbol) { return (source == target); } else { return source.getMatches().contains(target); } } }
package org.exist.xquery.test; import java.io.IOException; import java.io.StringReader; import java.net.BindException; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.stream.StreamSource; import org.custommonkey.xmlunit.XMLTestCase; import org.exist.StandaloneServer; import org.exist.storage.DBBroker; import org.exist.xmldb.CollectionImpl; import org.exist.xmldb.DatabaseInstanceManager; import org.exist.xmldb.XPathQueryServiceImpl; import org.exist.xquery.XPathException; import org.mortbay.util.MultiException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.CompiledExpression; import org.xmldb.api.base.Database; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceIterator; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import org.xmldb.api.modules.XPathQueryService; import org.xmldb.api.modules.XQueryService; public class XPathQueryTest extends XMLTestCase { private final static String nested = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<test><c></c><b><c><b></b></c></b><b></b><c></c></test>"; private final static String numbers = "<test>" + "<item id='1' type='alphanum'><price>5.6</price><stock>22</stock></item>" + "<item id='2'><price>7.4</price><stock>43</stock></item>" + "<item id='3'><price>18.4</price><stock>5</stock></item>" + "<item id='4'><price>65.54</price><stock>16</stock></item>" + "</test>"; private final static String numbers2 = "<test xmlns=\"http://numbers.org\">" + "<item id='1' type='alphanum'><price>5.6</price><stock>22</stock></item>" + "<item id='2'><price>7.4</price><stock>43</stock></item>" + "<item id='3'><price>18.4</price><stock>5</stock></item>" + "<item id='4'><price>65.54</price><stock>16</stock></item>" + "</test>"; private final static String namespaces = "<test xmlns='http: + " <section>" + " <title>Test Document</title>" + " <c:comment xmlns:c='http: + " </section>" + "</test>"; private final static String strings = "<test>" + "<string>Hello World!</string>" + "<string value='Hello World!'/>" + "<string>Hello</string>" + "</test>"; private final static String nested2 = "<RootElement>" + "<ChildA>" + "<ChildB id=\"2\"/>" + "</ChildA>" + "</RootElement>"; private final static String nested3 = "<test>" + " <a>" + " <t>1</t>" + " <a>" + " <t>2</t>" + " <a>" + " <t>3</t>" + " </a>" + " </a>" + " </a>" + "</test>"; private final static String siblings = "<test>" + " <a> <s>A</s> <n>1</n> </a>" + " <a> <s>Z</s> <n>2</n> </a>" + " <a> <s>B</s> <n>3</n> </a>" + " <a> <s>Z</s> <n>4</n> </a>" + " <a> <s>C</s> <n>5</n> </a>" + " <a> <s>Z</s> <n>6</n> </a>" + "</test>"; private final static String ids = "<!DOCTYPE test [" + "<!ELEMENT test (a | b | c | d)*>" + "<!ATTLIST test xml:space CDATA #IMPLIED>" + "<!ELEMENT a EMPTY>" + "<!ELEMENT b (name)>" + "<!ELEMENT c (name)>" + "<!ELEMENT d EMPTY>" + "<!ATTLIST d ref IDREF #IMPLIED>" + "<!ELEMENT name (#PCDATA)>" + "<!ATTLIST a ref IDREF #IMPLIED>" + "<!ATTLIST b id ID #IMPLIED>" + "<!ATTLIST c xml:id ID #IMPLIED>]>" + "<test xml:space=\"preserve\">" + "<a ref=\"id1\"/>" + "<a ref=\"id1\"/>" + "<d ref=\"id2\"/>" + "<b id=\"id1\"><name>one</name></b>" + "<c xml:id=\" id2 \"><name>two</name></c>" + "</test>"; private final static String date = "<timestamp date=\"2006-04-29+02:00\"/>"; private final static String quotes = "<test><title>&quot;Hello&quot;</title></test>"; private final static String ws = "<test><parent xml:space=\"preserve\"><text> </text><text xml:space=\"default\"> </text></parent></test>"; private final static String self = "<test-self><a>Hello</a><b>World!</b></test-self>"; // Added by Geoff Shuetrim (geoff@galexy.net) to highlight problems with XPath queries of elements called 'xpointer'. private final static String xpointerElementName = "<test><xpointer/></test>"; private static String uri = "xmldb:exist://" + DBBroker.ROOT_COLLECTION; public static void setURI(String collectionURI) { uri = collectionURI; } private static StandaloneServer server = null; private Collection testCollection; private String query; protected void setUp() { if (uri.startsWith("xmldb:exist://localhost")) initServer(); try { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); Collection root = DatabaseManager.getCollection( uri, "admin", null); CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); testCollection = service.createCollection("test"); assertNotNull(testCollection); } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (XMLDBException e) { e.printStackTrace(); } } private void initServer() { try { if (server == null) { server = new StandaloneServer(); if (!server.isStarted()) { try { System.out.println("Starting standalone server..."); String[] args = {}; server.run(args); while (!server.isStarted()) { Thread.sleep(1000); } } catch (MultiException e) { boolean rethrow = true; Iterator i = e.getExceptions().iterator(); while (i.hasNext()) { Exception e0 = (Exception)i.next(); if (e0 instanceof BindException) { System.out.println("A server is running already !"); rethrow = false; break; } } if (rethrow) throw e; } } } } catch(Exception e) { fail(e.getMessage()); } } protected void tearDown() throws Exception { try { if (!((CollectionImpl) testCollection).isRemoteCollection()) { DatabaseInstanceManager dim = (DatabaseInstanceManager) testCollection.getService( "DatabaseInstanceManager", "1.0"); dim.shutdown(); } testCollection = null; System.out.println("tearDown PASSED"); } catch (XMLDBException e) { e.printStackTrace(); fail(e.getMessage()); } } public void testPathExpression() { try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); //Invalid path expression left operand (not a node set). String message = ""; try { queryAndAssert(service, "('a', 'b', 'c')/position()", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue("Exception wanted: " + message, message.indexOf("XPTY0019") > -1); //Undefined context sequence message = ""; try { queryAndAssert(service, "for $a in (<a/>, <b/>, doh, <c/>) return $a", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue("Exception wanted: " + message, message.indexOf("XPDY0002") > -1); message = ""; try { //"1 to 2" is resolved as a (1, 2), i.e. a sequence of *integers* which is *not* a singleton queryAndAssert(service, "let $a := (1, 2, 3) for $b in $a[1 to 2] return $b", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } //No effective boolean value for such a kind of sequence ! assertTrue("Exception wanted: " + message, message.indexOf("FORG0006") >-1); queryAndAssert(service, "let $a := ('a', 'b', 'c') return $a[2 to 2]", 1, null); queryAndAssert(service, "let $a := ('a', 'b', 'c') return $a[(2 to 2)]", 1, null); queryAndAssert(service, "()/position()", 0, null); } catch (XMLDBException e) { fail(e.getMessage()); } } /** test simple queries involving attributes */ public void testAttributes() { ResourceSet result; try { String testDocument = "numbers.xml"; String query; XQueryService service = storeXMLStringAndGetQueryService( testDocument, numbers); query = "/test/item[ @id='1' ]"; result = service.queryResource(testDocument, query); System.out.println("testAttributes 1: ========"); printResult(result); assertEquals("XPath: " + query, 1, result.getSize()); XMLResource resource = (XMLResource)result.getResource(0); Node node = resource.getContentAsDOM(); if (node.getNodeType() == Node.DOCUMENT_NODE) node = node.getFirstChild(); assertEquals("XPath: " + query, "item", node.getNodeName()); query = "/test/item [ @type='alphanum' ]"; result = service.queryResource(testDocument, query); System.out.println("testAttributes 2: ========"); printResult(result); assertEquals("XPath: " + query, 1, result.getSize()); } catch (XMLDBException e) { System.out.println("testAttributes(): XMLDBException: " + e); fail(e.getMessage()); } } public void testStarAxis() { ResourceSet result; try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); result = service.queryResource("numbers.xml", "/*/item"); System.out.println("testStarAxis 1: ========"); printResult(result); assertEquals("XPath: /*/item", 4, result.getSize()); result = service.queryResource("numbers.xml", "/*/*"); assertEquals("XPath: /*/*", 4, result.getSize()); queryResource(service, "nested2.xml", "/RootElement/ChildA/parent::*/ChildA/ChildB", 1); service = storeXMLStringAndGetQueryService("numbers.xml", numbers2); service.setNamespace("n", "http://numbers.org"); queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::*[@id = '3']", 1); queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:item[@id = '3']", 1); queryResource(service, "numbers.xml", "//n:price/parent::n:item[@id = '3']", 1); ResourceSet result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:*/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::*:item/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/../string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:item/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); queryResource(service, "numbers.xml", "for $price in //n:price where $price/parent::*[@id = '3']/n:stock = '5' return $price", 1); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testParentSelfAxis() { try { XQueryService service = storeXMLStringAndGetQueryService("nested2.xml", nested2); queryResource(service, "nested2.xml", "/RootElement/descendant::*/parent::ChildA", 1); queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildB]/parent::RootElement", 0); queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildA]/parent::RootElement", 1); queryResource(service, "nested2.xml", "let $a := ('', 'b', '', '') for $b in $a[.] return <blah>{$b}</blah>", 1); String query = "let $doc := <root><page><a>a</a><b>b</b></page></root>" + "return " + public void bugtestPredicateBUG_wiki_1() throws Exception { String xQuery = "let $dum := <dummy><el>1</el><el>2</el></dummy> return $dum/el[2]"; XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("Predicate bug wiki_1", 1, rs.getSize()); assertEquals("Predicate bug wiki_1", "<el>2</el>", rs.getResource(0).getContent()); } public void testCardinalitySelfBUG_wiki_2() { String xQuery = "let $test := <test><works><employee>a</employee><employee>b</employee></works></test> " +"for $h in $test/works/employee[2] return fn:name($h/self::employee)"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("CardinalitySelfBUG bug wiki_2", 1, rs.getSize()); assertEquals("CardinalitySelfBUG bug wiki_2", "employee", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void bugtestVirtualNodesetBUG_wiki_3() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"let $node := (<c id=\"OK\"><b id=\"cool\"/></c>)" +"/descendant::*/attribute::id return <a>{$node}</a>"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("VirtualNodesetBUG_wiki_3", 1, rs.getSize()); assertEquals("VirtualNodesetBUG_wiki_3", "<a id=\"cool\"/>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void bugtestVirtualNodesetBUG_wiki_4() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"let $node := (<c id=\"OK\">" +"<b id=\"cool\"/></c>)/descendant-or-self::*/child::b " +"return <a>{$node}</a>"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("VirtualNodesetBUG_wiki_4", 1, rs.getSize()); assertEquals("VirtualNodesetBUG_wiki_4", "<a><b id=\"cool\"/></a>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void bugtestVirtualNodesetBUG_wiki_5() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"let $node := (<c id=\"OK\"><b id=\"cool\"/>" +"</c>)/descendant-or-self::*/descendant::b return <a>{$node}</a>"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("VirtualNodesetBUG_wiki_5", 1, rs.getSize()); assertEquals("VirtualNodesetBUG_wiki_5", "<a><b id=\"cool\"/></a>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } // It seems that the document builder receives events that are irrelevant. public void testDocumentBuilderBUG_wiki_6() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"declare function local:test() {let $results := <dummy/>" +"return \"id\" }; " +"<wrapper><string id=\"{local:test()}\"/></wrapper>"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("testDocumentBuilderBUG_wiki_6", 1, rs.getSize()); assertEquals("testDocumentBuilderBUG_wiki_6", "<wrapper><string id=\"id\"/></wrapper>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void testCastInPredicate_wiki_7() { String xQuery = "let $number := 2, $list := (\"a\", \"b\", \"c\") return $list[xs:int($number * 2) - 1]"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("testCalculationInPredicate_wiki_7", 1, rs.getSize()); assertEquals("testCalculationInPredicate_wiki_7", "c", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } /* * Miscomputation of the expression context in where clause when no * wrapper expression is used. Using, e.g. where data($x/@id) eq "id" works ! */ public void bugtestComputationBug_wiki_8() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"let $a := element node1 { attribute id {'id'}, " +"element node1 { '1'},element node2 { '2'} }" +"for $x in $a where $x/@id eq \"id\" return $x"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("testComputationBug_wiki_8", 1, rs.getSize()); assertEquals("testComputationBug_wiki_8", "<node1 id=\"id\"><node1>1</node1><node2>2</node2></node1>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void testStrings() { try { XQueryService service = storeXMLStringAndGetQueryService("strings.xml", strings); ResourceSet result = queryResource(service, "strings.xml", "substring(/test/string[1], 1, 5)", 1); assertEquals( "Hello", result.getResource(0).getContent() ); queryResource(service, "strings.xml", "/test/string[starts-with(string(.), 'Hello')]", 2); result = queryResource(service, "strings.xml", "count(/test/item/price)", 1, "Query should return an empty set (wrong document)"); assertEquals("0", result.getResource(0).getContent()); } catch (XMLDBException e) { System.out.println("testStrings(): XMLDBException: "+e); fail(e.getMessage()); } } public void testQuotes() { try { XQueryService service = storeXMLStringAndGetQueryService("quotes.xml", quotes); // ResourceSet result = queryResource(service, "quotes.xml", "/test[title = '&quot;Hello&quot;']", 1); service.declareVariable("content", "&quot;Hello&quot;"); // result = queryResource(service, "quotes.xml", "/test[title = $content]", 1); } catch (XMLDBException e) { System.out.println("testQuotes(): XMLDBException: "+e); fail(e.getMessage()); } } public void testBoolean() { try { System.out.println("Testing effective boolean value of expressions ..."); XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); ResourceSet result = queryResource(service, "numbers.xml", "boolean(1.0)", 1); assertEquals("boolean value of 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(0.0)", 1); assertEquals("boolean value of 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:double(0.0))", 1); assertEquals("boolean value of double 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:double(1.0))", 1); assertEquals("boolean value of double 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:float(1.0))", 1); assertEquals("boolean value of float 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:float(0.0))", 1); assertEquals("boolean value of float 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:integer(0))", 1); assertEquals("boolean value of integer 0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:integer(1))", 1); assertEquals("boolean value of integer 1 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "'true' cast as xs:boolean", 1); assertEquals("boolean value of 'true' cast to xs:boolean should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "'false' cast as xs:boolean", 1); assertEquals("boolean value of 'false' cast to xs:boolean should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean('Hello')", 1); assertEquals("boolean value of string 'Hello' should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean('')", 1); assertEquals("boolean value of empty string should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(())", 1); assertEquals("boolean value of empty sequence should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(('Hello'))", 1); assertEquals("boolean value of sequence with non-empty string should be true", "true", result.getResource(0).getContent()); // result = queryResource(service, "numbers.xml", "boolean((0.0, 0.0))", 1); // assertEquals("boolean value of sequence with two elements should be true", "true", // result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(//item[@id = '1']/price)", 1); assertEquals("boolean value of 5.6 should be true", "true", result.getResource(0).getContent()); boolean exceptionThrown = false; String message = ""; try { result = queryResource(service, "numbers.xml", "boolean(current-time())", 1); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("FORG0006") > -1); } catch (XMLDBException e) { System.out.println("testBoolean(): XMLDBException: "+e); fail(e.getMessage()); } } public void testNot() { try { XQueryService service = storeXMLStringAndGetQueryService("strings.xml", strings); queryResource(service, "strings.xml", "/test/string[not(@value)]", 2); ResourceSet result = queryResource(service, "strings.xml", "not(/test/abcd)", 1); Resource r = result.getResource(0); assertEquals("true", r.getContent().toString()); result = queryResource(service, "strings.xml", "not(/test)", 1); r = result.getResource(0); assertEquals("false", r.getContent().toString()); result = queryResource(service, "strings.xml", "/test/string[not(@id)]", 3); r = result.getResource(0); assertEquals("<string>Hello World!</string>", r.getContent().toString()); // test with non-existing items queryResource( service, "strings.xml", "document()/blah[not(blah)]", 0); /** test involving ancestor:: * >>>>>>> currently this produces variable corruption : * The result is the ancestor <<<<<<<<<< */ public void testAncestor() { ResourceSet result; try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers ); query = "let $all_items := /test/item " + "(: Note: variable non used but computed anyway :)" + "let $unused_variable :=" + " for $one_item in $all_items " + " / ancestor::* (: <<<<< if you remove this line all is normal :)" + " return 'foo'" + "return $all_items"; result = service.queryResource("numbers.xml", query ); assertEquals(4, result.getSize()); } catch (XMLDBException e) { System.out.println("testAncestor(): XMLDBException: "+e); fail(e.getMessage()); } } /** Helper that performs an XQuery and does JUnit assertion on result size. * @see #queryResource(XQueryService, String, String, int, String) */ private ResourceSet queryResource(XQueryService service, String resource, String query, int expected) throws XMLDBException { return queryResource(service, resource, query, expected, null); } /** Helper that performs an XQuery and does JUnit assertion on result size. * @param service XQuery service * @param resource database resource (collection) to query * @param query * @param expected size of result * @param message for JUnit * @return a ResourceSet, allowing to do more assertions if necessary. * @throws XMLDBException */ private ResourceSet queryResource(XQueryService service, String resource, String query, int expected, String message) throws XMLDBException { ResourceSet result = service.queryResource(resource, query); if(message == null) assertEquals(query, expected, result.getSize()); else assertEquals(message, expected, result.getSize()); return result; } /** For queries without associated data */ private ResourceSet queryAndAssert(XQueryService service, String query, int expected, String message) throws XMLDBException { ResourceSet result = service.query(query); if(message == null) assertEquals(expected, result.getSize()); else assertEquals(message, expected, result.getSize()); return result; } /** For queries without associated data */ private XQueryService getQueryService() throws XMLDBException { XQueryService service = (XQueryService) testCollection.getService( "XPathQueryService", "1.0"); return service; } /** stores XML String and get Query Service * @param documentName to be stored in the DB * @param content to be stored in the DB * @return the XQuery Service * @throws XMLDBException */ private XQueryService storeXMLStringAndGetQueryService(String documentName, String content) throws XMLDBException { XMLResource doc = (XMLResource) testCollection.createResource( documentName, "XMLResource" ); doc.setContent(content); testCollection.storeResource(doc); XQueryService service = (XQueryService) testCollection.getService( "XPathQueryService", "1.0"); return service; } public void testNamespaces() { try { XQueryService service = storeXMLStringAndGetQueryService("namespaces.xml", namespaces); service.setNamespace("t", "http: service.setNamespace("c", "http: ResourceSet result = service.queryResource("namespaces.xml", "//t:section"); assertEquals(1, result.getSize()); result = service.queryResource("namespaces.xml", "/t:test//c:comment"); assertEquals(1, result.getSize()); result = service.queryResource("namespaces.xml", " assertEquals(1, result.getSize()); /** * @param result * @throws XMLDBException */ private void printResult(ResourceSet result) throws XMLDBException { for (ResourceIterator i = result.getIterator(); i.hasMoreResources(); ) { Resource r = i.nextResource(); System.out.println(r.getContent()); } } public void testMembersAsResource() { try { // XPathQueryService service = // (XPathQueryService) testCollection.getService( // "XPathQueryService", // ResourceSet result = service.query("//SPEECH[LINE &= 'marriage']"); XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); ResourceSet result = service.query("//item/price"); Resource r = result.getMembersAsResource(); String content = (String)r.getContent(); System.out.println(content); Pattern p = Pattern.compile( ".*(<price>.*){4}", Pattern.DOTALL); Matcher m = p.matcher(content); assertTrue( "get whole document numbers.xml", m.matches() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testSatisfies() { try { XQueryService service = getQueryService(); ResourceSet result; result = queryAndAssert( service, "every $foo in (1,2,3) satisfies" + " let $bar := 'baz'" + " return false() ", 1, "" ); assertEquals( "satisfies + FLWR expression allways false 1", "false", result.getResource(0).getContent() ); result = queryAndAssert( service, "declare function local:foo() { false() };" + " every $bar in (1,2,3) satisfies" + " local:foo()", 1, "" ); assertEquals( "satisfies + FLWR expression allways false 2", "false", result.getResource(0).getContent() ); query = "every $x in () satisfies false()"; result = queryAndAssert( service, query, 1, "" ); assertEquals( query, "true", result.getResource(0).getContent() ); query = "some $x in () satisfies true()"; result = queryAndAssert( service, query, 1, "" ); assertEquals( query, "false", result.getResource(0).getContent() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testIntersect() { try { XQueryService service = getQueryService(); ResourceSet result; query = "() intersect ()"; result = queryAndAssert( service, query, 0, ""); query = "() intersect (1)"; result = queryAndAssert( service, query, 0, ""); query = "(1) intersect ()"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testUnion() { try { XQueryService service = getQueryService(); ResourceSet result; query = "() union ()"; result = queryAndAssert( service, query, 0, ""); boolean exceptionThrown = false; String message = ""; try { query = "() union (1)"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); exceptionThrown = false; message = ""; try { query = "(1) union ()"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); query = "<a/> union ()"; result = queryAndAssert( service, query, 1, ""); query = "() union <a/>"; result = queryAndAssert( service, query, 1, ""); //Not the same nodes query = "<a/> union <a/>"; result = queryAndAssert( service, query, 2, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testExcept() { try { XQueryService service = getQueryService(); query = "() except ()"; queryAndAssert( service, query, 0, ""); query = "() except (1)"; queryAndAssert( service, query, 0, ""); String message = ""; try { query = "(1) except ()"; queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); query = "<a/> except ()"; queryAndAssert( service, query, 1, ""); query = "() except <a/>"; queryAndAssert( service, query, 0, ""); //Not the same nodes query = "<a/> except <a/>"; queryAndAssert( service, query, 1, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testConvertToBoolean() throws XMLDBException { XQueryService service = getQueryService(); ResourceSet result; try { result = queryAndAssert( service, "let $doc := <element attribute=''/>" + "return (" + " <true>{boolean(($doc,2,3))}</true> ," + " <true>{boolean(($doc/@*,2,3))}</true> ," + " <true>{boolean(true())}</true> ," + " <true>{boolean('test')}</true> ," + " <true>{boolean(number(1))}</true> ," + " <false>{boolean((0))}</false> ," + " <false>{boolean(false())}</false> ," + " <false>{boolean('')}</false> ," + " <false>{boolean(number(0))}</false> ," + " <false>{boolean(number('NaN'))}</false>" + ")", 10, ""); for (int i = 0; i < 5; i++) { assertEquals("true " + (i + 1), "<true>true</true>", result .getResource(i).getContent()); } for (int i = 5; i < 10; i++) { assertEquals("false " + (i + 1), "<false>false</false>", result .getResource(i).getContent()); } } catch (XMLDBException e) { fail(e.getMessage()); } boolean exceptionThrown = false; String message = ""; try { result = queryAndAssert(service, "let $doc := <element attribute=''/>" + " return boolean( (1,2,$doc) )", 1, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue("Exception wanted: " + message, exceptionThrown); } public void testCompile() throws XMLDBException { String invalidQuery = "for $i in (1 to 10)\n return $b"; String validQuery = "for $i in (1 to 10) return $i"; String validModule = "module namespace foo=\"urn:foo\";\n" + "declare function foo:test() { \"Hello World!\" };"; String invalidModule = "module namespace foo=\"urn:foo\";\n" + "declare function foo:test() { \"Hello World! };"; org.exist.xmldb.XQueryService service = (org.exist.xmldb.XQueryService) getQueryService(); boolean exceptionOccurred = false; try { service.compile(invalidQuery); } catch (XMLDBException e) { assertEquals(((XPathException)e.getCause()).getLine(), 2); exceptionOccurred = true; } assertTrue("Expected an exception", exceptionOccurred); exceptionOccurred = false; try { service.compileAndCheck(invalidModule); } catch (XPathException e) { exceptionOccurred = true; } assertTrue("Expected an exception", exceptionOccurred); try { service.compile(validQuery); service.compile(validModule); } catch (XMLDBException e) { fail(e.getMessage()); } } /** * Added by Geoff Shuetrim on 15 July 2006 (geoff@galexy.net). * This test has been added following identification of a problem running * XPath queries that involved the name of elements with the name 'xpointer'. * @throws XMLDBException */ public void bugtestXPointerElementNameHandling() { try { XQueryService service = storeXMLStringAndGetQueryService( "xpointer.xml", xpointerElementName); ResourceSet result = service.queryResource("xpointer.xml", "/test/.[local-name()='xpointer']"); printResult(result); assertEquals(1, result.getSize()); result = service.queryResource("xpointer.xml", "/test/xpointer"); printResult(result); assertEquals(1, result.getSize()); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testSubstring() throws XMLDBException { XQueryService service = getQueryService(); ResourceSet result; // Testcases by MIKA try { String validQuery="substring(\"MK-1234\", 4,1)"; result = queryAndAssert( service, validQuery, 1, validQuery); assertEquals("1", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } try { String invalidQuery="substring(\"MK-1234\", 4,4)"; result = queryAndAssert( service, invalidQuery, 1, invalidQuery); assertEquals("1234", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } // Testcase by Toar try { String toarQuery="let $num := \"2003.123\" \n return substring($num, 1, 7)"; result = queryAndAssert( service, toarQuery, 1, toarQuery); assertEquals("2003.12", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public static void main(String[] args) { junit.textui.TestRunner.run(XPathQueryTest.class); } }
package info.tregmine.commands; import static org.bukkit.ChatColor.*; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import info.tregmine.Tregmine; import info.tregmine.api.Notification; import info.tregmine.api.TregminePlayer; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IPlayerDAO; public class MsgCommand extends AbstractCommand { public MsgCommand(Tregmine tregmine) { super(tregmine, "msg"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (args.length < 2) { return false; } Server server = player.getServer(); String recvPattern = args[0]; String message = argsToMessage(args); Player recv = server.getPlayer(recvPattern); if (recv == null) { // TODO: Error message... return true; } String[] receivingPlayers = args[0].split(","); try (IContext ctx = tregmine.createContext()) { IPlayerDAO playerDAO = ctx.getPlayerDAO(); for (String possiblePlayer : receivingPlayers) { List<TregminePlayer> candidates = tregmine.matchPlayer(possiblePlayer); if (candidates.size() != 1) { player.sendNotification(Notification.COMMAND_FAIL, ChatColor.RED + "No player found by the name of " + possiblePlayer); } TregminePlayer receivingPlayer = candidates.get(0); boolean ignored; ignored = playerDAO.doesIgnore(receivingPlayer, player); if (player.getRank().canNotBeIgnored()) ignored = false; if (ignored) continue; // Show message in senders terminal, as long as the recipient isn't // invisible, to prevent /msg from giving away hidden players presence if (!receivingPlayer.hasFlag(TregminePlayer.Flags.INVISIBLE) || player.getRank().canSeeHiddenInfo()) { player.sendMessage(GREEN + "(to) " + receivingPlayer.getChatName() + GREEN + ": " + message); } // Send message to recipient receivingPlayer.sendNotification(Notification.MESSAGE, GREEN + "(msg) " + player.getChatName() + GREEN + ": " + message); } } catch (DAOException e) { throw new RuntimeException(e); } return true; } }
package org.exist.xquery.value; import org.apache.log4j.Logger; import org.exist.collections.Collection; import org.exist.dom.DefaultDocumentSet; import org.exist.dom.DocumentSet; import org.exist.dom.MutableDocumentSet; import org.exist.dom.NewArrayNodeSet; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.StoredNode; import org.exist.memtree.DocumentImpl; import org.exist.memtree.NodeImpl; import org.exist.numbering.NodeId; import org.exist.util.FastQSort; import org.exist.xquery.Constants; import org.exist.xquery.NodeTest; import org.exist.xquery.Variable; import org.exist.xquery.XPathException; import org.w3c.dom.Node; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * A sequence that may contain a mixture of atomic values and nodes. * * @author wolf */ public class ValueSequence extends AbstractSequence implements MemoryNodeSet { private final Logger LOG = Logger.getLogger(ValueSequence.class); //Do not change the -1 value since size computation relies on this start value private final static int UNSET_SIZE = -1; private final static int INITIAL_SIZE = 64; protected Item[] values; protected int size = UNSET_SIZE; // used to keep track of the type of added items. // will be Type.ANY_TYPE if the typlexe is unknown // and Type.ITEM if there are items of mixed type. protected int itemType = Type.ANY_TYPE; private boolean noDuplicates = false; private boolean inMemNodeSet = false; private boolean isOrdered = false; private boolean enforceOrder = false; private boolean keepUnOrdered = false; private Variable holderVar = null; private int state = 0; private NodeSet cachedSet = null; public ValueSequence() { this(false); } public ValueSequence(boolean ordered) { values = new Item[INITIAL_SIZE]; enforceOrder = ordered; } public ValueSequence(int initialSize) { values = new Item[initialSize]; } public ValueSequence(Sequence otherSequence) throws XPathException { this(otherSequence, false); } public ValueSequence(Sequence otherSequence, boolean ordered) throws XPathException { values = new Item[otherSequence.getItemCount()]; addAll(otherSequence); this.enforceOrder = ordered; } public ValueSequence(final Item... items) throws XPathException { values = new Item[items.length]; for(final Item item : items) { add(item); } } public void keepUnOrdered(boolean flag) { keepUnOrdered = flag; } public void clear() { Arrays.fill(values, null); size = UNSET_SIZE; itemType = Type.ANY_TYPE; noDuplicates = false; } public boolean isEmpty() { return isEmpty; } public boolean hasOne() { return hasOne; } public void add(Item item) { if (hasOne) hasOne = false; if (isEmpty) hasOne = true; cachedSet = null; isEmpty = false; ++size; ensureCapacity(); values[size] = item; if (itemType == item.getType()) return; else if (itemType == Type.ANY_TYPE) itemType = item.getType(); else itemType = Type.getCommonSuperType(item.getType(), itemType); noDuplicates = false; isOrdered = false; setHasChanged(); } // public void addAll(ValueSequence otherSequence) throws XPathException { // if (otherSequence == null) // return; // enforceOrder = otherSequence.enforceOrder; // for (SequenceIterator i = otherSequence.iterate(); i.hasNext(); ) { // add(i.nextItem()); public void addAll(Sequence otherSequence) throws XPathException { if (otherSequence == null) return; SequenceIterator iterator = otherSequence.iterate(); if (iterator == null) { LOG.warn("Iterator == null: " + otherSequence.getClass().getName()); } for(; iterator.hasNext(); ) add(iterator.nextItem()); } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getItemType() */ public int getItemType() { return itemType == Type.ANY_TYPE ? Type.ITEM : itemType; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#iterate() */ public SequenceIterator iterate() throws XPathException { sortInDocumentOrder(); return new ValueSequenceIterator(); } /* (non-Javadoc) * @see org.exist.xquery.value.AbstractSequence#unorderedIterator() */ public SequenceIterator unorderedIterator() throws XPathException { sortInDocumentOrder(); return new ValueSequenceIterator(); } public boolean isOrdered() { return enforceOrder; } public void setIsOrdered(boolean ordered) { this.enforceOrder = ordered; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getLength() */ public int getItemCount() { sortInDocumentOrder(); return size + 1; } public Item itemAt(int pos) { sortInDocumentOrder(); return values[pos]; } public void setHolderVariable(Variable var) { this.holderVar = var; } /** * Makes all in-memory nodes in this sequence persistent, * so they can be handled like other node sets. * * @see org.exist.xquery.value.Sequence#toNodeSet() */ public NodeSet toNodeSet() throws XPathException { if(size == UNSET_SIZE) return NodeSet.EMPTY_SET; // for this method to work, all items have to be nodes if(itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.NODE)) { NodeSet set = new NewArrayNodeSet(); NodeValue v; for (int i = 0; i <= size; i++) { v = (NodeValue)values[i]; if(v.getImplementationType() != NodeValue.PERSISTENT_NODE) { // found an in-memory document DocumentImpl doc = ((NodeImpl)v).getDocument(); if (doc==null) { continue; } // make this document persistent: doc.makePersistent() // returns a map of all root node ids mapped to the corresponding // persistent node. We scan the current sequence and replace all // in-memory nodes with their new persistent node objects. DocumentImpl expandedDoc = doc.expandRefs(null); org.exist.dom.DocumentImpl newDoc = expandedDoc.makePersistent(); if (newDoc != null) { NodeId rootId = newDoc.getBrokerPool().getNodeFactory().createInstance(); for (int j = i; j <= size; j++) { v = (NodeValue) values[j]; if(v.getImplementationType() != NodeValue.PERSISTENT_NODE) { NodeImpl node = (NodeImpl) v; if (node.getDocument() == doc) { if (node.getNodeType() == Node.ATTRIBUTE_NODE) node = expandedDoc.getAttribute(node.getNodeNumber()); else node = expandedDoc.getNode(node.getNodeNumber()); NodeId nodeId = node.getNodeId(); if (nodeId == null) throw new XPathException("Internal error: nodeId == null"); if (node.getNodeType() == Node.DOCUMENT_NODE) nodeId = rootId; else nodeId = rootId.append(nodeId); NodeProxy p = new NodeProxy(newDoc, nodeId, node.getNodeType()); if (p != null) { // replace the node by the NodeProxy values[j] = p; } } } } set.add((NodeProxy) values[i]); } } else { set.add((NodeProxy)v); } } if (holderVar != null) holderVar.setValue(set); return set; } else throw new XPathException("Type error: the sequence cannot be converted into" + " a node set. Item type is " + Type.getTypeName(itemType)); } public MemoryNodeSet toMemNodeSet() throws XPathException { if(size == UNSET_SIZE) return MemoryNodeSet.EMPTY; if(itemType == Type.ANY_TYPE || !Type.subTypeOf(itemType, Type.NODE)) { throw new XPathException("Type error: the sequence cannot be converted into" + " a node set. Item type is " + Type.getTypeName(itemType)); } NodeValue v; for (int i = 0; i <= size; i++) { v = (NodeValue)values[i]; if(v.getImplementationType() == NodeValue.PERSISTENT_NODE) throw new XPathException("Type error: the sequence cannot be converted into" + " a MemoryNodeSet. It contains nodes from stored resources."); } expand(); inMemNodeSet = true; return this; } public boolean isInMemorySet() { if(size == UNSET_SIZE) return true; if(itemType == Type.ANY_TYPE || !Type.subTypeOf(itemType, Type.NODE)) return false; NodeValue v; for (int i = 0; i <= size; i++) { v = (NodeValue)values[i]; if(v.getImplementationType() == NodeValue.PERSISTENT_NODE) return false; } return true; } public boolean isPersistentSet() { if(size == UNSET_SIZE) return true; if(itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.NODE)) { NodeValue v; for (int i = 0; i <= size; i++) { v = (NodeValue)values[i]; if(v.getImplementationType() != NodeValue.PERSISTENT_NODE) return false; } return true; } return false; } /** * Scan the sequence and check all in-memory documents. * They may contains references to nodes stored in the database. * Expand those references to get a pure in-memory DOM tree. */ private void expand() { Set<DocumentImpl> docs = new HashSet<DocumentImpl>(); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if (node.getDocument().hasReferenceNodes()) docs.add(node.getDocument()); } for (DocumentImpl doc : docs) { doc.expand(); } } @Override public void destroy(Sequence contextSequence) { for (int i = 0; i <= size; i++) { ((Sequence)values[i]).destroy(contextSequence); } } public boolean containsValue(AtomicValue value) { for (int i = 0; i <= size; i++) { if (values[i] == value) return true; } return false; } public void sortInDocumentOrder() { if (size == UNSET_SIZE) return; if (keepUnOrdered) { removeDuplicateNodes(); return; } if (!enforceOrder || isOrdered) return; inMemNodeSet = inMemNodeSet || isInMemorySet(); if (inMemNodeSet) { FastQSort.sort(values, new InMemoryNodeComparator(), 0, size); } removeDuplicateNodes(); isOrdered = true; } public void removeDuplicates() { enforceOrder = true; isOrdered = false; sortInDocumentOrder(); } private void ensureCapacity() { if(size == values.length) { int newSize = (int)Math.round((size == 0 ? 1 : size * 3) / (double) 2); Item newValues[] = new Item[newSize]; System.arraycopy(values, 0, newValues, 0, size); values = newValues; } } private void removeDuplicateNodes() { if(noDuplicates || size < 1) return; if (inMemNodeSet) { int j = 0; for (int i = 1; i <= size; i++) { if (!values[i].equals(values[j])) { if (i != ++j) { values[j] = values[i]; } } } size = j; } else { if(itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.ATOMIC)) return; // check if the sequence contains nodes boolean hasNodes = false; for(int i = 0; i <= size; i++) { if(Type.subTypeOf(values[i].getType(), Type.NODE)) hasNodes = true; } if(!hasNodes) return; Map<Item, Item> nodes = new TreeMap<Item, Item>(); int j = 0; for (int i = 0; i <= size; i++) { if(Type.subTypeOf(values[i].getType(), Type.NODE)) { Item found = nodes.get(values[i]); if(found == null) { Item item = values[i]; values[j++] = item; nodes.put(item, item); } else { NodeValue nv = (NodeValue) found; if (nv.getImplementationType() == NodeValue.PERSISTENT_NODE) ((NodeProxy) nv).addMatches((NodeProxy) values[i]); } } else values[j++] = values[i]; } size = j - 1; } noDuplicates = true; } public void clearContext(int contextId) throws XPathException { for (int i = 0; i <= size; i++) { if (Type.subTypeOf(values[i].getType(), Type.NODE)) ((NodeValue) values[i]).clearContext(contextId); } } public void nodeMoved(NodeId oldNodeId, StoredNode newNode) { for (int i = 0; i <= size; i++) { values[i].nodeMoved(oldNodeId, newNode); } } private void setHasChanged() { state = (state == Integer.MAX_VALUE ? state = 0 : state + 1); } public int getState() { return state; } public boolean hasChanged(int previousState) { return state != previousState; } public boolean isCacheable() { return true; } /* (non-Javadoc) * @see org.exist.xquery.value.Sequence#getDocumentSet() */ public DocumentSet getDocumentSet() { if (cachedSet != null) return cachedSet.getDocumentSet(); try { boolean isPersistentSet = true; NodeValue node; for (int i = 0; i <= size; i++) { if (Type.subTypeOf(values[i].getType(), Type.NODE)) { node = (NodeValue) values[i]; if (node.getImplementationType() != NodeValue.PERSISTENT_NODE) { isPersistentSet = false; break; } } else { isPersistentSet = false; break; } } if (isPersistentSet) { cachedSet = toNodeSet(); return cachedSet.getDocumentSet(); } } catch (XPathException e) { } return extractDocumentSet(); } private DocumentSet extractDocumentSet() { MutableDocumentSet docs = new DefaultDocumentSet(); NodeValue node; for (int i = 0; i <= size; i++) { if (Type.subTypeOf(values[i].getType(), Type.NODE)) { node = (NodeValue) values[i]; if (node.getImplementationType() == NodeValue.PERSISTENT_NODE) docs.add((org.exist.dom.DocumentImpl) node.getOwnerDocument()); } } return docs; } /* Methods of MemoryNodeSet */ public Sequence getAttributes(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectAttributes(test, nodes); } return nodes; } public Sequence getDescendantAttributes(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectDescendantAttributes(test, nodes); } return nodes; } public Sequence getChildren(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectChildren(test, nodes); } return nodes; } public Sequence getChildrenForParent(NodeImpl parent) { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if (node.getNodeId().isChildOf(parent.getNodeId())) nodes.add(node); } return nodes; } public Sequence getDescendants(boolean includeSelf, NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectDescendants(includeSelf, test, nodes); } return nodes; } public Sequence getAncestors(boolean includeSelf, NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectAncestors(includeSelf, test, nodes); } return nodes; } public Sequence getParents(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; NodeImpl parent = (NodeImpl) node.selectParentNode(); if (parent != null && test.matches(parent)) nodes.add(parent); } return nodes; } public Sequence getSelf(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if ((test.getType() == Type.NODE && node.getNodeType() == Node.ATTRIBUTE_NODE) || test.matches(node)) nodes.add(node); } return nodes; } public Sequence getPrecedingSiblings(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectPrecedingSiblings(test, nodes); } return nodes; } public Sequence getPreceding(NodeTest test, int position) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectPreceding(test, nodes, position); } return nodes; } public Sequence getFollowingSiblings(NodeTest test) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectFollowingSiblings(test, nodes); } return nodes; } public Sequence getFollowing(NodeTest test, int position) throws XPathException { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; node.selectFollowing(test, nodes, position); } return nodes; } public Sequence selectDescendants(MemoryNodeSet descendants) { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; for (int j = 0; j < descendants.size(); j++) { NodeImpl descendant = descendants.get(j); if (descendant.getNodeId().isDescendantOrSelfOf(node.getNodeId())) nodes.add(node); } } return nodes; } public Sequence selectChildren(MemoryNodeSet children) { sortInDocumentOrder(); ValueSequence nodes = new ValueSequence(true); nodes.keepUnOrdered(keepUnOrdered); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; for (int j = 0; j < children.size(); j++) { NodeImpl descendant = children.get(j); if (descendant.getNodeId().isChildOf(node.getNodeId())) nodes.add(node); } } return nodes; } public int size() { return size + 1; } public NodeImpl get(int which) { return (NodeImpl) values[which]; } /* END methods of MemoryNodeSet */ public Iterator<Collection> getCollectionIterator() { return new CollectionIterator(); } private class CollectionIterator implements Iterator<Collection> { Collection nextCollection = null; int pos = 0; CollectionIterator() { next(); } public boolean hasNext() { return nextCollection != null; } public Collection next() { Collection oldCollection = nextCollection; nextCollection = null; while (pos <= size) { if (Type.subTypeOf(values[pos].getType(), Type.NODE)) { NodeValue node = (NodeValue) values[pos]; if (node.getImplementationType() == NodeValue.PERSISTENT_NODE) { NodeProxy p = (NodeProxy) node; if (!p.getDocument().getCollection().equals(oldCollection)) { nextCollection = p.getDocument().getCollection(); break; } } } pos++; } return oldCollection; } public void remove() { // not needed throw new IllegalStateException(); } } public String toString() { try { StringBuilder result = new StringBuilder(); result.append("("); boolean moreThanOne = false; for (SequenceIterator i = iterate(); i.hasNext(); ) { Item next = i.nextItem(); if (moreThanOne) result.append(", "); moreThanOne = true; result.append(next.toString()); } result.append(")"); return result.toString(); } catch (XPathException e) { return "ValueSequence.toString() failed: " + e.getMessage(); } } /** * Returns a hashKey based on sequence item string values. * This function is faster than toString() but need to be enhanced. * * Warning : don't use except for experimental GroupBy clause. * author Boris Verhaegen * * @see org.exist.xquery.value.GroupedValueSequenceTable * * */ public String getHashKey(){ try{ String hashKey = ""; for(SequenceIterator i = iterate();i.hasNext();){ Item current = i.nextItem(); hashKey+=current.getStringValue(); hashKey+="&&"; //bv : sentinel value to separate grouping keys values } return hashKey; } catch (XPathException e) { return "ValueSequence.getHashKey() failed: " + e.getMessage(); } } private class ValueSequenceIterator implements SequenceIterator { private int pos = 0; public ValueSequenceIterator() { } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#hasNext() */ public boolean hasNext() { return pos <= size; } /* (non-Javadoc) * @see org.exist.xquery.value.SequenceIterator#nextItem() */ public Item nextItem() { if(pos <= size) return values[pos++]; return null; } } private static class InMemoryNodeComparator implements Comparator<Item> { public int compare(Item o1, Item o2) { NodeImpl n1 = (NodeImpl) o1; NodeImpl n2 = (NodeImpl) o2; final int docCmp = n1.getDocument().compareTo(n2.getDocument()); if (docCmp == 0) { return n1.getNodeNumber() == n2.getNodeNumber() ? Constants.EQUAL : (n1.getNodeNumber() > n2.getNodeNumber() ? Constants.SUPERIOR : Constants.INFERIOR); } else return docCmp; } } public boolean matchSelf(NodeTest test) throws XPathException { //UNDERSTAND: is it required? -shabanovd sortInDocumentOrder(); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if ((test.getType() == Type.NODE && node.getNodeType() == Node.ATTRIBUTE_NODE) || test.matches(node)) return true; } return false; } public boolean matchChildren(NodeTest test) throws XPathException { //UNDERSTAND: is it required? -shabanovd sortInDocumentOrder(); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if (node.matchChildren(test)) return true; } return false; } public boolean matchAttributes(NodeTest test) throws XPathException { //UNDERSTAND: is it required? -shabanovd sortInDocumentOrder(); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if (node.matchAttributes(test)) return true; } return false; } public boolean matchDescendantAttributes(NodeTest test) throws XPathException { //UNDERSTAND: is it required? -shabanovd sortInDocumentOrder(); for (int i = 0; i <= size; i++) { NodeImpl node = (NodeImpl) values[i]; if (node.matchDescendantAttributes(test)) return true; } return false; } }
package it.ksuploader.main; import java.io.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.channels.UnresolvedAddressException; import java.util.Arrays; import java.util.Observable; import java.util.Observer; public class SocketUploader implements Observer{ private SocketChannel socketChannel; private String link; private String filePath; private DataOutputStream dos; private DataInputStream dis; private RandomAccessFile aFile; private FileChannel inChannel; public SocketUploader() { } public boolean send(String type) { try { this.socketChannel = createChannel(Main.config.getIp(), Main.config.getPort()); this.dos = new DataOutputStream(socketChannel.socket().getOutputStream()); this.dis = new DataInputStream(socketChannel.socket().getInputStream()); // send auth Main.myLog("[SocketUploader] Sending auth"); dos.writeUTF(Main.config.getPass()); Main.myLog("[SocketUploader] Auth sent: " + Main.config.getPass()); this.link = dis.readUTF(); Main.myLog("[SocketUploader] Auth reply: " + link); if (this.link.equals("OK")) { Main.myLog("Sending type: " + type); dos.writeUTF(type); String srvResponse; // Controllo e aspetto che il server abbia ricevuto il type // corretto if (dis.readUTF().equals(type)) { Main.myLog("Il server riceve un: " + type); File file = new File(filePath); long fileLength = file.length(); Main.myLog("[SocketUploader] File length: " + fileLength); dos.writeLong(fileLength); srvResponse = dis.readUTF(); switch (srvResponse) { case "START_TRANSFER": aFile = new RandomAccessFile(file, "r"); inChannel = aFile.getChannel(); long bytesSent = 0; Main.dialog.show("Uploading...", "", false); // send the file long bfSize = Math.min(32768, fileLength); // 128kB buffer while (bytesSent < fileLength) { bytesSent += inChannel.transferTo(bytesSent, bfSize, socketChannel); Main.myLog("[SocketUploader] Sent: " + 100 * bytesSent / fileLength + "%"); Main.dialog.set((int) (100 * bytesSent / fileLength)); } inChannel.close(); Main.myLog("[SocketUploader] End of file reached.."); aFile.close(); Main.myLog("[SocketUploader] File closed."); Main.dialog.setWait(); break; case "FILE_TOO_LARGE": Main.myLog("[SocketUploader] File too large"); Main.dialog.fileTooLarge(); break; case "SERVER_FULL": Main.myLog("[SocketUploader] Server Full"); Main.dialog.serverFull(); break; } // return link Main.myLog("[SocketUploader] Waiting link..."); this.link = dis.readUTF(); Main.myLog("[SocketUploader] Returned link: " + link); Main.dialog.destroy(); } else { Main.myLog("[SocketUploader] The server had a bad interpretation of the fileType"); return false; } } else { Main.myLog("[SocketUploader] Wrong password, closed"); Main.dialog.wrongPassword(); return false; } inChannel.close(); aFile.close(); dis.close(); dos.flush(); dos.close(); socketChannel.close(); } catch (IOException e) { e.printStackTrace(); try { inChannel.close(); aFile.close(); dos.close(); dis.close(); socketChannel.close(); } catch (IOException e1) { e1.printStackTrace(); return false; } return false; } return true; } public void stopUpload() { try { inChannel.close(); aFile.close(); dos.close(); dis.close(); socketChannel.close(); new File(Main.so.getTempDir(), "KStemp.zip").delete(); Main.dialog.show("Stopped...", "", false); } catch (IOException e) { e.printStackTrace(); Main.myErr(Arrays.toString(e.getStackTrace()).replace(",", "\n")); } } private SocketChannel createChannel(String ip, int port) { try { SocketChannel sc = SocketChannel.open(); SocketAddress socketAddress = new InetSocketAddress(ip, port); sc.connect(socketAddress); Main.myLog("[SocketUploader] Reloaded socket"); return sc; } catch (IOException | UnresolvedAddressException e) { e.printStackTrace(); Main.dialog.connectionError(); Main.myErr(Arrays.toString(e.getStackTrace()).replace(",", "\n")); return null; } } public void setFilePath(String filePath) { this.filePath = filePath; } public String getLink() { return link; } @Override public void update(Observable o, Object arg) { stopUpload(); } }
package it.unimi.dsi.sux4j.util; import it.unimi.dsi.Util; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.BitVectors; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.booleans.BooleanArrayList; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; import it.unimi.dsi.fastutil.objects.AbstractObjectSet; import it.unimi.dsi.fastutil.objects.AbstractObjectSortedSet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectSet; import it.unimi.dsi.fastutil.objects.ObjectSortedSet; import it.unimi.dsi.io.FastBufferedReader; import it.unimi.dsi.io.LineIterator; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.mph.Hashes; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.zip.GZIPInputStream; import org.apache.log4j.Logger; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; /** A z-fast trie, that is, a predecessor/successor data structure using low linear (in the number of keys) additional space and * answering in time &#x2113;/<var>w</var> + log(max(&#x2113;, &#x2113;<sup>-</sup>, &#x2113;<sup>+</sup>)) with high probability, * where <var>w</var> is the machine word size, and &#x2113;, &#x2113;<sup>-</sup>, and &#x2113;<sup>+</sup> are the * lengths of the query string, of its predecessor and of its successor (in the currently stored set), respectively. * * <p>In rough terms, the z-fast trie uses &#x2113;/<var>w</var> (which is optimal) to actually look at the string content, * and log(max(&#x2113;, &#x2113;<sup>-</sup>, &#x2113;<sup>+</sup>)) to perform the search. This is known to be (essentially) optimal. * String lengths are up to {@link Long#MAX_VALUE}, and not limited to be a constant multiple of <var>w</var> for the bounds to hold. * * <p>The linear overhead of a z-fast trie is very low. For <var>n</var> keys we allocate 2<var>n</var> &minus; 1 nodes containing six references and * two longs, plus a dictionary containing <var>n</var> &minus; 1 nodes (thus using around 2<var>n</var> references and 2<var>n</var> longs). * */ public class ZFastTrie<T> extends AbstractObjectSortedSet<T> implements Serializable { public static final long serialVersionUID = 1L; private static final Logger LOGGER = Util.getLogger( ZFastTrie.class ); private static final boolean ASSERTS = false; private static final boolean SHORT_SIGNATURES = false; private static final boolean DDEBUG = false; private static final boolean DDDEBUG = DDEBUG; /** The number of elements in the trie. */ private int size; /** The root node. */ private transient Node root; /** The transformation strategy. */ private final TransformationStrategy<? super T> transform; /** A dictionary mapping handles to the corresponding internal nodes. */ public transient Map map; /** The head of the doubly linked list of leaves. */ private transient Node head; /** The tail of the doubly linked list of leaves. */ private transient Node tail; /** A linear-probing hash map that compares keys using signatures. */ public final static class Map { private static final long serialVersionUID = 1L; private static final int INITIAL_LENGTH = 64; /** The keys of the table, that is, the signatures of the handles of the associated nodes. */ private long[] key; /** The node associated to each signature. */ private Node[] node; /** Whether a key is a duplicate. In this case, there are more copies of the key along the search path. */ private boolean dup[]; /** The mask to transform a signature into a position in the table. */ private int mask; /** The number of keys in the table. */ private int size; /** The number of slots in the table. */ private int length; private void assertTable() { for( int i = key.length; i-- != 0; ) if ( node[ i ] != null ) assert get( node[ i ].handle(), true ) == node[ i ]; if ( size == 0 ) return; final IntOpenHashSet overallHashes = new IntOpenHashSet(); int start = 0; int first = -1; while( node[ start ] != null ) start = ( start + 1 ) & mask; // We are on an empty entry for( ;; ) { while( node[ start ] == null ) start = ( start + 1 ) & mask; // We are on a nonempty entry if ( first == -1 ) first = start; else if ( first == start ) break; int end = start; while( node[ end ] != null ) end = ( end + 1 ) & mask; // [start..end) is a maximal nonempty subsequence LongOpenHashSet signaturesSeen = new LongOpenHashSet(); IntOpenHashSet hashesSeen = new IntOpenHashSet(); for( int pos = end; pos != start; ) { pos = ( pos - 1 ) & mask; assert signaturesSeen.add( key[ pos ] ) ^ dup[ pos ]; hashesSeen.add( hash( key[ pos ], mask ) ); } // Hashes in each maximal nonempty subsequence must be disjoint for( IntIterator iterator = hashesSeen.iterator(); iterator.hasNext(); ) assert overallHashes.add( iterator.nextInt() ); start = end; } } public Map( int size ) { length = Math.max( INITIAL_LENGTH, 1 << Fast.ceilLog2( 1 + size / 3 * 4 ) ); mask = length - 1; key = new long[ length ]; node = new Node[ length ]; dup = new boolean[ length ]; } public Map() { length = INITIAL_LENGTH; mask = length - 1; key = new long[ length ]; node = new Node[ length ]; dup = new boolean[ length ]; } public long probes = 0; public long scans = 0; private final static long PRIME = ( 1L << 61 ) - 1; private final static long LOW = ( 1L << 32 ) - 1; private final static long HIGH = LOW << 32; private final static long multAdd( int x, long a, long b ) { final long a0 = ( a & LOW ) * x; final long a1 = ( a & HIGH ) * x; final long c0 = a0 + ( a1 << 32 ); final long c1 = ( a0 >>> 32 ) + a1; return ( c0 & PRIME ) + ( c1 >>> 29 ) + b; } private final static long rehash( final int x ) { // TODO: we should really use tabulation-based 5-way independent hashing. final long h = multAdd( x, 104659742703825433L, 8758810104009432107L ); return ( h & PRIME ) + ( h >>> 61 ); } private static int hash( final long signature, final int mask ) { return (int)rehash( (int)( signature ^ signature >>> 32 ) ) & mask; } private int findPos( final BitVector v, final long prefixLength, final long signature ) { probes++; int pos = hash( signature, mask ); while( node[ pos ] != null ) { if ( key[ pos ] == signature && ( ! dup[ pos ] || prefixLength == node[ pos ].handleLength() && v.longestCommonPrefixLength( node[ pos ].key ) >= prefixLength ) ) break; pos = ( pos + 1 ) & mask; scans++; } return pos; } private int findExactPos( final BitVector v, final long prefixLength, final long signature ) { int pos = hash( signature, mask ); while( node[ pos ] != null ) { if ( key[ pos ] == signature && prefixLength == node[ pos ].handleLength() && v.longestCommonPrefixLength( node[ pos ].key ) >= prefixLength ) break; pos = ( pos + 1 ) & mask; } return pos; } private int findFreePos( final long signature ) { int pos = hash( signature, mask ); //int i = 0; while( node[ pos ] != null ) { if ( key[ pos ] == signature ) dup[ pos ] = true; pos = ( pos + 1 ) & mask; } //System.err.println( i ); return pos; } public void clear() { length = INITIAL_LENGTH; mask = length - 1; size = 0; key = new long[ length ]; node = new Node[ length ]; dup = new boolean[ length ]; } public ObjectSet<LongArrayBitVector> keySet() { return new AbstractObjectSet<LongArrayBitVector>() { @Override public ObjectIterator<LongArrayBitVector> iterator() { return new AbstractObjectIterator<LongArrayBitVector>() { private int i = 0; private int pos = -1; @Override public boolean hasNext() { return i < size; } @Override public LongArrayBitVector next() { if ( ! hasNext() ) throw new NoSuchElementException(); while( node[ ++pos ] == null ); i++; return LongArrayBitVector.copy( node[ pos ].handle() ); } }; } @Override public boolean contains( Object o ) { BitVector v = (BitVector)o; return get( v, true ) != null; } @Override public int size() { return size; } }; } public ObjectSet<Node> values() { return new AbstractObjectSet<Node>() { @Override public ObjectIterator<Node> iterator() { return new AbstractObjectIterator<Node>() { private int i = 0; private int pos = -1; @Override public boolean hasNext() { return i < size; } @Override public Node next() { if ( ! hasNext() ) throw new NoSuchElementException(); while( node[ ++pos ] == null ); i++; return node[ pos ]; } }; } @Override public boolean contains( Object o ) { final Node node = (Node)o; return get( node.handle(), true ) != null; } @Override public int size() { return size; } }; } public void replace( final Node newNode ) { final long signature = newNode.handleHash(); final int pos = findPos( newNode.key, newNode.handleLength(), signature ); if ( ASSERTS ) assert node[ pos ] != null; if ( ASSERTS ) assert node[ pos ].handle().equals( newNode.handle() ) : node[ pos ].handle() + " != " + newNode.handle(); node[ pos ] = newNode; if ( ASSERTS ) assertTable(); } public boolean remove( final Object k ) { if ( DDEBUG ) System.err.println( "Map.remove(" + k + ")" ); final Node v = (Node)k; final long signature = v.handleHash(); final int hash = hash( signature, mask ); final long prefixLength = v.handleLength(); int pos = hash; // The current position in the table. int lastDup = -1; while( node[ pos ] != null ) { if ( key[ pos ] == signature ) { if ( ! dup[ pos ] || prefixLength == node[ pos ].handleLength() && v.key.longestCommonPrefixLength( node[ pos ].key ) >= prefixLength ) break; else lastDup = pos; } pos = ( pos + 1 ) & mask; } if ( node[ pos ] == null ) return false; if ( ! dup[ pos ] && lastDup != -1 ) dup[ lastDup ] = false; // We are removing the only non-duplicate entry. // Move entries, compatibly with their hash code, to fill the hole. int candidateHole, h; do { candidateHole = pos; // Find candidate for a move (possibly empty). do { pos = ( pos + 1 ) & mask; if ( node[ pos ] == null ) break; h = hash( node[ pos ].handleHash(), mask ); /* The hash h must lie cyclically between candidateHole and pos: more precisely, h must be after candidateHole * but before the first free entry in the table (which is equivalent to the previous statement). */ } while( candidateHole <= pos ? candidateHole < h && h <= pos : candidateHole < h || h <= pos ); node[ candidateHole ] = node[ pos ]; key[ candidateHole ] = key[ pos ]; dup[ candidateHole ] = dup[ pos ]; } while( node[ pos ] != null ); size if ( ASSERTS ) assertTable(); return true; } public Node addNew( final Node v ) { final long signature = v.handleHash(); int pos = findFreePos( signature ); if ( ASSERTS ) assert node[ pos ] == null; size++; key[ pos ] = signature; node[ pos ] = v; if ( ( size / 3 * 4 ) > length ) { length *= 2; mask = length - 1; final long newKey[] = new long[ length ]; final Node[] newValue = new Node[ length ]; final boolean[] newCollision = new boolean[ length ]; final long[] key = this.key; final Node[] value = this.node; for( int i = key.length; i if ( value[ i ] != null ) { final long s = key[ i ]; pos = hash( s, mask ); while( newValue[ pos ] != null ) { if ( newKey[ pos ] == s ) newCollision[ pos ] = true; pos = ( pos + 1 ) & mask; } newKey[ pos ] = key[ i ]; newValue[ pos ] = value[ i ]; } } this.key = newKey; this.node = newValue; this.dup = newCollision; } if ( ASSERTS ) assertTable(); return null; } public int size() { return size; } public Node get( long signature, final BitVector v, final boolean exact ) { return get( signature, v, v.length(), exact ); } public Node get( long signature, final BitVector v, final long prefixLength, final boolean exact ) { if ( SHORT_SIGNATURES ) signature &= 0xF; final int pos = exact ? findExactPos( v, prefixLength, signature ) : findPos( v, prefixLength, signature ); return node[ pos ]; } public Node get( final BitVector v, final boolean exact ) { return get( Hashes.murmur( v, 0 ), v, exact ); } public String toString() { StringBuilder s = new StringBuilder(); s.append( '{' ); for( LongArrayBitVector v: keySet() ) s.append( v ).append( " => " ).append( get( v, false ) ).append( ", " ); if ( s.length() > 1 ) s.setLength( s.length() - 2 ); s.append( '}' ); return s.toString(); } } /** A node of the trie.* */ protected final static class Node { /** The left subtree for internal nodes; the predecessor leaf, otherwise. */ protected Node left; /** The right subtree for internal nodes; the successor leaf, otherwise. */ protected Node right; /** The jump pointer for the left path for internal nodes; <code>null</code>, otherwise (this * makes leaves distinguishable). */ protected Node jumpLeft; /** The jump pointer for the right path for internal nodes; <code>null</code>, otherwise. */ protected Node jumpRight; /** The leaf whose key this node refers to for internal nodes; the internal node that * refers to the key of this leaf, otherwise. Will be <code>null</code> for exactly one leaf. */ protected Node reference; /** The length of the extent of the parent node, or 0 for the root. */ protected long parentExtentLength; /** The length of the extent (for leaves, this is equal to the length of {@link #key}). */ protected long extentLength; /** The key upon which the extent of node is based, for internal nodes; the * key associated to a leaf, otherwise. */ protected LongArrayBitVector key; public boolean isLeaf() { return jumpLeft == null; } public boolean isInternal() { return jumpLeft != null; } public boolean intercepts( long h ) { return h > parentExtentLength && ( isLeaf() || h <= extentLength ); } public long handleLength() { return twoFattest( parentExtentLength, extentLength ); } public long jumpLength() { final long handleLength = twoFattest( parentExtentLength, extentLength ); return handleLength + ( handleLength & -handleLength ); } public BitVector extent() { return key.subVector( 0, extentLength ); } public BitVector handle() { return key.subVector( 0, handleLength() ); } public long handleHash() { if ( SHORT_SIGNATURES ) return Hashes.murmur( handle(), 0 ) & 0xF; else return Hashes.murmur( handle(), 0 ); } public String toString() { return ( isLeaf() ? "[" : "(" ) + Integer.toHexString( hashCode() & 0xFFFF ) + ( key == null ? "" : " " + ( extentLength > 16 ? key.subVector( 0, 8 ) + "..." + key.subVector( extentLength - 8, extentLength ): key.subVector( 0, extentLength ) ) ) + " (" + parentExtentLength + ".." + extentLength + "], " + handleLength() + "->" + jumpLength() + ( isLeaf() ? "]" : ")" ); } } /** Creates a new z-fast trie using the given transformation strategy. * * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final TransformationStrategy<? super T> transform ) { this.transform = transform; this.map = new Map(); initHeadTail(); } private void initHeadTail() { head = new Node(); tail = new Node(); head.right = tail; tail.left = head; } /** Creates a new z-fast trie using the given elements and transformation strategy. * * @param elements an iterator returning the elements among which the trie must be able to rank. * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final Iterator<? extends T> elements, final TransformationStrategy<? super T> transform ) { this( transform ); while( elements.hasNext() ) add( elements.next() ); } /** Creates a new z-fast trie using the given elements and transformation strategy. * * @param elements an iterator returning the elements among which the trie must be able to rank. * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final Iterable<? extends T> elements, final TransformationStrategy<? super T> transform ) { this( elements.iterator(), transform ); } public int size() { return size > Integer.MAX_VALUE ? -1 : (int)size; } /** Returns the 2-fattest number in an interval. * * <p>Note that to get the length of the handle of a node you must * call this function passing the length of the extent of the parent (one less * than the node name) and the length of the extent of the node. * * @param l left extreme (excluded). * @param r right extreme (included). * @return the 2-fattest number in (<code>l</code>..<code>r</code>]. */ private final static long twoFattest( final long l, final long r ) { return ( -1L << Fast.mostSignificantBit( l ^ r ) & r ); } private static void remove( final Node node ) { node.right.left = node.left; node.left.right = node.right; } private static void addAfter( final Node pred, final Node node ) { node.right = pred.right; node.left = pred; pred.right.left = node; pred.right = node; } private static void addBefore( final Node succ, final Node node ) { node.left = succ.left; node.right = succ; succ.left.right = node; succ.left = node; } private void assertTrie() { /* Shortest key */ LongArrayBitVector root = null; /* Keeps track of which nodes in map are reachable using left/right from the root. */ ObjectOpenHashSet<Node> nodes = new ObjectOpenHashSet<Node>(); /* Keeps track of leaves. */ ObjectOpenHashSet<Node> leaves = new ObjectOpenHashSet<Node>(); /* Keeps track of reference to leaf keys in internal nodes. */ ObjectOpenHashSet<BitVector> references = new ObjectOpenHashSet<BitVector>(); assert size == 0 && map.size() == 0 || size == map.size() + 1; /* Search for the root (shortest handle) and check that nodes and handles do match. */ for( LongArrayBitVector v : map.keySet() ) { final long vHandleLength = map.get( v, false ).handleLength(); if ( root == null || map.get( root, false ).handleLength() > vHandleLength ) root = v; final Node node = map.get( v, false ); nodes.add( node ); assert node.reference.reference == node : node + " -> " + node.reference + " -> " + node.reference.reference; } assert nodes.size() == map.size() : nodes.size() + " != " + map.size(); assert size < 2 || this.root == map.get( root, false ); if ( size > 1 ) { /* Verify doubly linked list of leaves. */ Node toRight = head.right, toLeft = tail.left; for( int i = 1; i < size; i++ ) { assert toRight.key.compareTo( toRight.right.key ) < 0 : toRight.key + " >= " + toRight.right.key + " " + toRight; assert toLeft.key.compareTo( toLeft.left.key ) > 0 : toLeft.key + " >= " + toLeft.left.key + " " + toLeft; toRight = toRight.right; toLeft = toLeft.left; } final int numNodes = visit( map.get( root, false ), null, 0, 0, nodes, leaves, references ); assert numNodes == 2 * size - 1 : numNodes + " != " + ( 2 * size - 1 ); assert leaves.size() == size; int c = 0; for( Node leaf: leaves ) if ( references.contains( leaf.key ) ) c++; assert c == size - 1 : c + " != " + ( size - 1 ); } else if ( size == 1 ) { assert head.right == this.root; assert tail.left == this.root; } assert nodes.isEmpty(); } private int visit( final Node n, final Node parent, final long parentExtentLength, final int depth, ObjectOpenHashSet<Node> nodes, ObjectOpenHashSet<Node> leaves, ObjectOpenHashSet<BitVector> references ) { if ( n == null ) return 0; if ( DDEBUG ) { for( int i = depth; i-- != 0; ) System.err.print( '\t' ); System.err.println( "Node " + n + " (parent extent length: " + parentExtentLength + ") Jump left: " + n.jumpLeft + " Jump right: " + n.jumpRight ); } assert parent == null || parent.extent().equals( n.extent().subVector( 0, parent.extentLength ) ); assert ( n.jumpLeft == null ) == ( n.jumpRight == null ); assert parentExtentLength < n.extentLength; assert n.parentExtentLength == parentExtentLength : n.parentExtentLength + " != " + parentExtentLength + " " + n; assert n.isLeaf() == ( n.extentLength == n.key.length() ); if ( n.isInternal() ) { assert references.add( n.key ); assert nodes.remove( n ) : n; assert map.keySet().contains( n.handle() ) : n; /* Check that jumps are correct. */ final long jumpLength = n.jumpLength(); Node jumpLeft = n.left; while( jumpLeft.isInternal() && jumpLength > jumpLeft.extentLength ) jumpLeft = jumpLeft.left; assert jumpLeft == n.jumpLeft : jumpLeft + " != " + n.jumpLeft + " (node: " + n + ")"; Node jumpRight = n.right; while( jumpRight.isInternal() && jumpLength > jumpRight.extentLength ) jumpRight = jumpRight.right; assert jumpRight == n.jumpRight : jumpRight + " != " + n.jumpRight + " (node: " + n + ")"; return 1 + visit( n.left, n, n.extentLength, depth + 1, nodes, leaves, references ) + visit( n.right, n, n.extentLength, depth + 1, nodes, leaves, references ); } else { assert leaves.add( n ); return 1; } } /** Sets the jump pointers of a node by searching exhaustively for * handles that are jumps of the node handle length. * * @param node the node whose jump pointers must be set. */ private static void setJumps( final Node node ) { if ( DDEBUG ) System.err.println( "setJumps(" + node + ")" ); final long jumpLength = node.jumpLength(); Node jump; for( jump = node.left; jump.isInternal() && jumpLength > jump.extentLength; ) jump = jump.jumpLeft; if ( ASSERTS ) assert jump.intercepts( jumpLength ); node.jumpLeft = jump; for( jump = node.right; jump.isInternal() && jumpLength > jump.extentLength; ) jump = jump.jumpRight; if ( ASSERTS ) assert jump.intercepts( jumpLength ); node.jumpRight = jump; } /** Fixes the right jumps of the ancestors of a node after an insertion. * * @param exitNode the exit node. * @param rightChild * @param leaf the new leaf. * @param stack a stack containing the 2-fat ancestors of <code>exitNode</code>. */ private static void fixRightJumpsAfterInsertion( final Node internal, Node exitNode, boolean rightChild, Node leaf, final ObjectArrayList<Node> stack ) { if ( DDEBUG ) System.err.println( "fixRightJumpsAfterInsertion(" + internal + ", " + exitNode + ", " + rightChild + ", " + leaf + ", " + stack ); final long lcp = leaf.parentExtentLength; Node toBeFixed = null; long jumpLength = -1; if ( ! rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != exitNode ) break; if ( jumpLength <= lcp ) toBeFixed.jumpLeft = internal; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != exitNode || jumpLength > lcp ) break; toBeFixed.jumpRight = internal; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); while( exitNode != null && toBeFixed.jumpRight != exitNode ) exitNode = exitNode.jumpRight; if ( exitNode == null ) return; toBeFixed.jumpRight = leaf; } } } /** Fixes the left jumps of the ancestors of a node after an insertion. * * @param exitNode the exit node. * @param rightChild * @param leaf the new leaf. * @param stack a stack containing the fat ancestors of <code>exitNode</code>. */ private static void fixLeftJumpsAfterInsertion( final Node internal, Node exitNode, boolean rightChild, Node leaf, final ObjectArrayList<Node> stack ) { if ( DDEBUG ) System.err.println( "fixLeftJumpsAfterInsertion(" + internal + ", " + exitNode + ", " + rightChild + ", " + leaf + ", " + stack ); final long lcp = leaf.parentExtentLength; Node toBeFixed = null; long jumpLength = -1; if ( rightChild ) { /* Nodes jumping to the right into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != exitNode ) break; if ( jumpLength <= lcp ) toBeFixed.jumpRight = internal; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != exitNode || jumpLength > lcp ) break; toBeFixed.jumpLeft = internal; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); while( exitNode != null && toBeFixed.jumpLeft != exitNode ) exitNode = exitNode.jumpLeft; if ( exitNode == null ) return; toBeFixed.jumpLeft = leaf; } } } /** Fixes the right jumps of the ancestors of a node after a deletion. * * @param parentExitNode the exit node. * @param rightChild * @param exitNode the new leaf. * @param stack a stack containing the 2-fat ancestors of <code>exitNode</code>. */ private static void fixRightJumpsAfterDeletion( Node otherNode, Node parentExitNode, boolean rightChild, Node exitNode, final ObjectArrayList<Node> stack ) { if ( DDEBUG ) System.err.println( "fixRightJumpsAfterDeletion(" + otherNode + ", " + parentExitNode + ", " + rightChild + ", " + exitNode + ", " + stack ); Node toBeFixed = null; long jumpLength = -1; if ( ! stack.isEmpty() ) stack.pop(); if ( ! rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != parentExitNode ) break; toBeFixed.jumpLeft = otherNode; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != parentExitNode ) break; toBeFixed.jumpRight = otherNode; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); if ( toBeFixed.jumpRight != exitNode ) break; jumpLength = toBeFixed.jumpLength(); while( ! otherNode.intercepts( jumpLength ) ) otherNode = otherNode.jumpRight; toBeFixed.jumpRight = otherNode; } } } /** Fixes the left jumps of the ancestors of a node after a deletion. * * @param parentExitNode the exit node. * @param rightChild * @param exitNode the new leaf. * @param stack a stack containing the 2-fat ancestors of <code>exitNode</code>. */ private static void fixLeftJumpsAfterDeletion( Node otherNode, Node parentExitNode, boolean rightChild, Node exitNode, final ObjectArrayList<Node> stack ) { if ( DDEBUG ) System.err.println( "fixLeftJumpsAfterDeletion(" + otherNode + ", " + parentExitNode + ", " + rightChild + ", " + exitNode + ", " + stack ); Node toBeFixed = null; long jumpLength = -1; if ( ! stack.isEmpty() ) stack.pop(); if ( rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != parentExitNode ) break; toBeFixed.jumpRight = otherNode; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != parentExitNode ) break; toBeFixed.jumpLeft = otherNode; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); if ( toBeFixed.jumpLeft != exitNode ) break; jumpLength = toBeFixed.jumpLength(); while( ! otherNode.intercepts( jumpLength ) ) otherNode = otherNode.jumpLeft; toBeFixed.jumpLeft = otherNode; } } } @SuppressWarnings("unchecked") public boolean remove( final Object k ) { final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)k ) ); if ( DDEBUG ) System.err.println( "remove(" + v + ")" ); if ( DDEBUG ) System.err.println( "Map: " + map + " root: " + root ); if ( size == 0 ) return false; if ( size == 1 ) { if ( ! root.key.equals( v ) ) return false; root = null; size = 0; if ( ASSERTS ) assertTrie(); return true; } final ObjectArrayList<Node> stack = new ObjectArrayList<Node>( 64 ); Node parentExitNode; boolean rightLeaf, rightChild = false; Node exitNode; long lcp; final long[] state = Hashes.preprocessMurmur( v, 0 ); parentExitNode = getParentExitNode( v, state, stack, false ); rightLeaf = parentExitNode != null && parentExitNode.extentLength < v.length() && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightLeaf ? parentExitNode.right : parentExitNode.left ); lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ! exitNode.intercepts( lcp ) ) { /* A mistake. We redo the query in exact mode. */ stack.clear(); parentExitNode = getParentExitNode( v, state, stack, true ); rightLeaf = parentExitNode != null && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightLeaf ? parentExitNode.right : parentExitNode.left ); lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ASSERTS ) assert exitNode.intercepts( lcp ); } if ( DDDEBUG ) System.err.println( "Exit node " + exitNode ); if ( ! exitNode.key.equals( v ) ) return false; // Not found final Node otherNode = rightLeaf ? parentExitNode.left : parentExitNode.right; final boolean otherNodeIsInternal = otherNode.isInternal(); if ( parentExitNode != null && parentExitNode != root ) { // Let us fix grandpa's child pointer. final int stackSize = stack.size(); Node grandParentExitNode = getGrandParentExitNode( v, state, stack, false ); if ( grandParentExitNode == null || grandParentExitNode.left != parentExitNode && grandParentExitNode.right != parentExitNode ) { // Clean up stack from garbage left from mistaken invocation stack.size( stackSize - 1 ); stack.push( parentExitNode ); grandParentExitNode = getGrandParentExitNode( v, state, stack, true ); } if ( rightChild = ( grandParentExitNode.right == parentExitNode ) ) grandParentExitNode.right = otherNode; else grandParentExitNode.left = otherNode; } final long t = parentExitNode.handleLength() | otherNode.handleLength(); final boolean cutLow = ( t & -t & otherNode.handleLength() ) != 0; if ( DDEBUG ) System.err.println( "lcp: " + lcp ); if ( parentExitNode == root ) root = otherNode; // Fix leaf reference if not null final Node refersToExitNode = exitNode.reference; if ( refersToExitNode == null ) parentExitNode.reference.reference = null; else { refersToExitNode.reference = parentExitNode.reference; refersToExitNode.reference.reference = refersToExitNode; refersToExitNode.key = refersToExitNode.reference.key; } // Fix doubly-linked list remove( exitNode ); if ( DDDEBUG ) System.err.println( "Cut " + ( cutLow ? "low" : "high") + "; leaf on the " + ( rightLeaf ? "right" : "left") + "; other node is " + ( otherNodeIsInternal ? "internal" : "a leaf") ); if ( rightLeaf ) fixRightJumpsAfterDeletion( otherNode, parentExitNode, rightChild, exitNode, stack ); else fixLeftJumpsAfterDeletion( otherNode, parentExitNode, rightChild, exitNode, stack ); if ( cutLow && otherNodeIsInternal ) { map.remove( otherNode ); otherNode.parentExtentLength = parentExitNode.parentExtentLength; map.replace( otherNode ); setJumps( otherNode ); } else { otherNode.parentExtentLength = parentExitNode.parentExtentLength; map.remove( parentExitNode ); } size if ( ASSERTS ) { assertTrie(); assert ! contains( k ); } return true; } @Override public boolean add( final T k ) { final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( k ) ); if ( DDEBUG ) System.err.println( "add(" + v + ")" ); if ( DDEBUG ) System.err.println( "Map: " + map + " root: " + root ); if ( size == 0 ) { root = new Node(); root.key = v; root.extentLength = v.length(); root.parentExtentLength = 0; root.reference = root; addAfter( head, root ); size++; if ( ASSERTS ) assertTrie(); return true; } final ObjectArrayList<Node> stack = new ObjectArrayList<Node>( 64 ); Node parentExitNode; boolean rightChild; Node exitNode; long lcp; final long[] state = Hashes.preprocessMurmur( v, 0 ); parentExitNode = getParentExitNode( v, state, stack, false ); rightChild = parentExitNode != null && parentExitNode.extentLength < v.length() && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ! exitNode.intercepts( lcp ) ) { /* A mistake. We redo the query in exact mode. */ stack.clear(); parentExitNode = getParentExitNode( v, state, stack, true ); rightChild = parentExitNode != null && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ASSERTS ) assert exitNode.intercepts( lcp ); } if ( DDDEBUG ) System.err.println( "Exit node " + exitNode ); if ( exitNode.key.equals( v ) ) return false; // Already there final boolean exitDirection = v.getBoolean( lcp ); final boolean cutLow = lcp >= exitNode.handleLength(); if ( DDEBUG ) System.err.println( "lcp: " + lcp ); Node leaf = new Node(); Node internal = new Node(); final boolean exitNodeIsInternal = exitNode.isInternal(); leaf.key = v; leaf.extentLength = v.length(); leaf.parentExtentLength = lcp; leaf.reference = internal; internal.key = leaf.key; internal.reference = leaf; internal.parentExtentLength = exitNode.parentExtentLength; internal.extentLength = lcp; if ( exitDirection ) { internal.jumpRight = internal.right = leaf; internal.left = exitNode; internal.jumpLeft = cutLow && exitNodeIsInternal ? exitNode.jumpLeft : exitNode; } else { internal.jumpLeft = internal.left = leaf; internal.right = exitNode; internal.jumpRight = cutLow && exitNodeIsInternal ? exitNode.jumpRight : exitNode; } if ( exitNode == root ) root = internal; // Update root else { if ( rightChild ) parentExitNode.right = internal; else parentExitNode.left = internal; } if ( DDDEBUG ) System.err.println( "Cut " + ( cutLow ? "low" : "high") + "; exit to the " + ( exitDirection ? "right" : "left") ); if ( exitDirection ) fixRightJumpsAfterInsertion( internal, exitNode, rightChild, leaf, stack ); else fixLeftJumpsAfterInsertion( internal, exitNode, rightChild, leaf, stack ); if ( cutLow && exitNodeIsInternal ) { map.replace( internal ); exitNode.parentExtentLength = lcp; map.addNew( exitNode ); setJumps( exitNode ); } else { exitNode.parentExtentLength = lcp; map.addNew( internal ); } if ( DDEBUG ) System.err.println( "After insertion, map: " + map + " root: " + root ); size++; /* We find a predecessor or successor to insert the new leaf in the doubly linked list. */ if ( exitDirection ) { while( exitNode.isInternal() ) exitNode = exitNode.jumpRight; addAfter( exitNode, leaf ); } else { while( exitNode.isInternal() ) exitNode = exitNode.jumpLeft; addBefore( exitNode, leaf ); } if ( ASSERTS ) assertTrie(); if ( ASSERTS ) assert contains( k ); return true; } private static final boolean equals( LongArrayBitVector a, LongArrayBitVector b, long start, long end ) { int startWord = (int)( start >>> LongArrayBitVector.LOG2_BITS_PER_WORD ); final int endWord = (int)( end >>> LongArrayBitVector.LOG2_BITS_PER_WORD ); final int startBit = (int)( start & LongArrayBitVector.WORD_MASK ); final int endBit = (int)( end & LongArrayBitVector.WORD_MASK ); final long[] aBits = a.bits(); final long[] bBits = b.bits(); if ( startWord == endWord ) return ( ( aBits[ startWord ] ^ bBits[ startWord ] ) & ( ( 1L << ( endBit - startBit ) ) - 1 ) << startBit ) == 0; if ( ( ( aBits[ startWord ] ^ bBits[ startWord ] ) & ( -1L << startBit ) ) != 0 ) return false; for( ++startWord; startWord < endWord; startWord++ ) if ( aBits[ startWord ] != bBits[ startWord ] ) return false; if ( ( ( aBits[ endWord ] ^ bBits[ endWord] ) & ( 1L << endBit) - 1 ) != 0 ) return false; return true; } /** Returns the parent of the exit node of a given bit vector. * * @param v a bit vector. * @param stack if not <code>null</code>, a stack that will be filled with the <em>fat nodes</em> along the path to the parent of the exit node. * @param exact if true, the map defining the trie will be accessed in exact mode. * @return the parent of the exit node of <code>v</code>, or <code>null</code> if the exit node is the root; * if <code>exact</code> is false, with low probability * the result might be wrong. */ public Node getParentExitNode( final LongArrayBitVector v, final long[] state, final ObjectArrayList<Node> stack, final boolean exact ) { if ( ASSERTS ) assert size > 0; if ( size == 1 ) return null; if ( DDDEBUG ) System.err.println( "getParentExitNode(" + v + ", " + exact + ")" ); final Node parent = fatBinarySearch( v, state, stack, exact, 0, v.length() ); if ( DDDEBUG ) System.err.println( "Parent exit node: " + parent ); return parent; } /** Returns the parent of the exit node of a given bit vector. * * @param v a bit vector. * @param stack if not <code>null</code>, a stack that will be filled with the <em>fat nodes</em> along the path to the parent of the exit node. * @param exact if true, the map defining the trie will be accessed in exact mode. * @return the parent of the exit node of <code>v</code>, or <code>null</code> if the exit node is the root; * if <code>exact</code> is false, with low probability * the result might be wrong. */ public Node getGrandParentExitNode( final LongArrayBitVector v, final long[] state, final ObjectArrayList<Node> stack, final boolean exact ) { if ( ASSERTS ) assert size > 0; if ( size < 3 ) return null; if ( DDDEBUG ) System.err.println( "getGrandParentExitNode(" + v + ", " + stack + " , " + exact + ")" ); // Grandpa is already on the stack. if ( stack.size() > 1 && stack.peek( 1 ).extentLength == stack.peek( 0 ).parentExtentLength ) return stack.peek( 1 ); final Node parentExitNode = stack.pop(); long l = stack.size() > 0 ? stack.top().extentLength : 0, r = parentExitNode.parentExtentLength + 1; final Node parent = fatBinarySearch( v, state, stack, exact, l, r ); if ( ASSERTS ) assert parent == null || parent.right == parentExitNode || parent.left == parentExitNode; stack.push( parentExitNode ); return parent; } private Node fatBinarySearch( final LongArrayBitVector v, final long[] state, final ObjectArrayList<Node> stack, final boolean exact, long l, long r ) { final int logLength = Fast.mostSignificantBit( r ); long checkMask = 1L << logLength; long computeMask = -1L << logLength; Node node = null, parent = null; while( r - l > 1 ) { if ( ASSERTS ) assert logLength > -1; if ( DDDEBUG ) System.err.println( "(" + l + ".." + r + "); checking for fatness " + checkMask ); if ( ( l & checkMask ) != ( r - 1 & checkMask ) ) { // Quick test for a 2-fattest number divisible by 2^i in (l..r). final long f = ( r - 1 ) & computeMask; if ( DDDEBUG ) System.err.println( "Inquiring with key " + v.subVector( 0, f ) + " (" + f + ")" ); node = map.get( Hashes.murmur( v, f, state ), v, f, exact ); if ( node == null ) { if ( DDDEBUG ) System.err.println( "Missing" ); r = f; } else { long g = node.extentLength; if ( DDDEBUG ) System.err.println( "Found extent of length " + g ); if ( g >= f && g < r && equals( node.key, v, f, g ) ) { if ( stack != null ) stack.push( node ); parent = node; l = g; } else r = f; } } computeMask >>= 1; checkMask >>= 1; } if ( DDDEBUG ) System.err.println( "Final length " + l + " node: " + parent ); if ( ASSERTS ) { boolean rightChild; Node exitNode; long lcp; rightChild = parent != null && parent.extentLength < v.length() && v.getBoolean( parent.extentLength ); exitNode = parent == null ? root : ( rightChild ? parent.right : parent.left ); lcp = exitNode.key.longestCommonPrefixLength( v ); if ( exitNode.intercepts( lcp ) ) { // We can do asserts only if the result is correct /* If parent is null, the extent of the root must not be a prefix of v. */ if ( parent == null ) assert root.key.longestCommonPrefixLength( v ) < root.extentLength; else { assert parent.extentLength == l; /* If parent is not null, the extent of the parent must be a prefix of v, * and the extent of the exit node must be either v, or not a prefix of v. */ assert ! exact || parent.extent().longestCommonPrefixLength( v ) == parent.extentLength; if ( stack != null ) { /** We check that the stack contains exactly all handles that are backjumps * of the length of the extent of the parent. */ l = parent.extentLength; while( l != 0 ) { final Node t = map.get( parent.key.subVector( 0, l ), true ); if ( t != null ) assert stack.contains( t ); l ^= ( l & -l ); } /** We check that the stack contains the nodes you would obtain by searching from * the top for nodes to fix. */ long left = 0; for( int i = 0; i < stack.size(); i++ ) { assert stack.get( i ).handleLength() == twoFattest( left, parent.extentLength ) : stack.get( i ).handleLength() + " != " + twoFattest( left, parent.extentLength ) + " " + i + " " + stack ; left = stack.get( i ).extentLength; } } } } } return parent; } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if ( DDEBUG ) System.err.println( "contains(" + o + ")" ); if ( size == 0 ) return false; final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)o ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); Node parentExitNode = getParentExitNode( v, state, null, false ); boolean rightChild = parentExitNode != null && parentExitNode.extentLength < v.length() && v.getBoolean( parentExitNode.extentLength ); Node exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); final long lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ! exitNode.intercepts( lcp ) ) { parentExitNode = getParentExitNode( v, state, null, true ); rightChild = parentExitNode != null && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); if ( ASSERTS ) assert exitNode.intercepts( exitNode.key.longestCommonPrefixLength( v ) ); } return exitNode.key.equals( v ); } @SuppressWarnings("unchecked") public Node pred( final Object o ) { if ( size == 0 ) return null; final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)o ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); Node parentExitNode = getParentExitNode( v, state, null, false ); boolean rightChild = parentExitNode != null && parentExitNode.extentLength < v.length() && v.getBoolean( parentExitNode.extentLength ); Node exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); final long lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ! exitNode.intercepts( lcp ) ) { parentExitNode = getParentExitNode( v, state, null, true ); rightChild = parentExitNode != null && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); if ( ASSERTS ) assert exitNode.intercepts( exitNode.key.longestCommonPrefixLength( v ) ); } if ( rightChild ) { while( exitNode.jumpRight != null ) exitNode = exitNode.jumpRight; return exitNode; } else { while( exitNode.jumpLeft != null ) exitNode = exitNode.jumpLeft; return exitNode.left; } } @SuppressWarnings("unchecked") public Node succ( final Object o ) { if ( size == 0 ) return null; final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)o ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); Node parentExitNode = getParentExitNode( v, state, null, false ); boolean rightChild = parentExitNode != null && parentExitNode.extentLength < v.length() && v.getBoolean( parentExitNode.extentLength ); Node exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); final long lcp = exitNode.key.longestCommonPrefixLength( v ); if ( ! exitNode.intercepts( lcp ) ) { parentExitNode = getParentExitNode( v, state, null, true ); rightChild = parentExitNode != null && v.getBoolean( parentExitNode.extentLength ); exitNode = parentExitNode == null ? root : ( rightChild ? parentExitNode.right : parentExitNode.left ); if ( ASSERTS ) assert exitNode.intercepts( exitNode.key.longestCommonPrefixLength( v ) ); } if ( rightChild ) { while( exitNode.jumpRight != null ) exitNode = exitNode.jumpRight; return exitNode.right; } else { while( exitNode.jumpLeft != null ) exitNode = exitNode.jumpLeft; return exitNode; } } private void writeObject( final ObjectOutputStream s ) throws IOException { s.defaultWriteObject(); if ( size > 0 ) writeNode( root, s ); } private static void writeNode( final Node node, final ObjectOutputStream s ) throws IOException { s.writeBoolean( node.isInternal() ); s.writeLong( node.extentLength - node.parentExtentLength ); if ( node.isInternal() ) { writeNode( node.left, s ); writeNode( node.right, s ); } else BitVectors.writeFast( node.key, s ); } private void readObject( final ObjectInputStream s ) throws IOException, ClassNotFoundException { s.defaultReadObject(); initHeadTail(); map = new Map( size ); System.err.println( map.length ); if ( size > 0 ) root = readNode( s, 0, 0, map, new ObjectArrayList<Node>(), new ObjectArrayList<Node>(), new IntArrayList(), new IntArrayList(), new BooleanArrayList() ); if ( ASSERTS ) assertTrie(); } /** Reads recursively a node of the trie. * * @param s the object input stream. * @param depth the depth of the node to be read. * @param parentExtentLength the length of the extent of the parent node. * @param map the map representing the trie. * @param leafStack a stack that cumulates leaves as they are found: internal nodes extract references from this stack when their visit is completed. * @param jumpStack a stack that cumulates nodes that need jump pointer fixes. * @param depthStack a stack parallel to <code>jumpStack</code>, providing the depth of the corresponding node. * @param segmentStack a stack of integers representing the length of maximal constant subsequences of the string of directions taken up to the current node; for instance, if we reached the current node by 1/1/0/0/0/1/0/0, the stack will contain 2,3,1,2. * @param dirStack a stack parallel to <code>segmentStack</code>: for each element, whether it counts left or right turns. * @return the subtree rooted at the next node in the stream. */ private Node readNode( final ObjectInputStream s, final int depth, final long parentExtentLength, final Map map, final ObjectArrayList<Node> leafStack, final ObjectArrayList<Node> jumpStack, final IntArrayList depthStack, final IntArrayList segmentStack, final BooleanArrayList dirStack ) throws IOException, ClassNotFoundException { final boolean isInternal = s.readBoolean(); final long pathLength = s.readLong(); final Node node = new Node(); node.parentExtentLength = parentExtentLength; node.extentLength = parentExtentLength + pathLength; if ( ! dirStack.isEmpty() ) { /* We cannot fix the jumps of nodes that are more than this number of levels up in the tree. */ final int maxDepthDelta = segmentStack.topInt(); final boolean dir = dirStack.topBoolean(); Node anc; int d; long jumpLength; do { jumpLength = ( anc = jumpStack.top() ).jumpLength(); d = depthStack.topInt(); /* To be fixable, a node must be within the depth limit, and we must intercept its jump length (note that * we cannot use .intercept() as the state of node is not yet consistent). If a node cannot be fixed, no * node higher in the stack can. */ if ( depth - d <= maxDepthDelta && jumpLength > parentExtentLength && ( ! isInternal || jumpLength <= node.extentLength ) ) { if ( DDEBUG ) System.err.println( "Setting " + ( dir ? "right" : "left" ) + " jump pointer of " + anc + " to " + node ); if ( dir ) anc.jumpRight = node; else anc.jumpLeft = node; jumpStack.pop(); depthStack.popInt(); } else break; } while( ! jumpStack.isEmpty() ); } if ( isInternal ) { if ( dirStack.isEmpty() || dirStack.topBoolean() != false ) { segmentStack.push( 1 ); dirStack.push( false ); } else segmentStack.push( segmentStack.popInt() + 1 ); jumpStack.push( node ); depthStack.push( depth ); if ( DDEBUG ) System.err.println( "Recursing into left node... " ); node.left = readNode( s, depth + 1, node.extentLength, map, leafStack, jumpStack, depthStack, segmentStack, dirStack ); int top = segmentStack.popInt(); if ( top != 1 ) segmentStack.push( top - 1 ); else dirStack.popBoolean(); if ( dirStack.isEmpty() || dirStack.topBoolean() != true ) { segmentStack.push( 1 ); dirStack.push( true ); } else segmentStack.push( segmentStack.popInt() + 1 ); jumpStack.push( node ); depthStack.push( depth ); if ( DDEBUG ) System.err.println( "Recursing into right node... " ); node.right = readNode( s, depth + 1, node.extentLength, map, leafStack, jumpStack, depthStack, segmentStack, dirStack ); top = segmentStack.popInt(); if ( top != 1 ) segmentStack.push( top - 1 ); else dirStack.popBoolean(); /* We assign the reference leaf, and store the associated key. */ final Node referenceLeaf = leafStack.pop(); node.key = referenceLeaf.key; node.reference = referenceLeaf; referenceLeaf.reference = node; map.addNew( node ); if ( ASSERTS ) { // Check jump pointers. Node t; t = node.left; while( t.isInternal() && ! t.intercepts( node.jumpLength() ) ) t = t.left; assert node.jumpLeft == t : node.jumpLeft + " != " + t + " (" + node + ")"; t = node.right; while( t.isInternal() && ! t.intercepts( node.jumpLength() ) ) t = t.right; assert node.jumpRight == t : node.jumpRight + " != " + t + " (" + node + ")"; } } else { node.key = BitVectors.readFast( s ); leafStack.push( node ); addBefore( tail, node ); } return node; } public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException { final SimpleJSAP jsap = new SimpleJSAP( ZFastTrie.class.getName(), "Builds an PaCo trie-based monotone minimal perfect hash function reading a newline-separated list of strings.", new Parameter[] { new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ), new Switch( "iso", 'i', "iso", "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)." ), new Switch( "bitVector", 'b', "bit-vector", "Build a trie of bit vectors, rather than a trie of strings." ), new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ), new UnflaggedOption( "trie", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised z-fast trie." ), new UnflaggedOption( "stringFile", JSAP.STRING_PARSER, "-", JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "The name of a file containing a newline-separated list of strings, or - for standard input." ), }); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final String functionName = jsapResult.getString( "trie" ); final String stringFile = jsapResult.getString( "stringFile" ); final Charset encoding = (Charset)jsapResult.getObject( "encoding" ); final boolean zipped = jsapResult.getBoolean( "zipped" ); final boolean iso = jsapResult.getBoolean( "iso" ); final boolean bitVector = jsapResult.getBoolean( "bitVector" ); final InputStream inputStream = "-".equals( stringFile ) ? System.in : new FileInputStream( stringFile ); final LineIterator lineIterator = new LineIterator( new FastBufferedReader( new InputStreamReader( zipped ? new GZIPInputStream( inputStream ) : inputStream, encoding ) ) ); final TransformationStrategy<CharSequence> transformationStrategy = iso ? TransformationStrategies.prefixFreeIso() : TransformationStrategies.prefixFreeUtf16(); ProgressLogger pl = new ProgressLogger(); pl.itemsName = "keys"; pl.displayFreeMemory = true; pl.start( "Adding keys..." ); if ( bitVector ) { ZFastTrie<LongArrayBitVector> zFastTrie = new ZFastTrie<LongArrayBitVector>( TransformationStrategies.identity() ); while( lineIterator.hasNext() ) { zFastTrie.add( LongArrayBitVector.copy( transformationStrategy.toBitVector( lineIterator.next() ) ) ); pl.lightUpdate(); } pl.done(); BinIO.storeObject( zFastTrie, functionName ); } else { ZFastTrie<CharSequence> zFastTrie = new ZFastTrie<CharSequence>( transformationStrategy ); while( lineIterator.hasNext() ) { zFastTrie.add( lineIterator.next() ); pl.lightUpdate(); } pl.done(); BinIO.storeObject( zFastTrie, functionName ); } LOGGER.info( "Completed." ); } @Override public ObjectBidirectionalIterator<T> iterator() { // TODO Auto-generated method stub return null; } @Override public ObjectSortedSet<T> headSet( T arg0 ) { // TODO Auto-generated method stub return null; } @Override public ObjectBidirectionalIterator<T> iterator( T arg0 ) { // TODO Auto-generated method stub return null; } @Override public ObjectSortedSet<T> subSet( T arg0, T arg1 ) { // TODO Auto-generated method stub return null; } @Override public ObjectSortedSet<T> tailSet( T arg0 ) { // TODO Auto-generated method stub return null; } @Override public Comparator<? super T> comparator() { // TODO Auto-generated method stub return null; } @Override public T first() { // TODO Auto-generated method stub return null; } @Override public T last() { // TODO Auto-generated method stub return null; } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.annotations.*; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.util.Util; import java.io.DataInput; import java.io.DataOutput; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.*; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; /** * Catches SUSPECT events traveling up the stack. Verifies that the suspected member is really dead. If yes, * passes SUSPECT event up the stack, otherwise discards it. Has to be placed somewhere above the FD layer and * below the GMS layer (receiver of the SUSPECT event). Note that SUSPECT events may be reordered by this protocol. * @author Bela Ban */ @MBean(description="Double-checks suspicions reports") public class VERIFY_SUSPECT extends Protocol implements Runnable { @Property(description="Number of millisecs to wait for a response from a suspected member") protected long timeout=2000; @Property(description="Number of verify heartbeats sent to a suspected member") protected int num_msgs=1; @Property(description="Use InetAddress.isReachable() to verify suspected member instead of regular messages") protected boolean use_icmp; @Property(description="Send the I_AM_NOT_DEAD message back as a multicast rather than as multiple unicasts " + "(default is false)") protected boolean use_mcast_rsps; @LocalAddress @Property(description="Interface for ICMP pings. Used if use_icmp is true " + "The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK", systemProperty={Global.BIND_ADDR}) protected InetAddress bind_addr; // interface for ICMP pings /** network interface to be used to send the ICMP packets */ protected NetworkInterface intf; protected Address local_addr; // a list of suspects, ordered by time when a SUSPECT event needs to be sent up protected final DelayQueue<Entry> suspects=new DelayQueue<>(); protected volatile Thread timer; protected volatile boolean running; @ManagedAttribute(description = "List of currently suspected members") public String getSuspects() { synchronized(suspects) { return suspects.toString(); } } public VERIFY_SUSPECT() { } public VERIFY_SUSPECT setTimeout(long timeout) { this.timeout = timeout; return this; } public long getTimeout() { return timeout; } public Object down(Event evt) { switch(evt.getType()) { case Event.SET_LOCAL_ADDRESS: local_addr=evt.getArg(); break; case Event.VIEW_CHANGE: View v=evt.getArg(); adjustSuspectedMembers(v.getMembers()); break; } return down_prot.down(evt); } public Object up(Event evt) { switch(evt.getType()) { case Event.SUSPECT: // it all starts here ... // todo: change to collections in 4.1 Collection<Address> s=evt.arg() instanceof Address? Collections.singletonList(evt.arg()) : evt.arg(); if(s == null) return null; s.remove(local_addr); // ignoring suspect of self if(use_icmp) s.forEach(this::verifySuspectWithICMP); else verifySuspect(s); return null; // don't pass up; we will decide later (after verification) whether to pass it up case Event.CONFIG: if(bind_addr == null) { Map<String,Object> config=evt.getArg(); bind_addr=(InetAddress)config.get("bind_addr"); } } return up_prot.up(evt); } public Object up(Message msg) { VerifyHeader hdr=msg.getHeader(this.id); if(hdr == null) return up_prot.up(msg); switch(hdr.type) { case VerifyHeader.ARE_YOU_DEAD: if(hdr.from == null) { log.error(Util.getMessage("AREYOUDEADHdrFromIsNull")); return null; } Address target=use_mcast_rsps? null : hdr.from; for(int i=0; i < num_msgs; i++) { Message rsp=new Message(target).setFlag(Message.Flag.INTERNAL) .putHeader(this.id, new VerifyHeader(VerifyHeader.I_AM_NOT_DEAD, local_addr)); down_prot.down(rsp); } return null; case VerifyHeader.I_AM_NOT_DEAD: if(hdr.from == null) { log.error(Util.getMessage("IAMNOTDEADHdrFromIsNull")); return null; } unsuspect(hdr.from); return null; } return null; } /** * Removes all elements from suspects that are <em>not</em> in the new membership */ protected void adjustSuspectedMembers(List<Address> new_mbrship) { synchronized(suspects) { suspects.removeIf(entry -> !new_mbrship.contains(entry.suspect)); } } /** * Started when a suspected member is added to suspects. Iterates over the queue as long as there are suspects in * it and removes a suspect when the timeout for it has elapsed. Sends up a SUSPECT event for every removed suspect. * When a suspected member is un-suspected, the member is removed from the queue. */ public void run() { for(;;) { synchronized(suspects) { // atomically checks for the empty queue and sets running to false (JGRP-2287) if(suspects.isEmpty()) { running=false; return; } } try { Entry entry=suspects.poll(timeout,TimeUnit.MILLISECONDS); if(entry != null) { List<Entry> expired=new ArrayList<>(suspects.size()); suspects.drainTo(expired); // let's see if we can remove more elements which have also expired Collection<Address> suspect_list=new LinkedHashSet<>(); suspect_list.add(entry.suspect); expired.forEach(e -> suspect_list.add(e.suspect)); log.debug("%s %s dead (passing up SUSPECT event)", suspect_list, suspect_list.size() > 1? "are" : "is"); up_prot.up(new Event(Event.SUSPECT, suspect_list)); } } catch(InterruptedException e) { if(!running) break; } } } /** * Sends ARE_YOU_DEAD message to suspected_mbr, wait for return or timeout */ protected void verifySuspect(Collection<Address> mbrs) { if(mbrs == null || mbrs.isEmpty()) return; if(addSuspects(mbrs)) { startTimer(); // start timer before we send out are you dead messages log.trace("verifying that %s %s dead", mbrs, mbrs.size() == 1? "is" : "are"); } for(Address mbr: mbrs) { for(int i=0; i < num_msgs; i++) { Message msg=new Message(mbr).setFlag(Message.Flag.INTERNAL) .putHeader(this.id, new VerifyHeader(VerifyHeader.ARE_YOU_DEAD, local_addr)); down_prot.down(msg); } } } protected void verifySuspectWithICMP(Address suspected_mbr) { InetAddress host=suspected_mbr instanceof IpAddress? ((IpAddress)suspected_mbr).getIpAddress() : null; if(host == null) throw new IllegalArgumentException("suspected_mbr is not of type IpAddress - FD_ICMP only works with these"); try { if(log.isTraceEnabled()) log.trace("pinging host " + suspected_mbr + " using interface " + intf); long start=getCurrentTimeMillis(), stop; boolean rc=host.isReachable(intf, 0, (int)timeout); stop=getCurrentTimeMillis(); if(rc) // success log.trace("successfully received response from " + host + " (after " + (stop-start) + "ms)"); else { // failure log.debug("failed pinging " + suspected_mbr + " after " + (stop-start) + "ms; passing up SUSPECT event"); removeSuspect(suspected_mbr); up_prot.up(new Event(Event.SUSPECT, Collections.singletonList(suspected_mbr))); } } catch(Exception ex) { log.error(Util.getMessage("FailedPinging"),suspected_mbr, ex); } } /** * Adds suspected members to the suspect list. Returns true if a member is not present and the timer is not running. * @param list The list of suspected members * @return true if the timer needs to be started, or false otherwise */ protected boolean addSuspects(Collection<Address> list) { if(list == null || list.isEmpty()) return false; boolean added=false; synchronized(suspects) { for(Address suspected_mbr : list) { boolean found_dupe=suspects.stream().anyMatch(e -> e.suspect.equals(suspected_mbr)); if(!found_dupe) { suspects.add(new Entry(suspected_mbr, getCurrentTimeMillis() + timeout)); added=true; } } return (added && !running) && (running=true); } } protected boolean removeSuspect(Address suspect) { if(suspect == null) return false; synchronized(suspects) { return suspects.removeIf(e -> Objects.equals(e.suspect, suspect)); } } protected void clearSuspects() { synchronized(suspects) { suspects.clear(); } } public void unsuspect(Address mbr) { boolean removed=mbr != null && removeSuspect(mbr); if(removed) { log.trace("member " + mbr + " was unsuspected"); down_prot.down(new Event(Event.UNSUSPECT, mbr)); up_prot.up(new Event(Event.UNSUSPECT, mbr)); } } protected synchronized void startTimer() { timer=getThreadFactory().newThread(this,"VERIFY_SUSPECT.TimerThread"); timer.setDaemon(true); timer.start(); } public void init() throws Exception { super.init(); if(bind_addr != null) intf=NetworkInterface.getByInetAddress(bind_addr); } public synchronized void stop() { clearSuspects(); running=false; if(timer != null && timer.isAlive()) { Thread tmp=timer; timer=null; tmp.interrupt(); } timer=null; } private static long getCurrentTimeMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } protected static class Entry implements Delayed { protected final Address suspect; protected final long target_time; public Entry(Address suspect, long target_time) { this.suspect=suspect; this.target_time=target_time; } public int compareTo(Delayed o) { Entry other=(Entry)o; long my_delay=getDelay(TimeUnit.MILLISECONDS), other_delay=other.getDelay(TimeUnit.MILLISECONDS); return Long.compare(my_delay, other_delay); } public long getDelay(TimeUnit unit) { long delay=target_time - getCurrentTimeMillis(); return unit.convert(delay, TimeUnit.MILLISECONDS); } public String toString() { return suspect + ": " + target_time; } } public static class VerifyHeader extends Header { static final short ARE_YOU_DEAD=1; // 'from' is sender of verify msg static final short I_AM_NOT_DEAD=2; // 'from' is suspected member short type=ARE_YOU_DEAD; Address from; // member who wants to verify that suspected_mbr is dead public VerifyHeader() { } // used for externalization VerifyHeader(short type) { this.type=type; } VerifyHeader(short type, Address from) { this(type); this.from=from; } public short getMagicId() {return 54;} public Supplier<? extends Header> create() {return VerifyHeader::new;} public String toString() { switch(type) { case ARE_YOU_DEAD: return "[VERIFY_SUSPECT: ARE_YOU_DEAD]"; case I_AM_NOT_DEAD: return "[VERIFY_SUSPECT: I_AM_NOT_DEAD]"; default: return "[VERIFY_SUSPECT: unknown type (" + type + ")]"; } } public void writeTo(DataOutput out) throws Exception { out.writeShort(type); Util.writeAddress(from, out); } public void readFrom(DataInput in) throws Exception { type=in.readShort(); from=Util.readAddress(in); } public int serializedSize() { return Global.SHORT_SIZE + Util.size(from); } } }
package bluebell.utils.ebmd; import bluebell.utils.ebmd.IArgSpec; import bluebell.utils.ebmd.ArgSpec; import bluebell.utils.ebmd.ArgSpecVars; import bluebell.utils.ebmd.ArgSpecVarsVisitor; import bluebell.utils.ebmd.IndirectArgSpec; import bluebell.utils.ebmd.Promotion; import bluebell.utils.ebmd.PolyFn; import bluebell.utils.ReadAndUpdateMachine; import bluebell.utils.ReadAndUpdateMachineSettings; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Collections; import java.util.concurrent.Callable; import java.lang.Runnable; import bluebell.utils.GraphUtils; import bluebell.utils.INeighborhoodFunction; import java.util.List; public class Registry { private ReadAndUpdateMachine _raum = new ReadAndUpdateMachine( ReadAndUpdateMachineSettings.debugSettings()); private Settings _settings; private int _mutationCounter = 0; private int _rebuiltAt = -1; private HashMap<Object, ArgSpecVars> _registry = new HashMap<Object, ArgSpecVars>(); public Registry(Settings s) { _settings = s; } public Settings getSettings() { return _settings; } public void registerIndirection(Object key, Object target) { registerArgSpec(key, new IndirectArgSpec(target)); } public void registerArgSpec(Object key, IArgSpec src) { _raum.withUpdate(new Callable<Integer>() { public Integer call() { if (src == null) { throw new RuntimeException("Provided null argspec"); } _mutationCounter++; ArgSpecVars vars = _registry.get(key); if (vars != null) { vars.argSpec = src; } else { vars = new ArgSpecVars(); vars.argSpec = src; _registry.put(key, vars); } return 0; } }); } public void registerArgSpecUnion(Object key) { registerArgSpec(key, new ArgSpecUnion()); } public ArgSpecVars trackIndirections( Object key, ArgSpecVarsVisitor v) { return ArgSpecVars.trackIndirections(_registry, key, v); } public IArgSpec resolve(Object key) { return trackIndirections(key, null).argSpec; } public HashMap<Object, Promotion> getPromotions(Object key) { HashMap<Object, Promotion> dst = new HashMap<Object, Promotion>(); trackIndirections(key, new ArgSpecVarsVisitor() { public void visit(ArgSpecVars vars) { dst.putAll(vars.promotions); } }); return dst; } private ArgSpecVars getOrMakeArgVarsAtKey(Object k) { ArgSpecVars x = _registry.get(k); if (x == null) { x = new ArgSpecVars(); _registry.put(k, x); return x; } else { return x; } } public void extendArgSpec(Object dstKey, Object src) { _raum.withUpdate(new Callable<Integer>() { public Integer call() { _mutationCounter++; getOrMakeArgVarsAtKey(dstKey).extensions.add(src); return 0; } }); } public void registerPromotion( Object dstKey, Promotion prom, Object srcKey) { _raum.withUpdate(new Callable<Integer>() { public Integer call() { _mutationCounter++; getOrMakeArgVarsAtKey(dstKey) .promotions .put(srcKey, prom.withSrcDst( srcKey, dstKey)); return 0; } }); } private ArrayList<PromotionPath> listPromotionPathsSub( Object dstKey, HashSet<Object> visited) { ArrayList<PromotionPath> result = new ArrayList<PromotionPath>(); if (!visited.contains(dstKey)) { visited.add(dstKey); IArgSpec sp = resolve(dstKey); result.add(new PromotionPath()); HashMap<Object, Promotion> proms = getPromotions(dstKey); for (HashMap.Entry<Object, Promotion> kv : proms.entrySet()) { Object subKey = kv.getKey(); Promotion prom = kv.getValue().resolve(this); ArrayList<PromotionPath> paths = listPromotionPathsSub(subKey, visited); for (int i = 0; i < paths.size(); i++) { PromotionPath p = paths.get(i); p.add(prom); result.add(p); } } visited.remove(dstKey); } return result; } public ArrayList<PromotionPath> listPromotionPaths( Object dstKey) { HashSet<Object> visited = new HashSet<Object>(); ArrayList<PromotionPath> p = listPromotionPathsSub(dstKey, visited); IArgSpec sp = resolve(dstKey); for (int i = 0; i < p.size(); i++) { p.get(i).setDst(dstKey, sp); } Collections.sort(p); return p; } public ArrayList<PromotionPath> getPromotionPaths(Object dstKey) { ArgSpecVars v = _registry.get(dstKey); if (v == null) { throw new RuntimeException( "No arg-spec at " + dstKey.toString()); } if (v.promotionPaths == null) { throw new RuntimeException( "No promotion paths have been built for " + dstKey); } return v.promotionPaths; } private void checkForCycles() { ArrayList<Object> vertices = new ArrayList<Object>(); vertices.addAll(_registry.keySet()); INeighborhoodFunction<Object> neigh = new INeighborhoodFunction<Object>() { public List<Object> getNeighbors(Object k) { ArgSpecVars v = _registry.get(k); if (v == null) { throw new RuntimeException( "Missing arg-spec at key " + k.toString()); } ArrayList<Object> dst = new ArrayList<Object>(); Object ind = v.argSpec.getIndirection(); if (ind != null) { dst.add(ind); } dst.addAll(v.extensions); return dst; } }; List<Object> cycles = GraphUtils.findCycles(vertices, neigh); if (!cycles.isEmpty()) { String msg = "The following arg-spec keys are part of cycles:"; for (Object k: cycles) { msg += " " + k.toString(); } throw new RuntimeException(msg); } } private void rebuildArgSpecs() { checkForCycles(); // Clean up all the vars for (HashMap.Entry<Object, ArgSpecVars> kv : _registry.entrySet()) { ArgSpecVars x = kv.getValue(); x.reset(); } // Build indirections for (HashMap.Entry<Object, ArgSpecVars> kv : _registry.entrySet()) { ArgSpecVars v = kv.getValue(); Object indirection = v.argSpec.getIndirection(); ArgSpecVars dst = _registry.get(indirection); if (dst != null) { dst.referents.add(kv.getKey()); } } // Build the arg specs for (HashMap.Entry<Object, ArgSpecVars> kv : _registry.entrySet()) { kv.getValue().build(kv.getKey(), _registry); } } private void rebuildPromotionPaths() { for (HashMap.Entry<Object, ArgSpecVars> kv : _registry.entrySet()) { kv.getValue().promotionPaths = listPromotionPaths(kv.getKey()); } } public void rebuild() { // Set this at the top, so that recursive call will see it as being rebuilt. _rebuiltAt = _mutationCounter; rebuildArgSpecs(); rebuildPromotionPaths(); } public boolean rebuildIfNeeded() { if (_mutationCounter == _rebuiltAt) { return false; } else { rebuild(); return true; } } public int getRebuiltAt() { return _rebuiltAt; } public Set<Object> getArgSpecKeys() { return _registry.keySet(); } public ReadAndUpdateMachine getReadAndUpdateMachine() { return _raum; } }
/** * Interfaces to an external shared library to which we pipe coordinate values * and then read back transformed values. Most useful in combination with * PROJ coordinate transform program for reprojecting coordinates. * * Uses JNI interface to call native methods to define transformation and then * to transform points between coordinate systems. */ package net.sourceforge.mapyrus; import java.util.Enumeration; import java.util.Hashtable; import java.io.*; public class WorldCoordinateTransform { /* * Native methods implementing defintion and transformation * between coordinate systems and retrieving error message when something * goes wrong. */ private static native int define(String description); private static native int transform(int t1, int t2, double []coords, int nCoords); static private Hashtable mDefinedCoordinateSystems; static { System.loadLibrary("mapyrusproj"); mDefinedCoordinateSystems = new Hashtable(); } /** * Define a coordinate system. Synchronized here because external * library may not be thread-safe. */ static private synchronized int defineCoordinateSystem(String description) throws MapyrusException { Integer definition; int newProjection; definition = (Integer)mDefinedCoordinateSystems.get(description); if (definition == null) { newProjection = define(description); if (newProjection < 0) { throw new MapyrusException("Failed to define coordinate system '" + description + "'"); } definition = new Integer(newProjection); mDefinedCoordinateSystems.put(description, definition); } return(definition.intValue()); } /** * Convert X, Y coordinates from one coordinate system to another. * Synchronized here because external library may not be thread-safe. * @param p1 is source coordinate system. * @param p2 is destination coordinate system. * @param coords is array of X, Y coordinates to transform. */ private static synchronized void transform(int p1, int p2, double []coords) throws MapyrusException { int nTransformed = transform(p1, p2, coords, coords.length / 2); if (nTransformed * 2 != coords.length) { Integer id; String sourceName = null, destName = null; /* * Find the names of the two coordinate systems that were used. */ Enumeration e = mDefinedCoordinateSystems.keys(); while (e.hasMoreElements()) { String s = (String)e.nextElement(); id = (Integer)mDefinedCoordinateSystems.get(s); if (id.intValue() == p1) sourceName = s; if (id.intValue() == p2) destName = s; } throw new MapyrusException("Failed to transform coordinates " + coords[nTransformed * 2] + " " + coords[nTransformed * 2 + 1] + " from '" + sourceName + "' to '" + destName + "'"); } } /* * Ids of the two coordinate systems in this transformation. */ private int mSourceSystem; private int mDestinationSystem; /** * Define a transformation between two coordinate systems. */ public WorldCoordinateTransform(String system1, String system2) throws MapyrusException { mSourceSystem = defineCoordinateSystem(system1); mDestinationSystem = defineCoordinateSystem(system2); } /** * Transform coordinates from first coordinate system to the second. * @param coords is array of X, Y coordinate values to be transformed. */ public void forwardTransform(double []coords) throws MapyrusException { if (mSourceSystem != mDestinationSystem) transform(mSourceSystem, mDestinationSystem, coords); } /** * Transform coordinates in reverse, from second coordinate system to the first. * @param coords is array of X, Y coordinate values to be transformed. */ public void backwardTransform(double []coords) throws MapyrusException { if (mSourceSystem != mDestinationSystem) transform(mDestinationSystem, mSourceSystem, coords); } }
package org.myrobotlab.framework; import java.io.Serializable; import java.util.ArrayList; import org.myrobotlab.service.interfaces.Invoker; /** * Simple class representing an operating system process * * @author GroG * */ public class ProcessData implements Serializable { private static final long serialVersionUID = 1L; public String branch; public String name; public String version; public Long startTs = null; public Long stopTs = null; public boolean isRunning = false; public String state = null; // running | stopped | unknown | non responsive public ArrayList<String> cmdLine = null; transient public Process process; transient Monitor monitor; transient public Invoker service; public boolean autoUpdate = false; public static class Monitor extends Thread { ProcessData data; public Monitor(ProcessData data) { this.data = data; } @Override public void run() { try { if (data.process != null) { data.isRunning = true; data.state = "running"; data.process.waitFor(); } } catch (Exception e) { } // FIXME - invoke("terminatedProcess(name)) data.service.invoke("publishTerminated", data.name); data.isRunning = false; data.state = "stopped"; } } public ProcessData(Invoker service, String branch, String version, String name, ArrayList<String> cmdLine, Process process) { this.service = service; this.name = name; this.branch = branch; this.version = version; this.process = process; this.cmdLine = cmdLine; this.startTs = System.currentTimeMillis(); monitor = new Monitor(this); monitor.start(); } }
package org.neo4j.impl.shell.apps; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.impl.shell.NeoApp; import org.neo4j.util.shell.AppCommandParser; import org.neo4j.util.shell.OptionValueType; import org.neo4j.util.shell.Output; import org.neo4j.util.shell.Session; import org.neo4j.util.shell.ShellException; /** * Mimics the POSIX application with the same name, i.e. traverses to a node. */ public class Cd extends NeoApp { /** * The {@link Session} key to use to store the current node and working * directory (i.e. the path which the client got to it). */ public static final String WORKING_DIR_KEY = "WORKING_DIR"; /** * Constructs a new application. */ public Cd() { this.addValueType( "a", new OptionContext( OptionValueType.NONE, "Absolute id, doesn't need to be connected to current node" ) ); } @Override public String getDescription() { return "Changes the current node. Usage: cd <node-id>"; } @Override protected String exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { List<Long> paths = readPaths( session ); Node currentNode = getCurrentNode( session ); Node newNode = null; if ( parser.arguments().isEmpty() ) { newNode = getNeoServer().getNeo().getReferenceNode(); paths.clear(); } else { String arg = parser.arguments().get( 0 ); long newId = currentNode.getId(); if ( arg.equals( ".." ) ) { if ( paths.size() > 0 ) { newId = paths.remove( paths.size() - 1 ); } } else if ( arg.equals( "." ) ) { } else { newId = Long.parseLong( arg ); if ( newId == currentNode.getId() ) { throw new ShellException( "Can't cd to the current node" ); } boolean absolute = parser.options().containsKey( "a" ); if ( !absolute && !this.nodeIsConnected( currentNode, newId ) ) { throw new ShellException( "Node " + newId + " isn't connected to the current node, use -a to " + "force it to go to that node anyway" ); } paths.add( currentNode.getId() ); } newNode = this.getNodeById( newId ); } setCurrentNode( session, newNode ); session.set( WORKING_DIR_KEY, this.makePath( paths ) ); return null; } private boolean nodeIsConnected( Node currentNode, long newId ) { for ( Relationship rel : currentNode.getRelationships() ) { if ( rel.getOtherNode( currentNode ).getId() == newId ) { return true; } } return false; } /** * Reads the session variable specified in {@link #WORKING_DIR_KEY} and * returns it as a list of node ids. * @param session the session to read from. * @return the working directory as a list. * @throws RemoteException if an RMI error occurs. */ public static List<Long> readPaths( Session session ) throws RemoteException { List<Long> list = new ArrayList<Long>(); String path = ( String ) session.get( WORKING_DIR_KEY ); if ( path != null && path.trim().length() > 0 ) { for ( String id : path.split( "," ) ) { list.add( new Long( id ) ); } } return list; } private String makePath( List<Long> paths ) { StringBuffer buffer = new StringBuffer(); for ( Long id : paths ) { if ( buffer.length() > 0 ) { buffer.append( "," ); } buffer.append( id ); } return buffer.length() > 0 ? buffer.toString() : null; } }
package winstone; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionListener; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Models the web.xml file's details ... basically just a bunch of configuration * details, plus the actual instances of mounted servlets. * * @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a> * @version $Id$ */ public class WebAppConfiguration implements ServletContext, Comparator { // private static final String ELEM_DESCRIPTION = "description"; private static final String ELEM_DISPLAY_NAME = "display-name"; private static final String ELEM_SERVLET = "servlet"; private static final String ELEM_SERVLET_MAPPING = "servlet-mapping"; private static final String ELEM_SERVLET_NAME = "servlet-name"; private static final String ELEM_FILTER = "filter"; private static final String ELEM_FILTER_MAPPING = "filter-mapping"; private static final String ELEM_FILTER_NAME = "filter-name"; private static final String ELEM_DISPATCHER = "dispatcher"; private static final String ELEM_URL_PATTERN = "url-pattern"; private static final String ELEM_WELCOME_FILES = "welcome-file-list"; private static final String ELEM_WELCOME_FILE = "welcome-file"; private static final String ELEM_SESSION_CONFIG = "session-config"; private static final String ELEM_SESSION_TIMEOUT = "session-timeout"; private static final String ELEM_MIME_MAPPING = "mime-mapping"; private static final String ELEM_MIME_EXTENSION = "extension"; private static final String ELEM_MIME_TYPE = "mime-type"; private static final String ELEM_CONTEXT_PARAM = "context-param"; private static final String ELEM_PARAM_NAME = "param-name"; private static final String ELEM_PARAM_VALUE = "param-value"; private static final String ELEM_LISTENER = "listener"; private static final String ELEM_LISTENER_CLASS = "listener-class"; private static final String ELEM_DISTRIBUTABLE = "distributable"; private static final String ELEM_ERROR_PAGE = "error-page"; private static final String ELEM_EXCEPTION_TYPE = "exception-type"; private static final String ELEM_ERROR_CODE = "error-code"; private static final String ELEM_ERROR_LOCATION = "location"; private static final String ELEM_SECURITY_CONSTRAINT = "security-constraint"; private static final String ELEM_LOGIN_CONFIG = "login-config"; private static final String ELEM_SECURITY_ROLE = "security-role"; private static final String ELEM_ROLE_NAME = "role-name"; private static final String ELEM_ENV_ENTRY = "env-entry"; private static final String ELEM_LOCALE_ENC_MAP_LIST = "locale-encoding-mapping-list"; private static final String ELEM_LOCALE_ENC_MAPPING = "locale-encoding-mapping"; private static final String ELEM_LOCALE = "locale"; private static final String ELEM_ENCODING = "encoding"; private static final String ELEM_JSP_CONFIG = "jsp-config"; private static final String ELEM_JSP_PROPERTY_GROUP = "jsp-property-group"; private static final String DISPATCHER_REQUEST = "REQUEST"; private static final String DISPATCHER_FORWARD = "FORWARD"; private static final String DISPATCHER_INCLUDE = "INCLUDE"; private static final String DISPATCHER_ERROR = "ERROR"; private static final String JSP_SERVLET_NAME = "JspServlet"; private static final String JSP_SERVLET_MAPPING = "*.jsp"; private static final String JSPX_SERVLET_MAPPING = "*.jspx"; private static final String JSP_SERVLET_LOG_LEVEL = "WARNING"; private static final String INVOKER_SERVLET_NAME = "invoker"; private static final String INVOKER_SERVLET_CLASS = "winstone.invoker.InvokerServlet"; private static final String DEFAULT_INVOKER_PREFIX = "/servlet/"; private static final String DEFAULT_SERVLET_NAME = "default"; private static final String DEFAULT_SERVLET_CLASS = "winstone.StaticResourceServlet"; private static final String DEFAULT_REALM_CLASS = "winstone.realm.ArgumentsRealm"; private static final String DEFAULT_JNDI_MGR_CLASS = "winstone.jndi.WebAppJNDIManager"; private static final String RELOADING_CL_CLASS = "winstone.classLoader.ReloadingClassLoader"; private static final String WEBAPP_CL_CLASS = "winstone.classLoader.WebappClassLoader"; private static final String ERROR_SERVLET_NAME = "winstoneErrorServlet"; private static final String ERROR_SERVLET_CLASS = "winstone.ErrorServlet"; private static final String WEB_INF = "WEB-INF"; private static final String CLASSES = "classes/"; private static final String LIB = "lib"; static final String JSP_SERVLET_CLASS = "org.apache.jasper.servlet.JspServlet"; private HostConfiguration ownerHostConfig; private Cluster cluster; private String webRoot; private String prefix; private String contextName; private ClassLoader loader; private String displayName; private Map attributes; private Map initParameters; private Map sessions; private Map mimeTypes; private Map servletInstances; private Map filterInstances; private ServletContextAttributeListener contextAttributeListeners[]; private ServletContextListener contextListeners[]; private ServletRequestListener requestListeners[]; private ServletRequestAttributeListener requestAttributeListeners[]; private HttpSessionActivationListener sessionActivationListeners[]; private HttpSessionAttributeListener sessionAttributeListeners[]; private HttpSessionListener sessionListeners[]; private Throwable contextStartupError; private Map exactServletMatchMounts; private Mapping patternMatches[]; private Mapping filterPatternsRequest[]; private Mapping filterPatternsForward[]; private Mapping filterPatternsInclude[]; private Mapping filterPatternsError[]; private AuthenticationHandler authenticationHandler; private AuthenticationRealm authenticationRealm; private String welcomeFiles[]; private Integer sessionTimeout; private Class[] errorPagesByExceptionKeysSorted; private Map errorPagesByException; private Map errorPagesByCode; private Map localeEncodingMap; private String defaultServletName; private String errorServletName; private JNDIManager jndiManager; private AccessLogger accessLogger; private Map filterMatchCache; private boolean useSavedSessions; public static boolean booleanArg(Map args, String name, boolean defaultTrue) { String value = (String) args.get(name); if (defaultTrue) return (value == null) || (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); else return (value != null) && (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); } public static String stringArg(Map args, String name, String defaultValue) { return (String) (args.get(name) == null ? defaultValue : args.get(name)); } public static int intArg(Map args, String name, int defaultValue) { return Integer.parseInt(stringArg(args, name, "" + defaultValue)); } public static String getTextFromNode(Node node) { if (node == null) { return null; } Node child = node.getFirstChild(); if (child == null) { return ""; } String textNode = child.getNodeValue(); if (textNode == null) { return ""; } else { return textNode.trim(); } } public static boolean useSavedSessions(Map args) { return booleanArg(args, "useSavedSessions", false); } /** * Constructor. This parses the xml and sets up for basic routing */ public WebAppConfiguration(HostConfiguration ownerHostConfig, Cluster cluster, String webRoot, String prefix, ObjectPool objectPool, Map startupArgs, Node elm, ClassLoader parentClassLoader, File parentClassPaths[], String contextName) { if (!prefix.equals("") && !prefix.startsWith("/")) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.AddingLeadingSlash", prefix); prefix = "/" + prefix; } this.ownerHostConfig = ownerHostConfig; this.webRoot = webRoot; this.prefix = prefix; this.contextName = contextName; List localLoaderClassPathFiles = new ArrayList(); this.loader = buildWebAppClassLoader(startupArgs, parentClassLoader, webRoot, localLoaderClassPathFiles); // Build switch values boolean useJasper = booleanArg(startupArgs, "useJasper", true); boolean useInvoker = booleanArg(startupArgs, "useInvoker", false); boolean useJNDI = booleanArg(startupArgs, "useJNDI", false); this.useSavedSessions = useSavedSessions(startupArgs); // Check jasper is available - simple tests if (useJasper) { try { Class.forName("javax.servlet.jsp.JspFactory", true, parentClassLoader); Class.forName(JSP_SERVLET_CLASS, true, this.loader); } catch (Throwable err) { if (booleanArg(startupArgs, "useJasper", false)) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.JasperNotFound"); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JasperLoadException", err); } useJasper = false; } } if (useInvoker) { try { Class.forName(INVOKER_SERVLET_CLASS, false, this.loader); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvokerNotFound"); useInvoker = false; } } this.attributes = new Hashtable(); this.initParameters = new HashMap(); this.sessions = new Hashtable(); this.servletInstances = new HashMap(); this.filterInstances = new HashMap(); this.filterMatchCache = new HashMap(); List contextAttributeListeners = new ArrayList(); List contextListeners = new ArrayList(); List requestListeners = new ArrayList(); List requestAttributeListeners = new ArrayList(); List sessionActivationListeners = new ArrayList(); List sessionAttributeListeners = new ArrayList(); List sessionListeners = new ArrayList(); this.errorPagesByException = new HashMap(); this.errorPagesByCode = new HashMap(); boolean distributable = false; this.exactServletMatchMounts = new Hashtable(); List localFolderPatterns = new ArrayList(); List localExtensionPatterns = new ArrayList(); List lfpRequest = new ArrayList(); List lfpForward = new ArrayList(); List lfpInclude = new ArrayList(); List lfpError = new ArrayList(); List localWelcomeFiles = new ArrayList(); List startupServlets = new ArrayList(); Set rolesAllowed = new HashSet(); List constraintNodes = new ArrayList(); List envEntryNodes = new ArrayList(); List localErrorPagesByExceptionList = new ArrayList(); Node loginConfigNode = null; // Add the class loader as an implicit context listener if it implements the interface addListenerInstance(this.loader, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); // init mimeTypes set this.mimeTypes = new Hashtable(); String allTypes = Launcher.RESOURCES.getString("WebAppConfig.DefaultMimeTypes"); StringTokenizer mappingST = new StringTokenizer(allTypes, ":", false); for (; mappingST.hasMoreTokens();) { String mapping = mappingST.nextToken(); int delimPos = mapping.indexOf('='); if (delimPos == -1) continue; String extension = mapping.substring(0, delimPos); String mimeType = mapping.substring(delimPos + 1); this.mimeTypes.put(extension.toLowerCase(), mimeType); } this.localeEncodingMap = new HashMap(); String encodingMapSet = Launcher.RESOURCES.getString("WebAppConfig.EncodingMap"); StringTokenizer st = new StringTokenizer(encodingMapSet, ";"); for (; st.hasMoreTokens();) { String token = st.nextToken(); int delimPos = token.indexOf("="); if (delimPos == -1) continue; this.localeEncodingMap.put(token.substring(0, delimPos), token .substring(delimPos + 1)); } // init jsp mappings set List jspMappings = new ArrayList(); jspMappings.add(JSP_SERVLET_MAPPING); jspMappings.add(JSPX_SERVLET_MAPPING); // Add required context atttributes String userName = System.getProperty("user.name", "anyone"); File tmpDir = new File(new File(new File(new File(System.getProperty("java.io.tmpdir"), userName), "winstone.tmp"), ownerHostConfig.getHostname()), contextName); tmpDir.mkdirs(); this.attributes.put("javax.servlet.context.tempdir", tmpDir); // Parse the web.xml file if (elm != null) { NodeList children = elm.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if (child.getNodeType() != Node.ELEMENT_NODE) continue; String nodeName = child.getNodeName(); if (nodeName.equals(ELEM_DISPLAY_NAME)) this.displayName = getTextFromNode(child); else if (nodeName.equals(ELEM_DISTRIBUTABLE)) distributable = true; else if (nodeName.equals(ELEM_SECURITY_CONSTRAINT)) constraintNodes.add(child); else if (nodeName.equals(ELEM_ENV_ENTRY)) envEntryNodes.add(child); else if (nodeName.equals(ELEM_LOGIN_CONFIG)) loginConfigNode = child; // Session config elements else if (nodeName.equals(ELEM_SESSION_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node timeoutElm = child.getChildNodes().item(m); if ((timeoutElm.getNodeType() == Node.ELEMENT_NODE) && (timeoutElm.getNodeName().equals(ELEM_SESSION_TIMEOUT))) { String timeoutStr = getTextFromNode(timeoutElm); if (!timeoutStr.equals("")) { this.sessionTimeout = Integer.valueOf(timeoutStr); } } } } // Construct the security roles else if (child.getNodeName().equals(ELEM_SECURITY_ROLE)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node roleElm = child.getChildNodes().item(m); if ((roleElm.getNodeType() == Node.ELEMENT_NODE) && (roleElm.getNodeName() .equals(ELEM_ROLE_NAME))) rolesAllowed.add(getTextFromNode(roleElm)); } } // Construct the servlet instances else if (nodeName.equals(ELEM_SERVLET)) { ServletConfiguration instance = new ServletConfiguration( this, child); this.servletInstances.put(instance.getServletName(), instance); if (instance.getLoadOnStartup() >= 0) startupServlets.add(instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_FILTER)) { FilterConfiguration instance = new FilterConfiguration( this, this.loader, child); this.filterInstances.put(instance.getFilterName(), instance); } // Construct the servlet instances else if (nodeName.equals(ELEM_LISTENER)) { String listenerClass = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node listenerElm = child.getChildNodes().item(m); if ((listenerElm.getNodeType() == Node.ELEMENT_NODE) && (listenerElm.getNodeName() .equals(ELEM_LISTENER_CLASS))) listenerClass = getTextFromNode(listenerElm); } if (listenerClass != null) try { Class listener = Class.forName(listenerClass, true, this.loader); Object listenerInstance = listener.newInstance(); addListenerInstance(listenerInstance, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners); Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AddListener", listenerClass); } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidListener", listenerClass); } } // Process the servlet mappings else if (nodeName.equals(ELEM_SERVLET_MAPPING)) { String name = null; List mappings = new ArrayList(); // Parse the element and extract NodeList mappingChildren = child.getChildNodes(); for (int k = 0; k < mappingChildren.getLength(); k++) { Node mapChild = mappingChildren.item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_SERVLET_NAME)) { name = getTextFromNode(mapChild); } else if (mapNodeName.equals(ELEM_URL_PATTERN)) { mappings.add(getTextFromNode(mapChild)); } } for (Iterator i = mappings.iterator(); i.hasNext(); ) { processMapping(name, (String) i.next(), this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } } // Process the filter mappings else if (nodeName.equals(ELEM_FILTER_MAPPING)) { String filterName = null; List mappings = new ArrayList(); boolean onRequest = false; boolean onForward = false; boolean onInclude = false; boolean onError = false; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node mapChild = child.getChildNodes().item(k); if (mapChild.getNodeType() != Node.ELEMENT_NODE) continue; String mapNodeName = mapChild.getNodeName(); if (mapNodeName.equals(ELEM_FILTER_NAME)) { filterName = getTextFromNode(mapChild); } else if (mapNodeName.equals(ELEM_SERVLET_NAME)) { mappings.add("srv:" + getTextFromNode(mapChild)); } else if (mapNodeName.equals(ELEM_URL_PATTERN)) { mappings.add("url:" + getTextFromNode(mapChild)); } else if (mapNodeName.equals(ELEM_DISPATCHER)) { String dispatcherValue = getTextFromNode(mapChild); if (dispatcherValue.equals(DISPATCHER_REQUEST)) onRequest = true; else if (dispatcherValue.equals(DISPATCHER_FORWARD)) onForward = true; else if (dispatcherValue.equals(DISPATCHER_INCLUDE)) onInclude = true; else if (dispatcherValue.equals(DISPATCHER_ERROR)) onError = true; } } if (!onRequest && !onInclude && !onForward && !onError) { onRequest = true; } if (mappings.isEmpty()) { throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.BadFilterMapping", filterName)); } for (Iterator i = mappings.iterator(); i.hasNext(); ) { String item = (String) i.next(); Mapping mapping = null; try { if (item.startsWith("srv:")) { mapping = Mapping.createFromLink(filterName, item.substring(4)); } else { mapping = Mapping.createFromURL(filterName, item.substring(4)); } if (onRequest) lfpRequest.add(mapping); if (onForward) lfpForward.add(mapping); if (onInclude) lfpInclude.add(mapping); if (onError) lfpError.add(mapping); } catch (WinstoneException err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.ErrorMapURL", err.getMessage()); } } } // Process the list of welcome files else if (nodeName.equals(ELEM_WELCOME_FILES)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node welcomeFile = child.getChildNodes().item(m); if ((welcomeFile.getNodeType() == Node.ELEMENT_NODE) && welcomeFile.getNodeName().equals(ELEM_WELCOME_FILE)) { String welcomeStr = getTextFromNode(welcomeFile); if (!welcomeStr.equals("")) { localWelcomeFiles.add(welcomeStr); } } } } // Process the error pages else if (nodeName.equals(ELEM_ERROR_PAGE)) { String code = null; String exception = null; String location = null; // Parse the element and extract for (int k = 0; k < child.getChildNodes().getLength(); k++) { Node errorChild = child.getChildNodes().item(k); if (errorChild.getNodeType() != Node.ELEMENT_NODE) continue; String errorChildName = errorChild.getNodeName(); if (errorChildName.equals(ELEM_ERROR_CODE)) code = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_EXCEPTION_TYPE)) exception = getTextFromNode(errorChild); else if (errorChildName.equals(ELEM_ERROR_LOCATION)) location = getTextFromNode(errorChild); } if ((code != null) && (location != null)) this.errorPagesByCode.put(code.trim(), location.trim()); if ((exception != null) && (location != null)) try { Class exceptionClass = Class.forName(exception .trim(), false, this.loader); localErrorPagesByExceptionList.add(exceptionClass); this.errorPagesByException.put(exceptionClass, location.trim()); } catch (ClassNotFoundException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ExceptionNotFound", exception); } } // Process the list of welcome files else if (nodeName.equals(ELEM_MIME_MAPPING)) { String extension = null; String mimeType = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mimeTypeNode = child.getChildNodes().item(m); if (mimeTypeNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_EXTENSION)) extension = getTextFromNode(mimeTypeNode); else if (mimeTypeNode.getNodeName().equals( ELEM_MIME_TYPE)) mimeType = getTextFromNode(mimeTypeNode); } if ((extension != null) && (mimeType != null)) this.mimeTypes.put(extension.toLowerCase(), mimeType); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMimeMapping", new String[] { extension, mimeType }); } // Process the list of welcome files else if (nodeName.equals(ELEM_CONTEXT_PARAM)) { String name = null; String value = null; for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node contextParamNode = child.getChildNodes().item(m); if (contextParamNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (contextParamNode.getNodeName().equals( ELEM_PARAM_NAME)) name = getTextFromNode(contextParamNode); else if (contextParamNode.getNodeName().equals( ELEM_PARAM_VALUE)) value = getTextFromNode(contextParamNode); } if ((name != null) && (value != null)) this.initParameters.put(name, value); else Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidInitParam", new String[] { name, value }); } // Process locale encoding mapping elements else if (nodeName.equals(ELEM_LOCALE_ENC_MAP_LIST)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node mappingNode = child.getChildNodes().item(m); if (mappingNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingNode.getNodeName().equals(ELEM_LOCALE_ENC_MAPPING)) { String localeName = ""; String encoding = ""; for (int l = 0; l < mappingNode.getChildNodes().getLength(); l++) { Node mappingChildNode = mappingNode.getChildNodes().item(l); if (mappingChildNode.getNodeType() != Node.ELEMENT_NODE) continue; else if (mappingChildNode.getNodeName().equals(ELEM_LOCALE)) localeName = getTextFromNode(mappingChildNode); else if (mappingChildNode.getNodeName().equals(ELEM_ENCODING)) encoding = getTextFromNode(mappingChildNode); } if (!encoding.equals("") && !localeName.equals("")) this.localeEncodingMap.put(localeName, encoding); } } } // Record the url mappings for jsp files if set else if (nodeName.equals(ELEM_JSP_CONFIG)) { for (int m = 0; m < child.getChildNodes().getLength(); m++) { Node propertyGroupNode = child.getChildNodes().item(m); if ((propertyGroupNode.getNodeType() == Node.ELEMENT_NODE) && propertyGroupNode.getNodeName().equals(ELEM_JSP_PROPERTY_GROUP)) { for (int l = 0; l < propertyGroupNode.getChildNodes().getLength(); l++) { Node urlPatternNode = propertyGroupNode.getChildNodes().item(l); if ((urlPatternNode.getNodeType() == Node.ELEMENT_NODE) && urlPatternNode.getNodeName().equals(ELEM_URL_PATTERN)) { String jm = getTextFromNode(urlPatternNode); if (!jm.equals("")) { jspMappings.add(jm); } } } } } } } } // If not distributable, remove the cluster reference if (!distributable && (cluster != null)) { Logger.log(Logger.INFO, Launcher.RESOURCES, "WebAppConfig.ClusterOffNotDistributable", this.contextName); } else { this.cluster = cluster; } // Build the login/security role instance if (!constraintNodes.isEmpty() && (loginConfigNode != null)) { String authMethod = null; for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) { if (loginConfigNode.getChildNodes().item(n).getNodeName().equals("auth-method")) { authMethod = getTextFromNode(loginConfigNode.getChildNodes().item(n)); } } // Load the appropriate auth class if (authMethod == null) { authMethod = "BASIC"; } else { authMethod = WinstoneResourceBundle.globalReplace(authMethod, "-", ""); } String realmClassName = stringArg(startupArgs, "realmClassName", DEFAULT_REALM_CLASS).trim(); String authClassName = "winstone.auth." + authMethod.substring(0, 1).toUpperCase() + authMethod.substring(1).toLowerCase() + "AuthenticationHandler"; try { // Build the realm Class realmClass = Class.forName(realmClassName, true, parentClassLoader); Constructor realmConstr = realmClass.getConstructor( new Class[] {Set.class, Map.class }); this.authenticationRealm = (AuthenticationRealm) realmConstr.newInstance( new Object[] { rolesAllowed, startupArgs }); // Build the authentication handler Class authClass = Class.forName(authClassName); Constructor authConstr = authClass .getConstructor(new Class[] { Node.class, List.class, Set.class, AuthenticationRealm.class }); this.authenticationHandler = (AuthenticationHandler) authConstr .newInstance(new Object[] { loginConfigNode, constraintNodes, rolesAllowed, authenticationRealm }); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.AuthDisabled", authMethod); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.AuthError", new String[] { authClassName, realmClassName }, err); } } else if (!stringArg(startupArgs, "realmClassName", "").trim().equals("")) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.NoWebXMLSecurityDefs"); } // Instantiate the JNDI manager String jndiMgrClassName = stringArg(startupArgs, "webappJndiClassName", DEFAULT_JNDI_MGR_CLASS).trim(); if (useJNDI) { try { // Build the realm Class jndiMgrClass = Class.forName(jndiMgrClassName, true, parentClassLoader); Constructor jndiMgrConstr = jndiMgrClass.getConstructor(new Class[] { Map.class, List.class, ClassLoader.class }); this.jndiManager = (JNDIManager) jndiMgrConstr.newInstance(new Object[] { null, envEntryNodes, this.loader }); if (this.jndiManager != null) this.jndiManager.setup(); } catch (ClassNotFoundException err) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.JNDIDisabled"); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.JNDIError", jndiMgrClassName, err); } } String loggerClassName = stringArg(startupArgs, "accessLoggerClassName", "").trim(); if (!loggerClassName.equals("")) { try { // Build the realm Class loggerClass = Class.forName(loggerClassName, true, parentClassLoader); Constructor loggerConstr = loggerClass.getConstructor(new Class[] { WebAppConfiguration.class, Map.class }); this.accessLogger = (AccessLogger) loggerConstr.newInstance(new Object[] { this, startupArgs}); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.LoggerError", loggerClassName, err); } } else { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.LoggerDisabled"); } // Add the default index.html welcomeFile if none are supplied if (localWelcomeFiles.isEmpty()) { if (useJasper) { localWelcomeFiles.add("index.jsp"); } localWelcomeFiles.add("index.html"); } // Put the name filters after the url filters, then convert to string arrays this.filterPatternsRequest = (Mapping[]) lfpRequest.toArray(new Mapping[0]); this.filterPatternsForward = (Mapping[]) lfpForward.toArray(new Mapping[0]); this.filterPatternsInclude = (Mapping[]) lfpInclude.toArray(new Mapping[0]); this.filterPatternsError = (Mapping[]) lfpError.toArray(new Mapping[0]); if (this.filterPatternsRequest.length > 0) Arrays.sort(this.filterPatternsRequest, this.filterPatternsRequest[0]); if (this.filterPatternsForward.length > 0) Arrays.sort(this.filterPatternsForward, this.filterPatternsForward[0]); if (this.filterPatternsInclude.length > 0) Arrays.sort(this.filterPatternsInclude, this.filterPatternsInclude[0]); if (this.filterPatternsError.length > 0) Arrays.sort(this.filterPatternsError, this.filterPatternsError[0]); this.welcomeFiles = (String[]) localWelcomeFiles.toArray(new String[0]); this.errorPagesByExceptionKeysSorted = (Class[]) localErrorPagesByExceptionList .toArray(new Class[0]); Arrays.sort(this.errorPagesByExceptionKeysSorted, this); // Put the listeners into their arrays this.contextAttributeListeners = (ServletContextAttributeListener[]) contextAttributeListeners .toArray(new ServletContextAttributeListener[0]); this.contextListeners = (ServletContextListener[]) contextListeners .toArray(new ServletContextListener[0]); this.requestListeners = (ServletRequestListener[]) requestListeners .toArray(new ServletRequestListener[0]); this.requestAttributeListeners = (ServletRequestAttributeListener[]) requestAttributeListeners .toArray(new ServletRequestAttributeListener[0]); this.sessionActivationListeners = (HttpSessionActivationListener[]) sessionActivationListeners .toArray(new HttpSessionActivationListener[0]); this.sessionAttributeListeners = (HttpSessionAttributeListener[]) sessionAttributeListeners .toArray(new HttpSessionAttributeListener[0]); this.sessionListeners = (HttpSessionListener[]) sessionListeners .toArray(new HttpSessionListener[0]); // If we haven't explicitly mapped the default servlet, map it here if (this.defaultServletName == null) this.defaultServletName = DEFAULT_SERVLET_NAME; if (this.errorServletName == null) this.errorServletName = ERROR_SERVLET_NAME; // If we don't have an instance of the default servlet, mount the inbuilt one boolean useDirLists = booleanArg(startupArgs, "directoryListings", true); Map staticParams = new Hashtable(); staticParams.put("webRoot", webRoot); staticParams.put("prefix", this.prefix); staticParams.put("directoryList", "" + useDirLists); if (this.servletInstances.get(this.defaultServletName) == null) { ServletConfiguration defaultServlet = new ServletConfiguration( this, this.defaultServletName, DEFAULT_SERVLET_CLASS, staticParams, 0); this.servletInstances.put(this.defaultServletName, defaultServlet); startupServlets.add(defaultServlet); } if (booleanArg(startupArgs, "alwaysMountDefaultServlet", true) && this.servletInstances.get(DEFAULT_SERVLET_NAME) == null) { ServletConfiguration defaultServlet = new ServletConfiguration( this, DEFAULT_SERVLET_NAME, DEFAULT_SERVLET_CLASS, staticParams, 0); this.servletInstances.put(DEFAULT_SERVLET_NAME, defaultServlet); startupServlets.add(defaultServlet); } // If we don't have an instance of the default servlet, mount the inbuilt one if (this.servletInstances.get(this.errorServletName) == null) { ServletConfiguration errorServlet = new ServletConfiguration( this, this.errorServletName, ERROR_SERVLET_CLASS, new HashMap(), 0); this.servletInstances.put(this.errorServletName, errorServlet); startupServlets.add(errorServlet); } // Initialise jasper servlet if requested if (useJasper) { setAttribute("org.apache.catalina.classloader", this.loader); try { StringBuffer cp = new StringBuffer(); for (Iterator i = localLoaderClassPathFiles.iterator(); i.hasNext(); ) { cp.append(((File) i.next()).getCanonicalPath()).append( File.pathSeparatorChar); } for (int n = 0; n < parentClassPaths.length; n++) { cp.append(parentClassPaths[n].getCanonicalPath()).append( File.pathSeparatorChar); } setAttribute("org.apache.catalina.jsp_classpath", (cp.length() > 0 ? cp.substring(0, cp.length() - 1) : "")); } catch (IOException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ErrorSettingJSPPaths", err); } Map jspParams = new HashMap(); addJspServletParams(jspParams); ServletConfiguration sc = new ServletConfiguration(this, JSP_SERVLET_NAME, JSP_SERVLET_CLASS, jspParams, 3); this.servletInstances.put(JSP_SERVLET_NAME, sc); startupServlets.add(sc); for (Iterator mapIt = jspMappings.iterator(); mapIt.hasNext(); ) { processMapping(JSP_SERVLET_NAME, (String) mapIt.next(), this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } } // Initialise invoker servlet if requested if (useInvoker) { // Get generic options String invokerPrefix = stringArg(startupArgs, "invokerPrefix", DEFAULT_INVOKER_PREFIX); Map invokerParams = new HashMap(); invokerParams.put("prefix", this.prefix); invokerParams.put("invokerPrefix", invokerPrefix); ServletConfiguration sc = new ServletConfiguration(this, INVOKER_SERVLET_NAME, INVOKER_SERVLET_CLASS, invokerParams, 3); this.servletInstances.put(INVOKER_SERVLET_NAME, sc); processMapping(INVOKER_SERVLET_NAME, invokerPrefix + Mapping.STAR, this.exactServletMatchMounts, localFolderPatterns, localExtensionPatterns); } // Sort the folder patterns so the longest paths are first localFolderPatterns.addAll(localExtensionPatterns); this.patternMatches = (Mapping[]) localFolderPatterns.toArray(new Mapping[0]); if (this.patternMatches.length > 0) Arrays.sort(this.patternMatches, this.patternMatches[0]); // Send init notifies try { for (int n = 0; n < this.contextListeners.length; n++) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.loader); this.contextListeners[n].contextInitialized(new ServletContextEvent(this)); Thread.currentThread().setContextClassLoader(cl); } } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ContextStartupError", this.contextName, err); this.contextStartupError = err; } if (this.contextStartupError == null) { // Load sessions if enabled if (this.useSavedSessions) { WinstoneSession.loadSessions(this); } // Initialise all the filters for (Iterator i = this.filterInstances.values().iterator(); i.hasNext();) { FilterConfiguration config = (FilterConfiguration) i.next(); try { config.getFilter(); } catch (ServletException err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.FilterStartupError", config.getFilterName(), err); } } // Initialise load on startup servlets Object autoStarters[] = startupServlets.toArray(); Arrays.sort(autoStarters); for (int n = 0; n < autoStarters.length; n++) { ((ServletConfiguration) autoStarters[n]).ensureInitialization(); } } } /** * Build the web-app classloader. This tries to load the preferred classloader first, * but if it fails, falls back to a simple URLClassLoader. */ private ClassLoader buildWebAppClassLoader(Map startupArgs, ClassLoader parentClassLoader, String webRoot, List classPathFileList) { List urlList = new ArrayList(); try { // Web-inf folder File webInfFolder = new File(webRoot, WEB_INF); // Classes folder File classesFolder = new File(webInfFolder, CLASSES); if (classesFolder.exists()) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.WebAppClasses"); String classesFolderURL = classesFolder.getCanonicalFile().toURL().toString(); urlList.add(new URL(classesFolderURL.endsWith("/") ? classesFolderURL : classesFolderURL + "/")); classPathFileList.add(classesFolder); } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.NoWebAppClasses", classesFolder.toString()); } // Lib folder's jar files File libFolder = new File(webInfFolder, LIB); if (libFolder.exists()) { File jars[] = libFolder.listFiles(); for (int n = 0; n < jars.length; n++) { String jarName = jars[n].getName().toLowerCase(); if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.WebAppLib", jars[n].getName()); urlList.add(jars[n].toURL()); classPathFileList.add(jars[n]); } } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.NoWebAppLib", libFolder .toString()); } } catch (MalformedURLException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WebAppConfig.BadURL"), err); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WebAppConfig.IOException"), err); } URL jarURLs[] = (URL []) urlList.toArray(new URL[urlList.size()]); String preferredClassLoader = stringArg(startupArgs, "preferredClassLoader", WEBAPP_CL_CLASS); if (booleanArg(startupArgs, "useServletReloading", false) && stringArg(startupArgs, "preferredClassLoader", "").equals("")) { preferredClassLoader = RELOADING_CL_CLASS; } // Try to set up the preferred class loader, and if we fail, use the normal one ClassLoader outputCL = null; if (!preferredClassLoader.equals("")) { try { Class preferredCL = Class.forName(preferredClassLoader, true, parentClassLoader); Constructor reloadConstr = preferredCL.getConstructor(new Class[] { URL[].class, ClassLoader.class}); outputCL = (ClassLoader) reloadConstr.newInstance(new Object[] { jarURLs, parentClassLoader}); } catch (Throwable err) { if (!stringArg(startupArgs, "preferredClassLoader", "").equals("") || !preferredClassLoader.equals(WEBAPP_CL_CLASS)) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.CLError", err); } } } if (outputCL == null) { outputCL = new URLClassLoader(jarURLs, parentClassLoader); } Logger.log(Logger.MAX, Launcher.RESOURCES, "WebAppConfig.WebInfClassLoader", outputCL.toString()); return outputCL; } private void addListenerInstance(Object listenerInstance, List contextAttributeListeners, List contextListeners, List requestAttributeListeners, List requestListeners, List sessionActivationListeners, List sessionAttributeListeners, List sessionListeners) { if (listenerInstance instanceof ServletContextAttributeListener) contextAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletContextListener) contextListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestAttributeListener) requestAttributeListeners.add(listenerInstance); if (listenerInstance instanceof ServletRequestListener) requestListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionActivationListener) sessionActivationListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionAttributeListener) sessionAttributeListeners.add(listenerInstance); if (listenerInstance instanceof HttpSessionListener) sessionListeners.add(listenerInstance); } public String getContextPath() { return this.prefix; } public String getWebroot() { return this.webRoot; } public ClassLoader getLoader() { return this.loader; } public AccessLogger getAccessLogger() { return this.accessLogger; } public Map getFilters() { return this.filterInstances; } public String getContextName() { return this.contextName; } public Class[] getErrorPageExceptions() { return this.errorPagesByExceptionKeysSorted; } public Map getErrorPagesByException() { return this.errorPagesByException; } public Map getErrorPagesByCode() { return this.errorPagesByCode; } public Map getLocaleEncodingMap() { return this.localeEncodingMap; } public String[] getWelcomeFiles() { return this.welcomeFiles; } public boolean isDistributable() { return (this.cluster != null); } public Map getFilterMatchCache() { return this.filterMatchCache; } public String getOwnerHostname() { return this.ownerHostConfig.getHostname(); } public ServletRequestListener[] getRequestListeners() { return this.requestListeners; } public ServletRequestAttributeListener[] getRequestAttributeListeners() { return this.requestAttributeListeners; } public static void addJspServletParams(Map jspParams) { jspParams.put("logVerbosityLevel", JSP_SERVLET_LOG_LEVEL); jspParams.put("fork", "false"); } public int compare(Object one, Object two) { if (!(one instanceof Class) || !(two instanceof Class)) throw new IllegalArgumentException( "This comparator is only for sorting classes"); Class classOne = (Class) one; Class classTwo = (Class) two; if (classOne.isAssignableFrom(classTwo)) return 1; else if (classTwo.isAssignableFrom(classOne)) return -1; else return 0; } public String getServletURIFromRequestURI(String requestURI) { if (prefix.equals("")) { return requestURI; } else if (requestURI.startsWith(prefix)) { return requestURI.substring(prefix.length()); } else { throw new WinstoneException("This shouldn't happen, " + "since we aborted earlier if we didn't match"); } } /** * Iterates through each of the servlets/filters and calls destroy on them */ public void destroy() { synchronized (this.filterMatchCache) { this.filterMatchCache.clear(); } Collection filterInstances = new ArrayList(this.filterInstances.values()); for (Iterator i = filterInstances.iterator(); i.hasNext();) { try { ((FilterConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.filterInstances.clear(); Collection servletInstances = new ArrayList(this.servletInstances.values()); for (Iterator i = servletInstances.iterator(); i.hasNext();) { try { ((ServletConfiguration) i.next()).destroy(); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.servletInstances.clear(); // Drop all sessions Collection sessions = new ArrayList(this.sessions.values()); for (Iterator i = sessions.iterator(); i.hasNext();) { WinstoneSession session = (WinstoneSession) i.next(); try { if (this.useSavedSessions) { session.saveToTemp(); } else { session.invalidate(); } } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.sessions.clear(); // Send destroy notifies - backwards for (int n = this.contextListeners.length - 1; n >= 0; n try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.loader); this.contextListeners[n].contextDestroyed(new ServletContextEvent(this)); this.contextListeners[n] = null; Thread.currentThread().setContextClassLoader(cl); } catch (Throwable err) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); } } this.contextListeners = null; // Terminate class loader reloading thread if running if (this.loader != null) { // already shutdown/handled by the servlet context listeners // try { // Method methDestroy = this.loader.getClass().getMethod("destroy", new Class[0]); // methDestroy.invoke(this.loader, new Object[0]); // } catch (Throwable err) { // Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.ShutdownError", err); this.loader = null; } // Kill JNDI manager if we have one if (this.jndiManager != null) { this.jndiManager.tearDown(); this.jndiManager = null; } // Kill JNDI manager if we have one if (this.accessLogger != null) { this.accessLogger.destroy(); this.accessLogger = null; } } /** * Triggered by the admin thread on the reloading class loader. This will * cause a full shutdown and reinstantiation of the web app - not real * graceful, but you shouldn't have reloading turned on in high load * environments. */ public void resetClassLoader() throws IOException { this.ownerHostConfig.reloadWebApp(getContextPath()); } /** * Here we process url patterns into the exactMatch and patternMatch lists */ private void processMapping(String name, String pattern, Map exactPatterns, List folderPatterns, List extensionPatterns) { Mapping urlPattern = null; try { urlPattern = Mapping.createFromURL(name, pattern); } catch (WinstoneException err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.ErrorMapURL", err.getMessage()); return; } // put the pattern in the correct list if (urlPattern.getPatternType() == Mapping.EXACT_PATTERN) { exactPatterns.put(urlPattern.getUrlPattern(), name); } else if (urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) { folderPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.EXTENSION_PATTERN) { extensionPatterns.add(urlPattern); } else if (urlPattern.getPatternType() == Mapping.DEFAULT_SERVLET) { this.defaultServletName = name; } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WebAppConfig.InvalidMount", new String[] { name, pattern }); } } /** * Execute the pattern match, and try to return a servlet that matches this * URL */ private ServletConfiguration urlMatch(String path, StringBuffer servletPath, StringBuffer pathInfo) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.URLMatch", path); // Check exact matches first String exact = (String) this.exactServletMatchMounts.get(path); if (exact != null) { if (this.servletInstances.get(exact) != null) { servletPath.append(WinstoneRequest.decodeURLToken(path)); // pathInfo.append(""); // a hack - empty becomes null later return (ServletConfiguration) this.servletInstances.get(exact); } } // Inexact mount check for (int n = 0; n < this.patternMatches.length; n++) { Mapping urlPattern = this.patternMatches[n]; if (urlPattern.match(path, servletPath, pathInfo) && (this.servletInstances.get(urlPattern.getMappedTo()) != null)) { return (ServletConfiguration) this.servletInstances .get(urlPattern.getMappedTo()); } } // return default servlet // servletPath.append(""); // unneeded if (this.servletInstances.get(this.defaultServletName) == null) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.MatchedNonExistServlet", this.defaultServletName)); // pathInfo.append(path); servletPath.append(WinstoneRequest.decodeURLToken(path)); return (ServletConfiguration) this.servletInstances.get(this.defaultServletName); } /** * Constructs a session instance with the given sessionId * * @param sessionId The sessionID for the new session * @return A valid session object */ public WinstoneSession makeNewSession(String sessionId) { WinstoneSession ws = new WinstoneSession(sessionId); ws.setWebAppConfiguration(this); setSessionListeners(ws); if ((this.sessionTimeout != null) && (this.sessionTimeout.intValue() > 0)) { ws.setMaxInactiveInterval(this.sessionTimeout.intValue() * 60); } else { ws.setMaxInactiveInterval(-1); } ws.setLastAccessedDate(System.currentTimeMillis()); ws.sendCreatedNotifies(); this.sessions.put(sessionId, ws); return ws; } /** * Retrieves the session by id. If the web app is distributable, it asks the * other members of the cluster if it doesn't have it itself. * * @param sessionId The id of the session we want * @return A valid session instance */ public WinstoneSession getSessionById(String sessionId, boolean localOnly) { if (sessionId == null) { return null; } WinstoneSession session = (WinstoneSession) this.sessions.get(sessionId); if (session != null) { return session; } // If I'm distributable ... check remotely if ((this.cluster != null) && !localOnly) { session = this.cluster.askClusterForSession(sessionId, this); if (session != null) { this.sessions.put(sessionId, session); } return session; } else { return null; } } /** * Add/Remove the session from the collection */ void removeSessionById(String sessionId) { this.sessions.remove(sessionId); } void addSession(String sessionId, WinstoneSession session) { this.sessions.put(sessionId, session); } public void invalidateExpiredSessions() { Object allSessions[] = this.sessions.values().toArray(); int expiredCount = 0; for (int n = 0; n < allSessions.length; n++) { WinstoneSession session = (WinstoneSession) allSessions[n]; if (!session.isNew() && session.isUnusedByRequests() && session.isExpired()) { session.invalidate(); expiredCount++; } } if (expiredCount > 0) { Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WebAppConfig.InvalidatedSessions", expiredCount + ""); } } public void setSessionListeners(WinstoneSession session) { session.setSessionActivationListeners(this.sessionActivationListeners); session.setSessionAttributeListeners(this.sessionAttributeListeners); session.setSessionListeners(this.sessionListeners); } public void removeServletConfigurationAndMappings(ServletConfiguration config) { this.servletInstances.remove(config.getServletName()); // The urlMatch method will only match to non-null mappings, so we don't need // to remove anything here } // Application level attributes public Object getAttribute(String name) { return this.attributes.get(name); } public Enumeration getAttributeNames() { return Collections.enumeration(this.attributes.keySet()); } public void removeAttribute(String name) { Object me = this.attributes.get(name); this.attributes.remove(name); if (me != null) for (int n = 0; n < this.contextAttributeListeners.length; n++) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getLoader()); this.contextAttributeListeners[n].attributeRemoved( new ServletContextAttributeEvent(this, name, me)); Thread.currentThread().setContextClassLoader(cl); } } public void setAttribute(String name, Object object) { if (object == null) { removeAttribute(name); } else { Object me = this.attributes.get(name); this.attributes.put(name, object); if (me != null) { for (int n = 0; n < this.contextAttributeListeners.length; n++) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getLoader()); this.contextAttributeListeners[n].attributeReplaced( new ServletContextAttributeEvent(this, name, me)); Thread.currentThread().setContextClassLoader(cl); } } else { for (int n = 0; n < this.contextAttributeListeners.length; n++) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getLoader()); this.contextAttributeListeners[n].attributeAdded( new ServletContextAttributeEvent(this, name, object)); Thread.currentThread().setContextClassLoader(cl); } } } } // Application level init parameters public String getInitParameter(String name) { return (String) this.initParameters.get(name); } public Enumeration getInitParameterNames() { return Collections.enumeration(this.initParameters.keySet()); } // Server info public String getServerInfo() { return Launcher.RESOURCES.getString("ServerVersion"); } public int getMajorVersion() { return 2; } public int getMinorVersion() { return 5; } // Weird mostly deprecated crap to do with getting servlet instances public javax.servlet.ServletContext getContext(String uri) { return this.ownerHostConfig.getWebAppByURI(uri); } public String getServletContextName() { return this.displayName; } /** * Look up the map of mimeType extensions, and return the type that matches */ public String getMimeType(String fileName) { int dotPos = fileName.lastIndexOf('.'); if ((dotPos != -1) && (dotPos != fileName.length() - 1)) { String extension = fileName.substring(dotPos + 1).toLowerCase(); String mimeType = (String) this.mimeTypes.get(extension); return mimeType; } else return null; } // Context level log statements public void log(String message) { Logger.logDirectMessage(Logger.INFO, this.contextName, message, null); } public void log(String message, Throwable throwable) { Logger.logDirectMessage(Logger.ERROR, this.contextName, message, throwable); } /** * Named dispatcher - this basically gets us a simple exact dispatcher (no * url matching, no request attributes and no security) */ public javax.servlet.RequestDispatcher getNamedDispatcher(String name) { ServletConfiguration servlet = (ServletConfiguration) this.servletInstances.get(name); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForNamedDispatcher(this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Gets a dispatcher, which sets the request attributes, etc on a * forward/include. Doesn't execute security though. */ public javax.servlet.RequestDispatcher getRequestDispatcher( String uriInsideWebapp) { if (uriInsideWebapp == null) { return null; } else if (!uriInsideWebapp.startsWith("/")) { return null; } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) { queryString = uriInsideWebapp.substring(questionPos + 1); } uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForURLDispatcher(servletPath.toString(), pathInfo.toString() .equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsForward, this.filterPatternsInclude); return rd; } } return null; } /** * Creates the dispatcher that corresponds to a request level dispatch (ie * the initial entry point). The difference here is that we need to set up * the dispatcher so that on a forward, it executes the security checks and * the request filters, while not setting any of the request attributes for * a forward. Also, we can't return a null dispatcher in error case - instead * we have to return a dispatcher pre-init'd for showing an error page (eg 404). * A null dispatcher is interpreted to mean a successful 302 has occurred. */ public RequestDispatcher getInitialDispatcher(String uriInsideWebapp, WinstoneRequest request, WinstoneResponse response) throws IOException { if (!uriInsideWebapp.equals("") && !uriInsideWebapp.startsWith("/")) { return this.getErrorDispatcherByCode( HttpServletResponse.SC_BAD_REQUEST, Launcher.RESOURCES.getString("WebAppConfig.InvalidURI", uriInsideWebapp), null); } else if (this.contextStartupError != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); this.contextStartupError.printStackTrace(pw); return this.getErrorDispatcherByCode( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Launcher.RESOURCES.getString("WebAppConfig.ErrorDuringStartup", sw.toString()), this.contextStartupError); } // Parse the url for query string, etc String queryString = ""; int questionPos = uriInsideWebapp.indexOf('?'); if (questionPos != -1) { if (questionPos != uriInsideWebapp.length() - 1) queryString = uriInsideWebapp.substring(questionPos + 1); uriInsideWebapp = uriInsideWebapp.substring(0, questionPos); } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo); if (servlet != null) { // If the default servlet was returned, we should check for welcome files if (servlet.getServletName().equals(this.defaultServletName)) { // Is path a directory ? String directoryPath = servletPath.toString(); if (directoryPath.endsWith("/")) { directoryPath = directoryPath.substring(0, directoryPath.length() - 1); } if (directoryPath.startsWith("/")) { directoryPath = directoryPath.substring(1); } File res = new File(webRoot, directoryPath); if (res.exists() && res.isDirectory() && (request.getMethod().equals("GET") || request.getMethod().equals("HEAD"))) { // Check for the send back with slash case if (!servletPath.toString().endsWith("/")) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.FoundNonSlashDirectory", servletPath.toString()); response.sendRedirect(this.prefix + servletPath.toString() + pathInfo.toString() + "/" + (queryString.equals("") ? "" : "?" + queryString)); return null; } // Check for welcome files Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WebAppConfig.CheckWelcomeFile", servletPath.toString() + pathInfo.toString()); String welcomeFile = matchWelcomeFiles(servletPath.toString() + pathInfo.toString(), request, queryString); if (welcomeFile != null) { response.sendRedirect(this.prefix + welcomeFile); // + servletPath.toString() // + pathInfo.toString() // + welcomeFile // + (queryString.equals("") ? "" : "?" + queryString)); return null; } } } RequestDispatcher rd = new RequestDispatcher(this, servlet); rd.setForInitialDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, this.filterPatternsRequest, this.authenticationHandler); return rd; } // If we are here, return a 404 return this.getErrorDispatcherByCode(HttpServletResponse.SC_NOT_FOUND, Launcher.RESOURCES.getString("StaticResourceServlet.PathNotFound", uriInsideWebapp), null); } /** * Gets a dispatcher, set up for error dispatch. */ public RequestDispatcher getErrorDispatcherByClass( Throwable exception) { // Check for exception class match Class exceptionClasses[] = this.errorPagesByExceptionKeysSorted; Throwable errWrapper = new ServletException(exception); while (errWrapper instanceof ServletException) { errWrapper = ((ServletException) errWrapper).getRootCause(); if (errWrapper == null) { break; } for (int n = 0; n < exceptionClasses.length; n++) { Logger.log(Logger.FULL_DEBUG, Launcher.RESOURCES, "WinstoneResponse.TestingException", new String[] {this.errorPagesByExceptionKeysSorted[n].getName(), errWrapper.getClass().getName()}); if (exceptionClasses[n].isInstance(errWrapper)) { String errorURI = (String) this.errorPagesByException.get(exceptionClasses[n]); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, errWrapper); if (rd != null) { return rd; } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.SkippingException", new String[] {exceptionClasses[n].getName(), (String) this.errorPagesByException.get(exceptionClasses[n]) }); } } else { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.ExceptionNotMatched", exceptionClasses[n].getName()); } } } // Otherwise throw a code error Throwable errPassDown = exception; while ((errPassDown instanceof ServletException) && (((ServletException) errPassDown).getRootCause() != null)) { errPassDown = ((ServletException) errPassDown).getRootCause(); } return getErrorDispatcherByCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, errPassDown); } public RequestDispatcher getErrorDispatcherByCode( int statusCode, String summaryMessage, Throwable exception) { // Check for status code match String errorURI = (String) getErrorPagesByCode().get("" + statusCode); if (errorURI != null) { RequestDispatcher rd = buildErrorDispatcher(errorURI, statusCode, summaryMessage, exception); if (rd != null) { return rd; } } // If no dispatcher available, return a dispatcher to the default error formatter ServletConfiguration errorServlet = (ServletConfiguration) this.servletInstances.get(this.errorServletName); if (errorServlet != null) { RequestDispatcher rd = new RequestDispatcher(this, errorServlet); if (rd != null) { rd.setForErrorDispatcher(null, null, null, statusCode, summaryMessage, exception, null, this.filterPatternsError); return rd; } } // Otherwise log and return null Logger.log(Logger.ERROR, Launcher.RESOURCES, "WebAppConfig.NoErrorServlet", "" + statusCode, exception); return null; } /** * Build a dispatcher to the error handler if it's available. If it fails, return null. */ private RequestDispatcher buildErrorDispatcher(String errorURI, int statusCode, String summaryMessage, Throwable exception) { // Parse the url for query string, etc String queryString = ""; int questionPos = errorURI.indexOf('?'); if (questionPos != -1) { if (questionPos != errorURI.length() - 1) { queryString = errorURI.substring(questionPos + 1); } errorURI = errorURI.substring(0, questionPos); } // Get the message by recursing if none supplied ServletException errIterator = new ServletException(exception); while ((summaryMessage == null) && (errIterator != null)) { summaryMessage = errIterator.getMessage(); if (errIterator.getRootCause() instanceof ServletException) { errIterator = (ServletException) errIterator.getRootCause(); } else { if ((summaryMessage == null) && (errIterator.getCause() != null)) { summaryMessage = errIterator.getRootCause().getMessage(); } errIterator = null; } } // Return the dispatcher StringBuffer servletPath = new StringBuffer(); StringBuffer pathInfo = new StringBuffer(); ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo); if (servlet != null) { RequestDispatcher rd = new RequestDispatcher(this, servlet); if (rd != null) { rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, statusCode, summaryMessage, exception, errorURI, this.filterPatternsError); return rd; } } return null; } /** * Check if any of the welcome files under this path are available. Returns the * name of the file if found, null otherwise. Returns the full internal webapp uri */ private String matchWelcomeFiles(String path, WinstoneRequest request, String queryString) { if (!path.endsWith("/")) { path = path + "/"; } String qs = (queryString.equals("") ? "" : "?" + queryString); for (int n = 0; n < this.welcomeFiles.length; n++) { String welcomeFile = this.welcomeFiles[n]; while (welcomeFile.startsWith("/")) { welcomeFile = welcomeFile.substring(1); } welcomeFile = path + welcomeFile; String exact = (String) this.exactServletMatchMounts.get(welcomeFile); if (exact != null) { return welcomeFile + qs; } // Inexact folder mount check - note folder mounts only for (int j = 0; j < this.patternMatches.length; j++) { Mapping urlPattern = this.patternMatches[j]; if ((urlPattern.getPatternType() == Mapping.FOLDER_PATTERN) && urlPattern.match(welcomeFile, null, null)) { return welcomeFile + qs; } } try { if (getResource(welcomeFile) != null) { return welcomeFile + qs; } } catch (MalformedURLException err) {} } return null; } // Getting resources via the classloader public URL getResource(String path) throws MalformedURLException { if (path == null) { return null; } else if (!path.startsWith("/")) { throw new MalformedURLException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); } else if (!path.equals("/") && path.endsWith("/")) { path = path.substring(0, path.length() - 1); } File res = new File(webRoot, path.substring(1)); return (res != null) && res.exists() ? res.toURL() : null; } public InputStream getResourceAsStream(String path) { try { URL res = getResource(path); return res == null ? null : res.openStream(); } catch (IOException err) { throw new WinstoneException(Launcher.RESOURCES .getString("WebAppConfig.ErrorOpeningStream"), err); } } public String getRealPath(String path) { // Trim the prefix if (path == null) return null; else { try { File res = new File(this.webRoot, path); if (res.isDirectory()) return res.getCanonicalPath() + "/"; else return res.getCanonicalPath(); } catch (IOException err) { return null; } } } public Set getResourcePaths(String path) { // Trim the prefix if (path == null) return null; else if (!path.startsWith("/")) throw new WinstoneException(Launcher.RESOURCES.getString( "WebAppConfig.BadResourcePath", path)); else { String workingPath = null; if (path.equals("/")) workingPath = ""; else { boolean lastCharIsSlash = path.charAt(path.length() - 1) == '/'; workingPath = path.substring(1, path.length() - (lastCharIsSlash ? 1 : 0)); } File inPath = new File(this.webRoot, workingPath.equals("") ? "." : workingPath).getAbsoluteFile(); if (!inPath.exists()) return null; else if (!inPath.isDirectory()) return null; // Find all the files in this folder File children[] = inPath.listFiles(); Set out = new HashSet(); for (int n = 0; n < children.length; n++) { // Write the entry as subpath + child element String entry = //this.prefix + "/" + (workingPath.length() != 0 ? workingPath + "/" : "") + children[n].getName() + (children[n].isDirectory() ? "/" : ""); out.add(entry); } return out; } } /** * @deprecated */ public javax.servlet.Servlet getServlet(String name) { return null; } /** * @deprecated */ public Enumeration getServletNames() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public Enumeration getServlets() { return Collections.enumeration(new ArrayList()); } /** * @deprecated */ public void log(Exception exception, String msg) { this.log(msg, exception); } }
package org.opencms.monitor; import org.opencms.cache.CmsLruCache; import org.opencms.cache.I_CmsLruCacheObject; import org.opencms.cron.I_CmsCronJob; import org.opencms.flex.CmsFlexCache.CmsFlexCacheVariation; import org.opencms.main.CmsEvent; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsPermissionSet; import org.opencms.util.PrintfFormat; import com.opencms.core.CmsException; import com.opencms.defaults.CmsMail; import com.opencms.file.CmsFile; import com.opencms.file.CmsGroup; import com.opencms.file.CmsObject; import com.opencms.file.CmsProject; import com.opencms.file.CmsResource; import com.opencms.file.CmsUser; import com.opencms.util.Utils; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.collections.ExtendedProperties; import org.apache.commons.collections.LRUMap; public class CmsMemoryMonitor implements I_CmsCronJob { /** set interval for clearing the caches to 15 minutes */ private static final int C_INTERVAL_CLEAR = 1000 * 60 * 15; /** max depth for object size recursion */ private static final int C_MAX_DEPTH = 5; private static boolean m_currentlyRunning = false; /** receivers fro status emails */ private String[] m_emailReceiver; /** sender for status emails */ private String m_emailSender; /** the interval to use for sending emails */ private int m_intervalEmail; /** the interval to use for the logging */ private int m_intervalLog; /** the interval to use for warnings if status is disabled */ private int m_intervalWarning; /** the time the caches where last cleared */ private long m_lastClearCache; /** the time the last status email was send */ private long m_lastEmailStatus; /** the time the last warning email was send */ private long m_lastEmailWarning; /** the time the last status log was written */ private long m_lastLogStatus; /** the time the last warning log was written */ private long m_lastLogWarning; /** memory limit that triggers a warning */ private int m_maxUsagePercent; /** contains the object to be monitored */ private Map m_monitoredObjects; /** flag for memory warning mail send */ private boolean m_warningSendSinceLastEmail; /** flag for memory warning mail send */ private boolean m_warningLoggedSinceLastLog; /** * Empty constructor, required by OpenCms scheduler.<p> */ public CmsMemoryMonitor() { // empty } /** * Creates a new monitor with the provided configuration.<p> * * @param configuration the configuration to use */ public CmsMemoryMonitor(ExtendedProperties configuration) { m_warningSendSinceLastEmail = false; m_warningLoggedSinceLastLog = false; m_lastEmailWarning = 0; m_lastEmailStatus = 0; m_lastLogStatus = 0; m_lastLogWarning = 0; m_lastClearCache = 0; m_monitoredObjects = new HashMap(); m_emailSender = configuration.getString("memorymonitor.email.sender"); m_emailReceiver = configuration.getStringArray("memorymonitor.email.receiver"); m_intervalEmail = configuration.getInteger("memorymonitor.email.interval", 0) * 60000; m_intervalLog = configuration.getInteger("memorymonitor.log.interval", 0) * 60000; m_intervalWarning = configuration.getInteger("memorymonitor.warning.interval", 360) * 60000; m_maxUsagePercent = configuration.getInteger("memorymonitor.maxUsagePercent", 90); if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval log : " + (m_intervalLog / 60000) + " min"); OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval email : " + (m_intervalEmail / 60000) + " min"); OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM interval warning : " + (m_intervalWarning / 60000) + " min"); OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM max usage : " + m_maxUsagePercent + "%"); if ((m_emailReceiver == null) || (m_emailSender == null)) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email : disabled"); } else { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email sender : " + m_emailSender); for (int i=0, s=m_emailReceiver.length; i < s; i++) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". MM email receiver : " + (i+1) + " - " + m_emailReceiver[i]); } } } } /** * Initalizes the Memory Monitor.<p> * * @param configuration the OpenCms configurations * @return the initialized CmsMemoryMonitor */ public static CmsMemoryMonitor initialize(ExtendedProperties configuration) { return new CmsMemoryMonitor(configuration); } /** * Clears the OpenCms caches.<p> */ private void clearCaches() { if ((m_lastClearCache + C_INTERVAL_CLEAR) > System.currentTimeMillis()) { // if the cache has already been cleared less then 15 minutes ago we skip this because // clearing the caches to often will hurt system performance and the // setup seems to be in trouble anyway return; } m_lastClearCache = System.currentTimeMillis(); if (OpenCms.getLog(this).isWarnEnabled()) { OpenCms.getLog(this).warn(", Clearing caches because memory consumption has reached a critical level"); } OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false)); System.gc(); } /** * Returns if monitoring is enabled.<p> * * @return true if monitoring is enabled */ public boolean enabled() { return true; } /** * Returns the cache costs of a monitored object.<p> * obj must be of type CmsLruCache * * @param obj the object * @return the cache costs or "-" */ private long getCosts(Object obj) { long costs = 0; if (obj instanceof CmsLruCache) { costs = ((CmsLruCache)obj).getObjectCosts(); if (costs < 0) { costs = 0; } } return costs; } /** * Returns the number of items within a monitored object.<p> * obj must be of type CmsLruCache, CmsLruHashMap or Map * * @param obj the object * @return the number of items or "-" */ private String getItems(Object obj) { if (obj instanceof CmsLruCache) { return Integer.toString(((CmsLruCache)obj).size()); } if (obj instanceof Map) { return Integer.toString(((Map)obj).size()); } return "-"; } /** * Returns the total size of key strings within a monitored object.<p> * obj must be of type map, the keys must be of type String. * * @param obj the object * @return the total size of key strings */ private long getKeySize(Object obj) { if (obj instanceof Map) { return getKeySize ((Map)obj, 1); } return 0; } /** * Returns the total size of key strings within a monitored map.<p> * the keys must be of type String. * * @param map the map * @param depth the max recursion depth for calculation the size * @return total size of key strings */ private long getKeySize(Map map, int depth) { long keySize = 0; for (Iterator i = map.values().iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof Map && depth < C_MAX_DEPTH) { keySize += getKeySize((Map)obj, depth+1); continue; } } for (Iterator i = map.keySet().iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof String) { String s = (String)obj; keySize += (s.length() * 2); } } return keySize; } /** * Returns the max costs for all items within a monitored object.<p> * obj must be of type CmsLruCache, CmsLruHashMap * * @param obj the object * @return max cost limit or "-" */ private String getLimit(Object obj) { if (obj instanceof CmsLruCache) { return Integer.toString(((CmsLruCache)obj).getMaxCacheCosts()); } if (obj instanceof LRUMap) { return Integer.toString(((LRUMap)obj).getMaximumSize()); } return "-"; } /** * Returns the value sizes of value objects within the monitored object.<p> * obj must be of type map * * @param obj the object * @return the value sizes of value objects or "-"-fields */ private long getValueSize(Object obj) { if (obj instanceof CmsLruCache) { return ((CmsLruCache)obj).size(); } if (obj instanceof Map) { return getValueSize((Map)obj, 1); } if (obj instanceof List) { return getValueSize((List)obj, 1); } try { return getMemorySize(obj); } catch (Exception exc) { return 0; } } /** * Returns the total value size of a map object.<p> * * @param mapValue the map object * @param depth the max recursion depth for calculation the size * @return the size of the map object */ private long getValueSize(Map mapValue, int depth) { long totalSize = 0; for (Iterator i = mapValue.values().iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof CmsAccessControlList) { obj = ((CmsAccessControlList)obj).getPermissionMap(); } if (obj instanceof CmsFlexCacheVariation) { obj = ((CmsFlexCacheVariation)obj).m_map; } if (obj instanceof Map && depth < C_MAX_DEPTH) { totalSize += getValueSize((Map)obj, depth+1); continue; } if (obj instanceof List && depth < C_MAX_DEPTH) { totalSize += getValueSize((List)obj, depth+1); continue; } totalSize += getMemorySize(obj); } return totalSize; } /** * Returns the total value size of a list object.<p> * * @param listValue the list object * @param depth the max recursion depth for calculation the size * @return the size of the list object */ private long getValueSize(List listValue, int depth) { long totalSize = 0; for (Iterator i = listValue.iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof CmsAccessControlList) { obj = ((CmsAccessControlList)obj).getPermissionMap(); } if (obj instanceof CmsFlexCacheVariation) { obj = ((CmsFlexCacheVariation)obj).m_map; } if (obj instanceof Map && depth < C_MAX_DEPTH) { totalSize += getValueSize((Map)obj, depth+1); continue; } if (obj instanceof List && depth < C_MAX_DEPTH) { totalSize += getValueSize((List)obj, depth+1); continue; } totalSize += getMemorySize(obj); } return totalSize; } /** * Returns the size of objects that are instances of * <code>byte[]</code>, <code>String</code>, <code>CmsFile</code>,<code>I_CmsLruCacheObject</code>.<p> * For other objects, a size of 0 is returned. * * @param obj the object * @return the size of the object */ private long getMemorySize(Object obj) { if (obj instanceof I_CmsLruCacheObject) { return ((I_CmsLruCacheObject)obj).getLruCacheCosts(); } if (obj instanceof byte[]) { return ((byte[])obj).length; } if (obj instanceof String) { return ((String)obj).length() * 2; } if (obj instanceof CmsFile) { CmsFile f = (CmsFile)obj; if (f.getContents() != null) { return f.getContents().length; } } if (obj instanceof CmsPermissionSet) { return 8; // two ints } if (obj instanceof CmsResource) { return 512; // estimated size } if (obj instanceof CmsUser) { return 1024; // estimated size } if (obj instanceof CmsGroup) { return 260; // estimated size } if (obj instanceof CmsProject) { return 344; } if (obj instanceof Boolean) { return 1; // one boolean } // System.err.println("Unresolved: " + obj.getClass().getName()); return 0; } /**a * @see org.opencms.cron.I_CmsCronJob#launch(com.opencms.file.CmsObject, java.lang.String) */ public String launch(CmsObject cms, String params) throws Exception { CmsMemoryMonitor monitor = OpenCms.getMemoryMonitor(); if (m_currentlyRunning) { return ""; } else { m_currentlyRunning = true; } // check if the system is in a low memory condition if (monitor.lowMemory()) { // log warning monitor.monitorWriteLog(true); // send warning email monitor.monitorSendEmail(true); // clean up caches monitor.clearCaches(); } // check if regular a log entry must be written if ((System.currentTimeMillis() - monitor.m_lastLogStatus) > monitor.m_intervalLog) { monitor.monitorWriteLog(false); } // check if the memory status email must be send if ((System.currentTimeMillis() - monitor.m_lastEmailStatus) > monitor.m_intervalEmail) { monitor.monitorSendEmail(false); } m_currentlyRunning = false; return ""; } /** * Returns true if the system runs low on memory.<p> * * @return true if the system runs low on memory */ public boolean lowMemory() { long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long usage = usedMemory * 100 / Runtime.getRuntime().maxMemory(); return ((m_maxUsagePercent > 0) && (usage > m_maxUsagePercent)); } /** * Sends a warning or status email with OpenCms Memory information.<p> * * @param warning if true, send a memory warning email */ private void monitorSendEmail(boolean warning) { if ((warning && m_warningSendSinceLastEmail) || ((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning)))) { // send only one warning email between regular status emails OR if status is disabled and warn interval has passed return; } else if ((! warning) && (m_intervalEmail <= 0)) { // if email iterval is <= 0 status email is disabled return; } String date = Utils.getNiceDate(System.currentTimeMillis()); String subject; String content = ""; if (warning) { m_warningSendSinceLastEmail = true; m_lastEmailWarning = System.currentTimeMillis(); subject = "OpenCms Memory W A R N I N G [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]"; content += "W A R N I N G !\nOpenCms memory consumption on server " + OpenCms.getServerName().toUpperCase() + " has reached a critical level !\n\n" + "The configured limit is " + m_maxUsagePercent + "%\n\n"; } else { m_warningSendSinceLastEmail = false; m_lastEmailStatus = System.currentTimeMillis(); subject = "OpenCms Memory Status [" + OpenCms.getServerName().toUpperCase() + "/" + date + "]"; } long maxMemory = Runtime.getRuntime().maxMemory() / 1048576; long totalMemory = Runtime.getRuntime().totalMemory() / 1048576; long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576; long freeMemory = maxMemory - usedMemory; long usage = usedMemory * 100 / maxMemory; content += "Memory usage report of OpenCms server " + OpenCms.getServerName().toUpperCase() + " at " + date + "\n\n" + "Memory maximum heap size: " + maxMemory + " mb\n" + "Memory current heap size: " + totalMemory + " mb\n\n" + "Memory currently used : " + usedMemory + " mb (" + usage + "%)\n" + "Memory currently unused : " + freeMemory + " mb\n\n"; if (warning) { content += "*** Please take action NOW to ensure that no OutOfMemoryException occurs.\n\n"; } content += "\nCurrent size of the caches:\n\n"; List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray()); Collections.sort(keyList); long totalSize = 0; for (Iterator keys = keyList.iterator(); keys.hasNext();) { String key = (String)keys.next(); String shortKeys[] = key.split("\\."); String shortKey = shortKeys[shortKeys.length - 2] + "." + shortKeys[shortKeys.length - 1]; PrintfFormat form = new PrintfFormat("%9s"); Object obj = m_monitoredObjects.get(key); long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj); totalSize += size; content += new PrintfFormat("%-42.42s").sprintf(shortKey) + " " + "Entries: " + form.sprintf(getItems(obj)) + " " + "Limit: " + form.sprintf(getLimit(obj)) + " " + "Size: " + form.sprintf(Long.toString(size)) + "\n"; } content += "Memory monitored : " + totalSize / 1048576 + "mb\n\n"; String from = m_emailSender; String[] to = m_emailReceiver; try { if (from != null && to != null) { CmsMail email = new CmsMail(from, to, subject, content, "text/plain"); email.start(); } if (OpenCms.getLog(this).isInfoEnabled()) { OpenCms.getLog(this).info(", Memory Monitor " + (warning?"warning":"status") + " email send"); } } catch (CmsException e) { e.printStackTrace(); } } /** * Write a warning or status log entry with OpenCms Memory information.<p> * * @param warning if true, write a memory warning log entry */ private void monitorWriteLog(boolean warning) { if ((warning && m_warningLoggedSinceLastLog) || ((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))) { // send only one warning email between regular status emails OR if status is disabled and warn interval has passed return; } else if ((! OpenCms.getLog(this).isDebugEnabled()) || ((! warning) && (m_intervalLog <= 0))) { // if email iterval is <= 0 status email is disabled return; } long maxMemory = Runtime.getRuntime().maxMemory() / 1048576; long totalMemory = Runtime.getRuntime().totalMemory() / 1048576; long usedMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576; long freeMemory = maxMemory - usedMemory; long usage = usedMemory * 100 / maxMemory; if (warning) { m_lastLogWarning = System.currentTimeMillis(); m_warningLoggedSinceLastLog = true; OpenCms.getLog(this).warn(", W A R N I N G Memory consumption of " + usage + "% has reached a critical level" + " (" + m_maxUsagePercent + "% configured)"); } else { m_warningLoggedSinceLastLog = false; m_lastLogStatus = System.currentTimeMillis(); } String memStatus = ", Memory max: " + maxMemory + " mb " + "total: " + totalMemory + " mb " + "free: " + freeMemory + " mb " + "used: " + usedMemory + " mb"; if (warning) { OpenCms.getLog(this).warn(memStatus); } else { long totalSize = 0; for (Iterator keys = m_monitoredObjects.keySet().iterator(); keys.hasNext();) { String key = (String)keys.next(); Object obj = m_monitoredObjects.get(key); long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj); totalSize += size; PrintfFormat name1 = new PrintfFormat("%-100s"); PrintfFormat name2 = new PrintfFormat("%-50s"); PrintfFormat form = new PrintfFormat("%9s"); OpenCms.getLog(this).debug(",, " + "Monitored:, " + name1.sprintf(key) + ", " + "Type:, " + name2.sprintf(obj.getClass().getName()) + ", " + "Entries:, " + form.sprintf(getItems(obj)) + ", " + "Limit:, " + form.sprintf(getLimit(obj)) + ", " + "Size:, " + form.sprintf(Long.toString(size))); } memStatus += " " + "monitored: " + totalSize / 1048576 + " mb"; OpenCms.getLog(this).debug(memStatus); } } /** * Adds a new object to the monitor.<p> * * @param objectName name of the object * @param object the object for monitoring */ public void register(String objectName, Object object) { m_monitoredObjects.put(objectName, object); } }
package org.pentaho.di.trans.step; import java.util.ArrayList; import java.util.List; import org.pentaho.di.trans.step.errorhandling.StreamInterface; public class StepIOMeta implements StepIOMetaInterface { private boolean inputAcceptor; private boolean outputProducer; private boolean inputOptional; private boolean outputDynamic; private boolean inputDynamic; private List<StreamInterface> streams; private boolean sortedDataRequired; private String generalInfoDescription; private String generalTargetDescription; /** * @param inputAcceptor * @param outputProducer */ public StepIOMeta(boolean inputAcceptor, boolean outputProducer, boolean inputOptional, boolean sortedDataRequired, boolean inputDynamic, boolean outputDynamic) { this.inputAcceptor = inputAcceptor; this.outputProducer = outputProducer; this.inputOptional = inputOptional; this.sortedDataRequired = sortedDataRequired; this.streams = java.util.Collections.synchronizedList(new ArrayList<StreamInterface>()); this.inputDynamic = inputDynamic; this.outputDynamic = outputDynamic; } /** * @return the inputAcceptor */ public boolean isInputAcceptor() { return inputAcceptor; } /** * @param inputAcceptor the inputAcceptor to set */ public void setInputAcceptor(boolean inputAcceptor) { this.inputAcceptor = inputAcceptor; } /** * @return the outputProducer */ public boolean isOutputProducer() { return outputProducer; } /** * @param outputProducer the outputProducer to set */ public void setOutputProducer(boolean outputProducer) { this.outputProducer = outputProducer; } /** * @return the inputOptional */ public boolean isInputOptional() { return inputOptional; } /** * @param inputOptional the inputOptional to set */ public void setInputOptional(boolean inputOptional) { this.inputOptional = inputOptional; } /** * @return the info streams of this step. * Important: Modifying this list does not have any effect on the Steps IO metadata. * */ public List<StreamInterface> getInfoStreams() { List<StreamInterface> list = new ArrayList<StreamInterface>(); synchronized(streams) { for (StreamInterface stream : streams) { if (stream.getStreamType().equals(StreamInterface.StreamType.INFO)) { list.add(stream); } } } return list; } /** * @return the target streams of this step. * Important: Modifying this list does not have any effect on the Steps IO metadata. * */ public List<StreamInterface> getTargetStreams() { List<StreamInterface> list = new ArrayList<StreamInterface>(); synchronized(streams) { for (StreamInterface stream : streams) { if (stream.getStreamType().equals(StreamInterface.StreamType.TARGET)) { list.add(stream); } } } return list; } /** * @return the sortedDataRequired */ public boolean isSortedDataRequired() { return sortedDataRequired; } /** * @param sortedDataRequired the sortedDataRequired to set */ public void setSortedDataRequired(boolean sortedDataRequired) { this.sortedDataRequired = sortedDataRequired; } public void addStream(StreamInterface stream) { streams.add(stream); } public String[] getInfoStepnames() { List<StreamInterface> infoStreams = getInfoStreams(); String[] names = new String[infoStreams.size()]; for (int i=0;i<names.length;i++) { names[i] = infoStreams.get(i).getStepname(); } return names; } public String[] getTargetStepnames() { List<StreamInterface> targetStreams = getTargetStreams(); String[] names = new String[targetStreams.size()]; for (int i=0;i<names.length;i++) { names[i] = targetStreams.get(i).getStepname(); } return names; } /** * Replace the info steps with the supplied source steps. * * @param infoSteps */ public void setInfoSteps(StepMeta[] infoSteps) { // First get the info steps... List<StreamInterface> list = new ArrayList<StreamInterface>(); synchronized(streams) { for (StreamInterface stream : streams) { if (stream.getStreamType().equals(StreamInterface.StreamType.INFO)) { list.add(stream); } } } for (int i=0;i<infoSteps.length;i++) { if (i>=list.size()) { throw new RuntimeException("We expect all possible info streams to be pre-populated!"); } streams.get(i).setStepMeta(infoSteps[i]); } } /** * @return the generalInfoDescription */ public String getGeneralInfoDescription() { return generalInfoDescription; } /** * @param generalInfoDescription the generalInfoDescription to set */ public void setGeneralInfoDescription(String generalInfoDescription) { this.generalInfoDescription = generalInfoDescription; } /** * @return the generalTargetDescription */ public String getGeneralTargetDescription() { return generalTargetDescription; } /** * @param generalTargetDescription the generalTargetDescription to set */ public void setGeneralTargetDescription(String generalTargetDescription) { this.generalTargetDescription = generalTargetDescription; } public void clearStreams() { streams.clear(); } /** * @return the outputDynamic */ public boolean isOutputDynamic() { return outputDynamic; } /** * @param outputDynamic the outputDynamic to set */ public void setOutputDynamic(boolean outputDynamic) { this.outputDynamic = outputDynamic; } /** * @return the inputDynamic */ public boolean isInputDynamic() { return inputDynamic; } /** * @param inputDynamic the inputDynamic to set */ public void setInputDynamic(boolean inputDynamic) { this.inputDynamic = inputDynamic; } public StreamInterface findTargetStream(StepMeta targetStep) { for (StreamInterface stream : getTargetStreams()) { if (targetStep.equals(stream.getStepMeta())) return stream; } return null; } public StreamInterface findInfoStream(StepMeta infoStep) { for (StreamInterface stream : getInfoStreams()) { if (infoStep.equals(stream.getStepMeta())) return stream; } return null; } }
package org.phenoscape.bridge; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.obd.model.CompositionalDescription; import org.obd.model.Graph; import org.obd.model.LinkStatement; import org.obd.model.Node; import org.obd.model.CompositionalDescription.Predicate; import org.obd.model.Node.Metatype; import org.obd.model.vocabulary.TermVocabulary; import org.obo.datamodel.Link; import org.obo.datamodel.OBOClass; import org.obo.util.ReasonerUtil; import org.obo.util.TermUtil; import org.phenoscape.model.Character; import org.phenoscape.model.DataSet; import org.phenoscape.model.Phenotype; import org.phenoscape.model.State; import org.phenoscape.model.Taxon; import org.purl.obo.vocab.RelationVocabulary; /** * Bridges between phenoscape objects and a model expressed using OBO * primitives. * * OBD Instances and the relations between them generally reflect java instances * of the corresponding phenoscape model. We model cells, states and * matrixes/datasets using instances of CDAO owl classes. We go beyond the * phenoscape model and CDAO in positing an annotation link between the * phenotype and the taxon. The annotation is linked to the cell. * * TODO: reverse mapping TODO: finalize relations and classes; both from OBO_REL * and CDAO TODO: make this subclass a generic bridge framework * * @author cjm * */ public class OBDModelBridge { protected Graph graph; // CDAO vacab : TODO public static String DATASET_TYPE_ID = "cdao:CharacterStateDataMatrix"; public static String STATE_TYPE_ID = "cdao:CharacterStateDomain"; public static String CELL_TYPE_ID = "cdao:CharacterStateDatum"; public static String CHARACTER_TYPE_ID = "cdao:Character"; public static String PUBLICATION_TYPE_ID = "cdao:Pub"; // TODO public static String HAS_PUB_REL_ID = "cdao:hasPub"; public static String HAS_STATE_REL_ID = "cdao:has_Datum"; public static String REFERS_TO_TAXON_REL_ID = "cdao:hasTaxon"; // has_TU? // TODO public static String HAS_CHARACTER_REL_ID = "cdao:has_Character"; public static String HAS_PHENOTYPE_REL_ID = "cdao:has_Phenotype"; // TODO public static String TAXON_PHENOTYPE_REL_ID = "PHENOSCAPE:exhibits"; // TODO public static String CELL_TO_STATE_REL_ID = "cdao:has_State"; // TODO public static String ANNOT_TO_CELL_REL_ID = "has_source"; // TODO private static TermVocabulary vocab = new TermVocabulary(); private static RelationVocabulary relationVocabulary = new RelationVocabulary(); private Map<Character, String> characterIdMap = new HashMap<Character, String>(); private Map<State, String> stateIdMap = new HashMap<State, String>(); private Map<Taxon, String> taxonIdMap = new HashMap<Taxon, String>(); private Map<Phenotype, String> phenotypeIdMap = new HashMap<Phenotype, String>(); private BufferedWriter problemLog; // added to avoid null IDs associated with Phenotype instances: Cartik1.0 // private static int phenotype_id = 1; // private static int taxon_id = 1; private Set<String> fileSpecificProblemSet = new HashSet<String>(); // an instantiation block { try { problemLog = new BufferedWriter( new FileWriter(new File("testfiles/problemLog.txt"))); problemLog.write("PROBLEM LOG\n___________\n\n"); } catch (Exception e) { e.printStackTrace(); } } public OBDModelBridge() { super(); graph = new Graph(); } public Graph getGraph() { return graph; } public void setGraph(Graph graph) { this.graph = graph; } public Graph translate(DataSet ds, File dataFile) { String dsId = UUID.randomUUID().toString(); // Dataset metadata Node dsNode = createInstanceNode(dsId, DATASET_TYPE_ID); // link publication to dataset Node pubNode = createInstanceNode(ds.getPublication(), PUBLICATION_TYPE_ID); LinkStatement ds2p = new LinkStatement(dsId, HAS_PUB_REL_ID, pubNode .getId()); graph.addStatement(ds2p); // link dataset to taxa for (Taxon t : ds.getTaxa()) { // avoid uploading taxa without names; Cartik1.0 if (t.getValidName() != null && t.getValidName().getName().length() > 0) { Node tn = translate(t); if (tn.getId() != null) { taxonIdMap.put(t, tn.getId()); LinkStatement ds2t = new LinkStatement(dsId, REFERS_TO_TAXON_REL_ID, tn.getId()); graph.addStatement(ds2t); } } } // link dataset to characters used in that dataset for (Character character : ds.getCharacters()) { // if (character.toString().length() > 0) { String cid = UUID.randomUUID().toString(); Node characterNode = createInstanceNode(cid, CHARACTER_TYPE_ID); characterNode.setLabel(character.getLabel()); characterIdMap.put(character, cid); LinkStatement ds2c = new LinkStatement(dsId, HAS_CHARACTER_REL_ID, cid); graph.addStatement(ds2c); for (State state : character.getStates()) { String sid = UUID.randomUUID().toString(); Node stateNode = createInstanceNode(sid, STATE_TYPE_ID); stateNode.setLabel(state.getLabel()); stateIdMap.put(state, sid); LinkStatement c2s = new LinkStatement(cid, HAS_STATE_REL_ID, sid); graph.addStatement(c2s); for (Phenotype p : state.getPhenotypes()) { // a minimal check: Cartik1.0 if (p.getEntity() != null && p.getQuality() != null) { CompositionalDescription cd = translate(p); if (cd.getId() != null && cd.getId().length() > 0) { phenotypeIdMap.put(p, cd.getId()); LinkStatement s2p = new LinkStatement(sid, HAS_PHENOTYPE_REL_ID, cd.getId()); graph.addStatement(s2p); } } } } } // Matrix -> annotations for (Taxon t : ds.getTaxa()) { for (Character c : ds.getCharacters()) { State state = ds.getStateForTaxon(t, c); if (state == null) { // System.err.println("no state for t:"+t+" char:"+c); continue; } for (Phenotype p : state.getPhenotypes()) { // taxon to phenotype LinkStatement annotLink = new LinkStatement(); // to avoid insertion of null Ids: Cartik1.0 annotLink.setNodeId(taxonIdMap.get(t)); String problem = ""; if (phenotypeIdMap.get(p) != null && taxonIdMap.get(t) != null) { annotLink.setNodeId(taxonIdMap.get(t)); annotLink.setTargetId(phenotypeIdMap.get(p)); annotLink.setRelationId(TAXON_PHENOTYPE_REL_ID); annotLink.addSubLinkStatement("posited_by", dsId); graph.addStatement(annotLink); } else if(taxonIdMap.get(t) == null){ problem = "Null identifier for taxon: " + t; if(phenotypeIdMap.get(p) != null){ problem += " exhibiting quality " + p.getQuality() + " inhering in " + p.getEntity(); } else{ problem += " exhibiting null phenotype"; } } else if(phenotypeIdMap.get(p) == null){ problem = "Taxon: " + taxonIdMap.get(t) + " exhibits null phenotype"; } if(problem.length() > 0){ fileSpecificProblemSet.add(problem); } // link description of biology back to data Node cellNode = createInstanceNode(UUID.randomUUID() .toString(), CELL_TYPE_ID); annotLink.addSubLinkStatement(CELL_TO_STATE_REL_ID, cellNode.getId()); // cell to state LinkStatement cell2s = new LinkStatement(cellNode.getId(), CELL_TO_STATE_REL_ID, stateIdMap.get(state)); // TODO graph.addStatement(cell2s); } } } // problems.put(dataFile.getName(), fileSpecificProblemSet); try{ problemLog.write(dataFile.getName() + "\n\n"); for(String s : fileSpecificProblemSet){ System.err.println(s); problemLog.write(s + "\n"); } problemLog.write("\n"); } catch(Exception e){ e.printStackTrace(); } return graph; } public CompositionalDescription translate(Phenotype p) { OBOClass e = p.getEntity(); OBOClass q = p.getQuality(); OBOClass e2 = p.getRelatedEntity(); OBOClass u = p.getUnit(); Integer count = p.getCount(); Float m = p.getMeasurement(); CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.addArgument(q.getID()); // check to avoid a NullPointerException if (e.getParents() != null) { cd.addArgument(relationVocabulary.inheres_in(), translateOBOClass(e)); } if (e2 != null) cd.addArgument(relationVocabulary.towards(), translateOBOClass(e2)); if (false) { if (u == null && m != null) { // TODO : throw } if (m != null) { cd.addArgument("has_unit", u.getID()); // cd.addArgument("has_measurement",m); } } cd.setId(cd.generateId()); getGraph().addStatements(cd); return cd; } public CompositionalDescription translateOBOClass(OBOClass c) { if (TermUtil.isIntersection(c)) { CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.setId(c.getID()); OBOClass g = ReasonerUtil.getGenus(c); cd.addArgument(translateOBOClass(g)); Collection<Link> diffs = ReasonerUtil.getDifferentia(c); for (Link diff : diffs) { cd.addArgument(diff.getType().getID(), translateOBOClass((OBOClass) diff.getParent())); /* * CompositionalDescription restr = new * CompositionalDescription(Predicate.RESTRICTION); * CompositionalDescription diffCD = ); LinkStatement ls = new * LinkStatement(null,diff.getType().getID(), diffCD.getId()); * restr.setRestriction(ls); * restr.addArgument(ls.getTargetId()); cd.addArgument(restr); */ } return cd; } else { CompositionalDescription d = new CompositionalDescription( Predicate.ATOM); d.setNodeId(c.getID()); return d; } } public Node translate(Taxon taxon) { Node n = new Node(taxon.getValidName().getID()); n.setLabel(taxon.getValidName().getName()); graph.addNode(n); return n; } protected Node createInstanceNode(String id, String typeId) { Node n = new Node(id); n.setMetatype(Metatype.CLASS); n.addStatement(new LinkStatement(id, relationVocabulary.instance_of(), typeId)); graph.addNode(n); return n; } }
package org.smblott.intentradio; import android.app.Service; import android.content.Intent; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.IBinder; import android.os.PowerManager; import android.os.StrictMode; import android.app.PendingIntent; import android.app.Notification; import android.app.NotificationManager; import android.app.Notification.Builder; import android.media.AudioManager; import android.media.AudioManager.OnAudioFocusChangeListener; import android.media.MediaPlayer; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnInfoListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnCompletionListener; import android.net.Uri; import android.os.Build.VERSION; import android.webkit.URLUtil; public class IntentPlayer extends Service implements OnBufferingUpdateListener, OnInfoListener, OnErrorListener, OnPreparedListener, OnAudioFocusChangeListener, OnCompletionListener { private static final int note_id = 100; private static final String preference_file = "state"; private static SharedPreferences settings = null; private static Context context = null; private static PendingIntent pending_stop = null; private static PendingIntent pending_play = null; private static PendingIntent pending_restart = null; private static String app_name = null; private static String app_name_long = null; private static String intent_play = null; private static String intent_stop = null; private static String intent_pause = null; private static String intent_restart = null; private static String intent_state_request = null; private static String default_url = null; private static String default_name = null; public static String name = null; public static String url = null; private static NotificationManager note_manager = null; private static Notification note = null; private static MediaPlayer player = null; private static Builder builder = null; private static AudioManager audio_manager = null; private static Playlist playlist_task = null; private static AsyncTask<Integer,Void,Void> pause_task = null; @Override public void onCreate() { context = getApplicationContext(); Logger.init(context); app_name = getString(R.string.app_name); app_name_long = getString(R.string.app_name_long); intent_play = getString(R.string.intent_play); intent_stop = getString(R.string.intent_stop); intent_pause = getString(R.string.intent_pause); intent_restart = getString(R.string.intent_restart); intent_state_request = context.getString(R.string.intent_state_request); default_url = getString(R.string.default_url); default_name = getString(R.string.default_name); settings = getSharedPreferences(preference_file, context.MODE_PRIVATE); url = settings.getString("url", default_url); name = settings.getString("name", default_name); note_manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); pending_stop = PendingIntent.getBroadcast(context, 0, new Intent(intent_stop), 0); pending_play = PendingIntent.getBroadcast(context, 0, new Intent(intent_play), 0); pending_restart = PendingIntent.getBroadcast(context, 0, new Intent(intent_restart), 0); audio_manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); builder = new Notification.Builder(context) .setSmallIcon(R.drawable.intent_radio) .setPriority(Notification.PRIORITY_HIGH) .setContentIntent(pending_stop) .setContentTitle(app_name_long) // not available in API 16... // .setShowWhen(false) ; } public void onDestroy() { log("Destroyed."); stop(); if ( player != null ) { player.release(); player = null; } Logger.state("off"); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if ( intent == null || ! intent.hasExtra("action") ) return done(); if ( intent.hasExtra("debug") ) Logger.state(intent.getStringExtra("debug")); if ( ! Counter.still(intent.getIntExtra("counter", Counter.now())) ) return done(); String action = intent.getStringExtra("action"); log("Action: ", action); if ( action.equals(intent_stop) ) return stop(); if ( action.equals(intent_pause) ) return pause(); if ( action.equals(intent_restart) ) return restart(); if ( action.equals(intent_state_request) ) { State.get_state(context); return done(); } if ( action.equals(intent_play) ) { if ( intent.hasExtra("url") ) url = intent.getStringExtra("url"); if ( intent.hasExtra("name") ) name = intent.getStringExtra("name"); Editor editor = settings.edit(); editor.putString("url", url); editor.putString("name", name); editor.commit(); log("Name: ", name); log("URL: ", url); return play(url); } log("unknown action: ", action); return done(); } private int play() { return play(url); } private int play(String url) { stop(false); toast(name); log("Play: ", url); // Notification... builder .setOngoing(true) .setContentIntent(pending_stop) .setContentText("Connecting..."); note = builder.build(); startForeground(note_id, note); // Check URL... if ( ! URLUtil.isValidUrl(url) ) { toast("Invalid URL."); return stop("Invalid URL."); } // Audio focus... int focus = audio_manager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if ( focus != AudioManager.AUDIOFOCUS_REQUEST_GRANTED ) return stop("Failed to obtain audio focus!"); // Set up media player... if ( player == null ) { log("Creating media player..."); player = new MediaPlayer(); player.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setOnPreparedListener(this); player.setOnBufferingUpdateListener(this); player.setOnInfoListener(this); player.setOnErrorListener(this); player.setOnCompletionListener(this); } else log("Re-using existing player."); WifiLocker.lock(context, app_name_long); log("Connecting..."); // Playlists... /* Is there a better way to test whether a URL is a playlist? */ playlist_task = null; if ( url.endsWith(PlaylistPls.suffix) ) playlist_task = new PlaylistPls(this); if ( url.endsWith(PlaylistM3u.suffix) ) playlist_task = new PlaylistM3u(this); if ( playlist_task != null ) { playlist_task.execute(url); notificate("Fetching playlist..."); notificate_click_to_stop(); return done(State.STATE_BUFFER); } // Ready... return play_launch(url); } private static String previous_launch_url = null; private static boolean previous_launch_successful = false; public void play_relaunch() { if ( previous_launch_successful && previous_launch_url != null ) play_launch(previous_launch_url); } public int play_launch(String url) { log("Launching: ", url); notificate("Connecting..."); notificate_click_to_stop(); previous_launch_successful = false; if ( ! URLUtil.isValidUrl(url) ) { previous_launch_url = null; previous_launch_successful = false; toast("Invalid URL."); return stop("Invalid URL."); } previous_launch_url = url; try { player.setVolume(1.0f, 1.0f); player.setDataSource(context, Uri.parse(url)); player.prepareAsync(); } catch (Exception e) { return stop("Initialisation error."); } return done(State.STATE_BUFFER); } private int stop() { // Stop, kill notification an send state. // This is a real and final stop(). return stop(true,null,true); } private int stop(boolean real_stop) { // Stop, kill notification and possibly send state. return stop(true,null,real_stop); } private int stop(String msg) { // Stop, keep notification and do send state. return stop(false,msg,true); } private int stop(boolean kill_note, String text, boolean real_stop) { log("Stopping kill_note: ", ""+kill_note); log("Stopping real_stop: ", ""+real_stop); log("Stopping text: ", text == null ? "null" : text); audio_manager.abandonAudioFocus(this); WifiLocker.unlock(); // Time moves on... Counter.time_passes(); previous_launch_url = null; // Stop player... if ( player != null ) { log("Stopping player..."); if ( player.isPlaying() ) player.stop(); player.reset(); } // Handle notification... if ( kill_note || text == null || text.length() == 0 ) { stopForeground(true); note = null; } else { log("Keeping (now-)dismissable note: ", text); notificate(text,false); notificate_click_to_restart(); } if ( real_stop ) // We're still holding resources, including the player itself. // Spin off a task to clean up, soon. // No need to cancel this. Because the state is now STATE_STOP, all // events effecting the relevance of this thread move time on. new Later() { @Override public void later() { if ( player != null ) { log("Releasing player."); player.release(); player = null; } } }.start(); return done(real_stop ? State.STATE_STOP : null); } private int pause() { return pause("Paused..."); } private int pause(String msg) { log("Pause: ", State.current()); if ( player == null ) return done(); // if ( ! player.isPlaying() ) // return done(); if ( State.is(State.STATE_PAUSE) || ! State.is_playing() ) return done(); if ( pause_task != null ) pause_task.cancel(true); pause_task = null; if ( URLUtil.isNetworkUrl(previous_launch_url) ) // We're still holding resources, including a Wifi Wakelock and the player // itself. Spin off a task to convert this "pause" into a stop, soon, if // necessary. This will be cacelled if we restart(), or become // irrelevant if another action such as stop() or play() occurs, because // then time will have passed. pause_task = new Later() { @Override public void later() { pause_task = null; stop("Suspended, click to restart..."); } }.start(); player.pause(); notificate(msg); notificate_click_to_restart(); return done(State.STATE_PAUSE); } private int duck(String msg) { log("Duck: ", State.current()); if ( State.is(State.STATE_DUCK) || ! State.is_playing() ) return done(); player.setVolume(0.1f, 0.1f); notificate(msg); notificate_click_to_stop(); return done(State.STATE_DUCK); } private int restart() { log("Restart: ", State.current()); if ( player == null || State.is(State.STATE_STOP) || State.is(State.STATE_ERROR) ) return play(); if ( State.is(State.STATE_PLAY) || State.is(State.STATE_BUFFER) ) return done(); if ( State.is(State.STATE_DUCK) ) { player.setVolume(0.1f, 0.1f); notificate(); notificate_click_to_stop(); return done(State.STATE_PLAY); } int focus = audio_manager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if ( focus != AudioManager.AUDIOFOCUS_REQUEST_GRANTED ) { toast("Intent Radio:\nFailed to (re-)acquire audio focus."); return done(); } if ( pause_task != null ) { pause_task.cancel(true); pause_task = null; } player.setVolume(1.0f, 1.0f); player.start(); notificate(); notificate_click_to_stop(); return done(State.STATE_PLAY); } private int done(String state) { if ( state != null ) State.set_state(context, state); return done(); } private int done() { return START_NOT_STICKY; } @Override public void onPrepared(MediaPlayer mp) { if ( mp == player ) { log("Starting...."); player.start(); State.set_state(context, State.STATE_PLAY); notificate(); notificate_click_to_stop(); // A launch is successful if there is no error within the first few // seconds. If a launch is successful then later the stream fails, // then the launch will be repeated. If it fails before it is // considered successful, then it will not be repeated. This is // intented to prevent thrashing. // No need to cancel this. All events effecting the relevance of this // thread move time on. // TODO: Is that really true? new Later(20) { @Override public void later() { log("Launch successful."); previous_launch_successful = true; } }.start(); } } @Override public void onBufferingUpdate(MediaPlayer player, int percent) { /* if ( 0 <= percent && percent <= 100 ) log("Buffering: ", ""+percent, "%"); */ } @Override public boolean onInfo(MediaPlayer player, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: State.set_state(context, State.STATE_BUFFER); notificate("Buffering..."); notificate_click_to_stop(); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: State.set_state(context, State.STATE_PLAY); notificate(); notificate_click_to_stop(); break; } return true; } @Override public boolean onError(MediaPlayer player, int what, int extra) { log("Error: ", ""+what); if ( player != null && previous_launch_url != null && previous_launch_successful && URLUtil.isNetworkUrl(previous_launch_url)) { player.reset(); play_relaunch(); } else { switch ( what ) { case MediaPlayer.MEDIA_ERROR_SERVER_DIED: stop("Media server died."); break; case MediaPlayer.MEDIA_ERROR_UNKNOWN: stop("Media error."); break; default: stop("Unknown error."); break; } } return true; } @Override public void onCompletion(MediaPlayer mp) { log("Completion."); stop("Completed. Click to restart."); done(State.STATE_COMPLETE); // if ( player != null // && previous_launch_url != null // && previous_launch_successful // && URLUtil.isNetworkUrl(previous_launch_url)) // player.reset(); // play_relaunch(); // else // stop("Completed. Click to restart."); // done(State.STATE_COMPLETE); } @Override public void onAudioFocusChange(int change) { log("onAudioFocusChange: ", ""+change); if ( player != null ) switch (change) { case AudioManager.AUDIOFOCUS_GAIN: log("audiofocus_gain"); restart(); break; case AudioManager.AUDIOFOCUS_LOSS: log("audiofocus_loss"); stop("Audio focus lost, stopped..."); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: log("audiofocus_loss_transient"); pause("Audio focus lost, paused..."); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: log("audiofocus_loss_transient_can_duck"); duck("Audio focus lost, ducking..."); break; } } private void notificate() { notificate(null); } private void notificate(String msg) { notificate(msg,true); } private void notificate(String msg, boolean ongoing) { if ( note != null ) { log("Notificate: ", msg == null ? name : msg); note = builder .setOngoing(ongoing) .setContentText(msg == null ? name : msg) .build(); note_manager.notify(note_id, note); } } private void notificate_click_to_stop() { note = builder.setContentIntent(pending_stop).build(); note_manager.notify(note_id, note); } private void notificate_click_to_restart() { note = builder.setContentIntent(pending_restart).build(); note_manager.notify(note_id, note); } private void log(String... msg) { Logger.log(msg); } private void toast(String msg) { Logger.toast(msg); } @Override public IBinder onBind(Intent intent) { return null; } }
package org.usfirst.frc.team2503.r2016; import edu.wpi.first.wpilibj.IterativeRobot; public class Robot extends IterativeRobot { public Robot() { } public void robotInit() { } public void disabledInit() { } public void disabledPeriodic() { } public void autonomousInit() { } public void autonomousPeriodic() { } public void teleopInit() { } public void teleopPeriodic() { } public void testInit() { } public void testPeriodic() { } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // FILE NAME: Autonomous.java (Team 339 - Kilroy) // ABSTRACT: // This file is where almost all code for Kilroy will be // written. All of these functions are functions that should // override methods in the base class (IterativeRobot). The // functions are as follows: // Init() - Initialization code for teleop mode // should go here. Will be called each time the robot enters // teleop mode. // Periodic() - Periodic code for teleop mode should // go here. Will be called periodically at a regular rate while // the robot is in teleop mode. // Team 339. package org.usfirst.frc.team339.robot; import org.usfirst.frc.team339.Hardware.Hardware; import org.usfirst.frc.team339.Utils.Drive; import edu.wpi.first.wpilibj.Relay; /** * This class contains all of the user code for the Autonomous part of the * match, namely, the Init and Periodic code * * @author Nathanial Lydick * @written Jan 13, 2015 */ public class Teleop { /** * User Initialization code for teleop mode should go here. Will be called * once when the robot enters teleop mode. * * @author Nathanial Lydick * @written Jan 13, 2015 */ int control = 1; public static void init () { // initialize all encoders here Hardware.leftFrontEncoder.reset(); Hardware.rightFrontEncoder.reset(); Hardware.rightRearEncoder.reset(); Hardware.leftRearEncoder.reset(); // initialize all motors here Hardware.leftRearMotor.set(0.0); Hardware.rightRearMotor.set(0.0); Hardware.rightFrontMotor.set(0.0); Hardware.leftFrontMotor.set(0.0); // Hardware.rightFrontMotor.setInverted(true); // TODO takeout // Hardware.rightRearMotor.setInverted(true); // Hardware.leftFrontMotor.setInverted(true); // Hardware.leftRearMotor.setInverted(true); Hardware.mecanumDrive.setMecanumJoystickReversed(false); // Hardware.tankDrive.setGear(1); // Hardware.leftUS.setScalingFactor(.13); // Hardware.leftUS.setOffsetDistanceFromNearestBummper(0); // Sets the scaling factor and general ultrasonic stuff Hardware.rightUS.setScalingFactor(.13); Hardware.rightUS.setOffsetDistanceFromNearestBummper(3); Hardware.rightUS.setNumberOfItemsToCheckBackwardForValidity(3); // Hardware.leftUS.setNumberOfItemsToCheckBackwardForValidity(1); // Hardware.LeftUS.setConfidenceCalculationsOn(false); // Hardware.RightUS.setConfidenceCalculationsOn(false); // Hardware.tankDrive.setRightMotorDirection(MotorDirection.REVERSED); // boolean testchoosers = true; // SendableChooser sendablechoosetest; // sendablechoosetest = new SendableChooser(); // sendablechoosetest.addDefault("default", testchoosers); // Sendable testsendable = ; // SmartDashboard.putData("teleoptest", testsendable); Hardware.tankDrive.setGear(1); isAligning = false; isStrafingToTarget = false; Hardware.autoDrive.setDriveCorrection(.3); Hardware.autoDrive.setEncoderSlack(1); // TODO } // end Init /** * User Periodic code for teleop mode should go here. Will be called * periodically at a regular rate while the robot is in teleop mode. * * @author Nathanial Lydick * @written Jan 13, 2015 */ public static void periodic () { // Command chooseTrueorFalse; // SendableChooser testbool; // testbool = new SendableChooser(); // testbool.addDefault("true", Hardware.changeBool.equals(true)); // testbool.addObject(" false", Hardware.changeBool.equals(false)); // int control = 1; // SmartDashboard.putData("testbool", testbool); // switch (control) // case 1: // // System.out.println(Hardware.changeBool.getClass()); // control = 1; // break; // case 2: // break; if (Hardware.leftDriver.getTrigger() && !previousFireButton) { firing = !firing; } if (firing) Hardware.shooter.fire(); // previousFireButton = Hardware.leftDriver.getTrigger(); // if (fireCount > 0) // if (Hardware.shooter.fire()) // fireCount--; if (preparingToFire == false) Hardware.shooter.stopFlywheelMotor(); /* * System.out.println("Firecount: " + fireCount); * * System.out.println( * "Flywheel speed: " + Hardware.shooterMotor.getSpeed()); */ // TODO Figure out why the ring light is flickering if (Hardware.ringlightSwitch.isOnCheckNow()) { Hardware.ringlightRelay.set(Relay.Value.kOn); } else { Hardware.ringlightRelay.set(Relay.Value.kOff); } // Hardware.gearServo.setAngle(200); // Hardware.gearServo.getAngle(); // Print out any data we want from the hardware elements. printStatements(); // TESTING CODE: if (Hardware.rightOperator.getRawButton(2)) Hardware.intake.startIntake(); else if (Hardware.rightOperator.getRawButton(3)) Hardware.intake.reverseIntake(); else Hardware.intake.stopIntake(); // Driving code if (Hardware.leftDriver.getTrigger()) { rotationValue = Hardware.leftDriver.getTwist(); System.out.println("Twist: " + Hardware.leftDriver.getTwist()); } else rotationValue = 0.0; if (!isAligning && !isStrafingToTarget) if (Hardware.isUsingMecanum == true) Hardware.mecanumDrive.drive( Hardware.leftDriver.getMagnitude(), Hardware.leftDriver.getDirectionDegrees(), rotationValue); else Hardware.tankDrive.drive(Hardware.rightDriver.getY(), Hardware.leftDriver.getY()); if (Hardware.leftDriver.getRawButton(9) == true) { Hardware.autoDrive.brake(-.1, -.1); } } // CAMERA CODE // "Cancel basically everything" button // if (Hardware.leftOperator.getRawButton(7) // || Hardware.leftOperator.getRawButton(6)) // System.out.println("Cancelling everything"); // isAligning = false; // isStrafingToTarget = false; // // Testing aligning to target // if (Hardware.rightOperator.getRawButton(4)) // isAligning = true; // if (isAligning) // alignValue = Hardware.autoDrive.alignToGear(CAMERA_ALIGN_CENTER, // movementSpeed, CAMERA_ALIGN_DEADBAND); // if (alignValue == Drive.AlignReturnType.ALIGNED) // System.out.println("We are aligned!"); // isAligning = false; // else if (alignValue == Drive.AlignReturnType.MISALIGNED) // System.out.println("We are not aligned!"); // else if (alignValue == Drive.AlignReturnType.NO_BLOBS) // System.out.println("We don't see anything!"); // // Testing Strafe to target // if (Hardware.rightOperator.getRawButton(8)) // isStrafingToTarget = true; // if (isStrafingToTarget) // alignValue = Hardware.autoDrive.strafeToGear(movementSpeed, .2, // CAMERA_ALIGN_DEADBAND, CAMERA_ALIGN_CENTER, 20); // if (alignValue == Drive.AlignReturnType.ALIGNED) // System.out.println("We are aligned!"); // else if (alignValue == Drive.AlignReturnType.MISALIGNED) // System.out.println("WE are NOT aligned!"); // else if (alignValue == Drive.AlignReturnType.NO_BLOBS) // System.out.println("We have no blobs!"); // else if (alignValue == Drive.AlignReturnType.CLOSE_ENOUGH) // System.out.println("We are good to go!"); // isStrafingToTarget = false; // Testing good speed values // if (Hardware.leftOperator.getRawButton(4) && !hasPressedFive) // // adds .05 to movement speed then prints movementSpeed // movementSpeed += .05; // System.out.println(movementSpeed); // hasPressedFour = Hardware.leftOperator.getRawButton(4); // if (Hardware.leftOperator.getRawButton(5) && !hasPressedFour) // // subtracts .05 from movement speed then prints movementSpeed // movementSpeed -= .05; // System.out.println(movementSpeed); // hasPressedFive = Hardware.leftOperator.getRawButton(5); // Hardware.axisCamera.takeSinglePicture(Hardware.leftOperator.getRawButton(8)); // // end // Hardware.axisCamera.takeSinglePicture(Hardware.rightOperator.getRawButton(8)); // Periodic // private static boolean isSpeedTesting = false; private static double rotationValue = 0.0; private static Drive.AlignReturnType alignValue = Drive.AlignReturnType.MISALIGNED; private static boolean isAligning = false; private static boolean isStrafingToTarget = false; private static double movementSpeed = 0.3; private static boolean hasPressedFour = false; private static boolean hasPressedFive = false; private static boolean previousFireButton = false; private static boolean preparingToFire = false; private static boolean firing = false; /** * stores print statements for future use in the print "bank", statements * are commented out when not in use, when you write a new print * statement, "deposit" the statement in the correct "bank" * do not "withdraw" statements, unless directed to. * * NOTE: Keep the groupings below, which correspond in number and * order as the hardware declarations in the HARDWARE class * * @author Ashley Espeland * @written 1/28/16 * * Edited by Ryan McGee * Also Edited by Josef Liebl * */ public static void printStatements () { // Motor controllers // prints value of the motors // System.out.println("Right Front Motor Controller: " // + Hardware.rightFrontMotor.get()); // System.out.println("Left Front Motor Controller: " + // Hardware.leftFrontMotor.get()); // System.out.println("Right Rear Motor Controller: " + // Hardware.rightRearMotor.get()); // System.out.println("Left Rear Motor Controller: " + // Hardware.leftRearMotor.get()); // System.out.println("Flywheel Motor: " + Hardware.shooterMotor.get()); // System.out.println("Intake Motor: " + Hardware.intakeMotor.get()); if (Hardware.rightOperator.getRawButton(11)) { Hardware.elevatorMotor.setSpeed(1); System.out.println( "Elevator Motor: " + Hardware.elevatorMotor.get()); } // System.out.println("Turret Spark: " + Hardware.gimbalMotor.get()); // CAN items // prints value of the CAN controllers // Hardware.CAN.printAllPDPChannels(); // Relay // prints value of the relay states // if (Hardware.ringlightSwitch.isOnCheckNow()) // System.out.println("Ring light relay is On"); // else if (!Hardware.ringlightSwitch.isOnCheckNow()) // System.out.println("Ring light relay is Off"); // Digital Inputs // Switches // prints state of switches // System.out.println("Gear Limit Switch: " // + Hardware.gearLimitSwitch.isOn()); // System.out.println("Backup or fire: " + Hardware.backupOrFire.isOn()); // System.out.println("Enable Auto: " + Hardware.enableAutonomous.isOn()); // System.out.println("Path Selector: " + // Hardware.pathSelector.getPosition()); // System.out.println("Right UltraSonic distance from bumper: " // + Hardware.rightUS.getDistanceFromNearestBumper()); // Encoders // prints the distance from the encoders /* * System.out.println("Right Front Encoder: " * + Hardware.rightFrontEncoder.get()); * System.out.println("Right Rear Encoder: " * + Hardware.rightRearEncoder.get()); * System.out.println("Left Front Encoder: " * + Hardware.leftFrontEncoder.get()); * System.out.println("Left Rear Encoder: " * + Hardware.leftRearEncoder.get()); */ /* * System.out.println("Right Front Encoder Distance: " * + Hardware.autoDrive.getRightRearEncoderDistance()); * System.out.println("Right Rear Encoder Distance: " * + Hardware.autoDrive.getRightRearEncoderDistance()); * System.out.println("Left Front Encoder Distance: " * + Hardware.autoDrive.getLeftFrontEncoderDistance()); * System.out.println("Left Rear Encoder Distance: " * + Hardware.autoDrive.getLeftFrontEncoderDistance()); */ // Red Light/IR Sensors // prints the state of the sensor // if (Hardware.ballLoaderSensor.isOn() == true) // System.out.println("Ball IR Sensor is On"); // else if (Hardware.ballLoaderSensor.isOn() == false) // System.out.println("Ball IR Sensor is Off"); // Pneumatics // Compressor // prints information on the compressor // There isn't one at the moment // Solenoids // prints the state of solenoids // There are none at the moment // That seems familiar... // Analogs // We don't want the print statements to flood everything and go ahhhhhhhh // if (Hardware.rightOperator.getRawButton(11)) // System.out.println("LeftUS = " // + Hardware.leftUS.getDistanceFromNearestBumper()); // System.out.println("RightUS = " // + Hardware.rightUS.getDistanceFromNearestBumper()); // System.out.println("Delay Pot: " + Hardware.delayPot.get()); // pots // where the pot is turned to // System.out.println("Delay Pot Degrees" + Hardware.delayPot.get()); // Connection Items // Cameras // prints any camera information required // System.out.println("Expected center: " + CAMERA_ALIGN_CENTER); // Hardware.imageProcessor.processImage(); // System.out.println("Number of blobs: " + Hardware.imageProcessor // .getParticleAnalysisReports().length); // if (Hardware.imageProcessor.getNthSizeBlob(1) != null) // System.out // .println("Actual center: " + ((Hardware.imageProcessor // .getNthSizeBlob(0).center_mass_x // + Hardware.imageProcessor // .getNthSizeBlob(1).center_mass_x) // / Hardware.axisCamera // .getHorizontalResolution()); // System.out.println("Deadband: " + CAMERA_ALIGN_DEADBAND); // Driver station // Joysticks // information about the joysticks // System.out.println("Left Joystick: " + // Hardware.leftDriver.getDirectionDegrees()); // System.out.println("Right Joystick: " + // Hardware.rightDriver.getDirectionDegrees()); // System.out.println("Left Operator: " + // Hardware.leftOperator.getDirectionDegrees()); // System.out.println("Right Operator: " + // Hardware.rightOperator.getDirectionDegrees()); // System.out.println("Twist: " + Hardware.leftDriver.getTwist()); // System.out.println("Left Joystick: " + Hardware.leftDriver.getY()); // System.out.println("Right Joystick: " + Hardware.rightDriver.getY()); // System.out.println("Left Operator: " + Hardware.leftOperator.getY()); // System.out.println("Right Operator: " + Hardware.rightOperator.getY()); // Kilroy ancillary items // timers // what time does the timer have now } // end printStatements private final static double CAMERA_ALIGN_SPEED = .5; //// The dead zone for the aligning TODO private final static double CAMERA_ALIGN_DEADBAND = 10.0 // +/- Pixels / Hardware.axisCamera.getHorizontalResolution(); private final static double CAMERA_ALIGN_CENTER = .478; // Relative coordinates // TUNEABLES } // end class
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package org.usfirst.frc.team5160.robot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.RobotDrive.MotorType; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.CANTalon.ControlMode; import edu.wpi.first.wpilibj.CANTalon.FeedbackDevice; import edu.wpi.first.wpilibj.Preferences; import edu.wpi.first.wpilibj.Gyro; public class Robot extends SampleRobot { Preferences prefs; RobotDrive drive = new RobotDrive(0, 1, 2, 3); CANTalon chainMotor = new CANTalon(0); CANTalon chainMotorSlave = new CANTalon(1); Joystick rightStick = new Joystick(0); Joystick leftStick = new Joystick(1); JoystickButton halfSpeedButton = new JoystickButton(leftStick, 1); JoystickButton calibrate = new JoystickButton(rightStick, 11); CameraServer cameraServer; Gyro gyro; ControlMode mode; double ticksPerInch = 136.3158; double hookMoveAmount = 20; double desiredChainPosition = 0.0; double chainStartingPosition = 0.0; double chainSpeed = 170.0; int prevDir = 0; long lastDashUpdateTime = 0; double drivingMult = 0.5; double turningMult = 0.3; double xyClipAmt = 0.2; double zClipAmt = 0.2; double brakeYMult = 0.3; double brakeZMult = 0.7; double pP = 5.0; double pI = 0.0; double pD = 30.0; double vP = 2.0; double vI = 0.001; double vD = 0.0; public void print(String msg) { System.out.println(msg); } public void robotInit() { prefs = Preferences.getInstance(); gyro = new Gyro(0); gyro.initGyro(); chainMotorSlave.changeControlMode(ControlMode.Follower); chainMotorSlave.set(0); //set to follow chainMotor, with id 0 chainMotor.setFeedbackDevice(FeedbackDevice.QuadEncoder); if (!prefs.containsKey("3chainCalibration")) { savePositionAsCalibration(); } else { chainStartingPosition = prefs.getDouble("3chainCalibration", 0.0); } if (!prefs.containsKey("3lastRawChainPosition")) { saveLastRawPosition(); } else { chainStartingPosition -= prefs.getDouble("3lastRawChainPosition", 0.0); prefs.putDouble("3chainCalibration", chainStartingPosition); } if (!prefs.containsKey("turnAngle")) { prefs.putDouble("turnAngle", 81); } if (!prefs.containsKey("robotMoveForwardTime")) { prefs.putLong("robotMoveForwardTime", 500); } if (!prefs.containsKey("robotMoveForwardTime2")) { prefs.putLong("robotMoveForwardTime2", 200); } if (!prefs.containsKey("robotMoveForwardTime3")) { prefs.putLong("robotMoveForwardTime3", 2000); } desiredChainPosition = getChainPosition(); positionControlMode(); //initialize SmartDashboard with default values SmartDashboard.putNumber("DrivingMultiplier", drivingMult); SmartDashboard.putNumber("TurningMultiplier", turningMult); SmartDashboard.putNumber("xyClipAmt", xyClipAmt); SmartDashboard.putNumber("zClipAmt", zClipAmt); SmartDashboard.putNumber("brakeYMult", brakeYMult); SmartDashboard.putNumber("brakeZMult", brakeZMult); SmartDashboard.putNumber("chainSpeed", chainSpeed); SmartDashboard.putNumber("pP", pP); SmartDashboard.putNumber("pI", pI); SmartDashboard.putNumber("pD", pD); SmartDashboard.putNumber("vP", vP); SmartDashboard.putNumber("vI", vI); SmartDashboard.putNumber("vD", vD); drive.setInvertedMotor(MotorType.kFrontRight, true); drive.setInvertedMotor(MotorType.kRearRight, true); cameraServer = CameraServer.getInstance(); cameraServer.setQuality(10); cameraServer.startAutomaticCapture("cam0"); } public void disabled() { prefs.save(); print("Preferences saved."); } public void autonomous() { if (isAutonomous() && isEnabled()) { double startPos = getChainPosition(); velocityControlMode(); int ultimateHeight = 33; while (getChainPosition() < startPos + 8 && isAutonomous() && isEnabled()) { chainMotor.set(chainSpeed); } long startTime = System.currentTimeMillis(); long duration = prefs.getLong("robotMoveForwardTime", 500); while (System.currentTimeMillis() <= startTime + duration) { drive.mecanumDrive_Cartesian(0, -0.3, 0, 0); //drive straight if (getChainPosition() < startPos + ultimateHeight) chainMotor.set(chainSpeed); } drive.mecanumDrive_Cartesian(0, 0, 0, 0); //stop while (getChainPosition() < startPos + ultimateHeight && isAutonomous() && isEnabled()) { chainMotor.set(chainSpeed); } chainMotor.set(0); //turn left double startAngle = gyro.getAngle(); print("Start Angle: " + startAngle); while (gyro.getAngle() > startAngle - prefs.getDouble("turnAngle", 81) && isAutonomous() && isEnabled()) { print("" + gyro.getAngle()); drive.mecanumDrive_Cartesian(0, 0, -0.3, 0); //turn left } //drive to bin startTime = System.currentTimeMillis(); duration = prefs.getLong("robotMoveForwardTime2", 200); while (System.currentTimeMillis() <= startTime + duration) { drive.mecanumDrive_Cartesian(0, -0.25, 0, 0); //drive straight } drive.mecanumDrive_Cartesian(0, 0, 0, 0); //stop //lift bin startPos = getChainPosition(); while (getChainPosition() < startPos + 10 && isAutonomous() && isEnabled()) { chainMotor.set(chainSpeed); } chainMotor.set(0); //turn right while (gyro.getAngle() < startAngle && isAutonomous() && isEnabled()) { print("" + gyro.getAngle()); drive.mecanumDrive_Cartesian(0, 0, 0.3, 0); //turn right } //drive to zone startTime = System.currentTimeMillis(); duration = prefs.getLong("robotMoveForwardTime3", 2000); while (System.currentTimeMillis() <= startTime + duration) { drive.mecanumDrive_Cartesian(0, -0.3, 0, 0); //drive straight } drive.mecanumDrive_Cartesian(0, 0, 0, 0); //stop desiredChainPosition = getChainPosition(); } } /** Main operator control. */ public void operatorControl() { positionControlMode(); while (isOperatorControl() && isEnabled()) { long curTime = System.currentTimeMillis(); //update smart dashboard values if (curTime > lastDashUpdateTime + 1000) { drivingMult = SmartDashboard.getNumber("DrivingMultiplier"); turningMult = SmartDashboard.getNumber("TurningMultiplier"); xyClipAmt = SmartDashboard.getNumber("xyClipAmt"); zClipAmt = SmartDashboard.getNumber("zClipAmt"); brakeYMult = SmartDashboard.getNumber("brakeYMult"); brakeZMult = SmartDashboard.getNumber("brakeZMult"); chainSpeed = SmartDashboard.getNumber("chainSpeed"); pP = SmartDashboard.getNumber("pP"); pI = SmartDashboard.getNumber("pI"); pD = SmartDashboard.getNumber("pD"); vP = SmartDashboard.getNumber("vP"); vI = SmartDashboard.getNumber("vI"); vD = SmartDashboard.getNumber("vD"); if (mode == ControlMode.Position) { if (pP != chainMotor.getP() || pI != chainMotor.getI() || pD != chainMotor.getD()) chainMotor.setPID(pP, pI, pD); } else if (mode == ControlMode.Speed) { if (vP != chainMotor.getP() || vI != chainMotor.getI() || vD != chainMotor.getD()) chainMotor.setPID(vP, vI, vD); } SmartDashboard.putNumber("Encoder position", getChainPosition()); SmartDashboard.putNumber("Desired position", desiredChainPosition); SmartDashboard.putNumber("Raw position", chainMotor.getPosition()); saveLastRawPosition(); lastDashUpdateTime = curTime; } //check if we should calibrate if (calibrate.get()) savePositionAsCalibration(); //get joystick values double xVal = clip(leftStick.getX(), xyClipAmt); double yVal = clip(leftStick.getY(), xyClipAmt); double zVal = clip(leftStick.getZ(), zClipAmt); //decrease values if brake pressed if (halfSpeedButton.get()) { yVal *= brakeYMult; zVal *= brakeZMult; } //drive debugging double debugSpeed = (-leftStick.getThrottle() + 1) / 2; double pov = leftStick.getPOV(0); //main drive if (pov != -1) { //debug driving with the POV drive.mecanumDrive_Polar(debugSpeed, pov, 0); } else { //normal driving drive.mecanumDrive_Cartesian(xVal * drivingMult, yVal * drivingMult, zVal * turningMult, 0); } //chain driving double chainPov = rightStick.getPOV(0); double dif = getChainPosition() - desiredChainPosition; int dir = dif == 0 ? 0 : (int) (-dif / Math.abs(dif)); double chainJoyVal = clip(-rightStick.getY() * 0.5, 0.1); if (chainJoyVal == 0) { if (mode == ControlMode.PercentVbus) { positionControlMode(); desiredChainPosition = getChainPosition(); } if (mode == ControlMode.Speed) { if (dir == -prevDir) positionControlMode(); else { chainMotor.set(chainSpeed * dir); } prevDir = dir; } else { //mode == ControlMode.Position setChainPosition(desiredChainPosition); if (chainPov == 0 || chainPov == 180) { if (chainPov == 180 && desiredChainPosition % (int) hookMoveAmount == 0) desiredChainPosition -= hookMoveAmount; else { desiredChainPosition = ((int) desiredChainPosition / (int) hookMoveAmount) * hookMoveAmount; if (chainPov == 0) desiredChainPosition += hookMoveAmount; } velocityControlMode(); } prevDir = 0; } } else { if (mode != ControlMode.PercentVbus) percentControlMode(); chainMotor.set(chainJoyVal); } Timer.delay(0.005); //do not delete } } /** This saves the current raw position as the last known raw position. */ private void saveLastRawPosition() { prefs.putDouble("2lastRawChainPosition", chainMotor.getPosition()); } /** This saves the current raw position as the 0.0 position. */ private void savePositionAsCalibration() { chainStartingPosition = chainMotor.getPosition(); prefs.putDouble("2chainCalibration", chainStartingPosition); desiredChainPosition = getChainPosition(); } /** Change control mode to percent voltage. */ private void percentControlMode() { mode = ControlMode.PercentVbus; chainMotor.changeControlMode(mode); } /** Change control mode to position. */ private void positionControlMode() { mode = ControlMode.Position; chainMotor.changeControlMode(mode); chainMotor.setPID(pP, pI, pD); } /** Change control mode to velocity. */ private void velocityControlMode() { mode = ControlMode.Speed; chainMotor.changeControlMode(mode); chainMotor.setPID(vP, vI, vD); } /** This method returns the accurate chain position based on the calibration. */ private double getChainPosition() { return (chainMotor.getPosition() - chainStartingPosition) / ticksPerInch; } /** This method sets the chain position based on the calibration. */ private void setChainPosition(double pos) { chainMotor.set(pos * ticksPerInch + chainStartingPosition); } /** If val is less than clipAmt away from 0, then 0 is returned. * Otherwise, the val will be scaled from the clipAmt to 1.0 or -1.0 */ private double clip(double val, double clipAmt) { if (Math.abs(val) < clipAmt) { return 0; } else { if (val > 0) val -= clipAmt; else val += clipAmt; val *= 1 / (1 - clipAmt); return val; } } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5506.Steamworks; import org.usfirst.frc5506.Steamworks.commands.Auto; import org.usfirst.frc5506.Steamworks.commands.Routine; import org.usfirst.frc5506.Steamworks.commands.Teleop; import org.usfirst.frc5506.Steamworks.subsystems.Conveyer; import org.usfirst.frc5506.Steamworks.subsystems.DriveTrain; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command auto; Command teleop; // 1 = left; 2 = center; 3 = right; public static byte starting = 1; // I technically don't need '<Byte>' here, but just for safety, I use it public static SendableChooser<Byte> pos; public static SendableChooser<Command> autochooser; // same for '<Command>' here public static SendableChooser<Boolean> rumble; public static int time = 0; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; public static Conveyer conveyer; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); conveyer = new Conveyer(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // OI must be constructed after subsystems. If the OI creates Commands //(which it very likely will), subsystems are not guaranteed to be // constructed yet. Thus, their requires() statements may grab null // pointers. Bad news. Don't move it. oi = new OI(); // instantiate the command used for the autonomous period auto = new Auto(); teleop = new Teleop(); Vision.init(); // front camera (ball end) CameraServer.getInstance().startAutomaticCapture(0).setExposureManual(40); // back camera (gear end) CameraServer.getInstance().startAutomaticCapture(1).setExposureManual(50); driveTrain.gyro.calibrate(); starting = (byte) DriverStation.getInstance().getLocation(); pos = new SendableChooser<Byte>(); switch(starting) { case(1): pos.addDefault("Left", (byte) 1); pos.addObject("Center", (byte) 2); pos.addObject("Right", (byte) 3); break; case(3): pos.addObject("Left", (byte) 1); pos.addObject("Center", (byte) 2); pos.addDefault("Right", (byte) 3); break; case(2): default: // 'Center' is a safe bet.... right? pos.addObject("Left", (byte) 1); pos.addDefault("Center", (byte) 2); pos.addObject("Right", (byte) 3); break; } autochooser = new SendableChooser<Command>(); autochooser.addObject("Gear", new Auto()); autochooser.addObject("Mobility", new Auto(true)); autochooser.addDefault("Play dead", new Routine("SafeReset")); // at least safe reset the conveyer rumble = new SendableChooser<Boolean>(); rumble.addDefault("Rumble On", true); rumble.addObject("Rumble Off", false); SmartDashboard.putData("Rumble", rumble); SmartDashboard.putData("Position", pos); SmartDashboard.putData("Routine", autochooser); System.out.println("All systems go!"); } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ Robot.driveTrain.driveArcade(0, 0); Robot.conveyer.set(0); } public void disabledPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (auto != null) auto.cancel(); if (teleop != null) teleop.start(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); //if (Vision.izgud()) //System.out.println(Vision.getDistance() + "\t" + Vision.getTurningAngle()); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } public void autonomousInit() { // schedule the autonomous command (example) auto = autochooser.getSelected(); if (auto != null) auto.start(); } public void robotPeriodic() { // if Pi hasn't responded for a second, it's probably dead // Pi "responds" by setting "true" to "Pi" every time it processes a frame SmartDashboard.putBoolean("Pi", time < 50); if (Vision.isalive()) { time = 0; Vision.table.putBoolean("running", false); } else time++; if (Vision.izgud() && !Vision.isalive()) { // clearly the Pi isn't on to target the peg Vision.table.putBoolean("sight", false); } SmartDashboard.putBoolean("Sight", Vision.izgud()); // update selectors // and pray the DS is still alive to make these choices... starting = pos.getSelected(); } }
package org.visualtrading.xml; import org.visualtrading.model.NewModel; import org.visualtrading.xml.nanoxml.XMLElement; import java.util.Enumeration; import java.util.Hashtable; public class ModelConverter implements Converter { public ModelConverter() { super(); } public void addToMapping(Hashtable mappings) { mappings.put(tagName(), this); mappings.put(getObjClass(), this); mappings.put(tagName(), this); } /* (non-Javadoc) * @see org.visualtrading.xml.Converter#convertFrom(java.lang.Object) */ public String convertFrom(Object object) { return object.toString(); } /* (non-Javadoc) * @see org.visualtrading.xml.Converter#convertTo(java.lang.String) */ public Object convertTo(String value) { return value; } public XMLElement fromObject(Object obj) { XMLElement xml = new XMLElement(); if (obj != null) { NewModel model = (NewModel) obj; xml.setName(tagName()); for (Enumeration e = model.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); xml.addChild(ConverterEngine.toXML("key", key, model.get(key))); } } return xml; } public Object fromXml(XMLElement xml) { NewModel table = null; try { table = (NewModel) ConverterEngine.getClassFrom(xml).newInstance(); for (Enumeration e = xml.enumerateChildren(); e.hasMoreElements();) { XMLElement element = (XMLElement) e.nextElement(); table.put(element.getAttribute("key"), ConverterEngine.fromXML(element)); } } catch (InstantiationException e1) { // TODO e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO e1.printStackTrace(); } return table; } /* (non-Javadoc) * @see org.visualtrading.xml.Converter#getDefault() */ public Object getDefault() { return new Hashtable(); } public Class getObjClass() { return NewModel.class; } public String tagName() { return "Model1"; } }
package pl.polidea.imagemanager; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.Point; import android.util.Log; /** * Image manager. Manager provides way to load image resources asynchronously * with many options like: * <ul> * <li>loading from * <ul> * <li>file system * <li>application resources * </ul> * <li>caching * <li>low-quality preview * <li>sub-sampling * <li>loading rescaled bitmap * <li>using strong GC-proof cache * </ul> * Provides optional logging on different levels which makes it easy to debug * your code. Image manager should be interfaced mostly by * {@link #getImage(ImageManagerRequest)} or using * {@link pl.polidea.imagemanager.ManagedImageView} * * * @author karooolek * @see #getImage(ImageManagerRequest) * @see pl.polidea.imagemanager.ManagedImageView */ public final class ImageManager { private static final String TAG = ImageManager.class.getSimpleName(); private static final class LoadedBitmap { private final WeakReference<Bitmap> weakBitmap; private final Bitmap bitmap; LoadedBitmap(final Bitmap bitmap, final boolean strong) { this.bitmap = strong ? bitmap : null; this.weakBitmap = strong ? null : new WeakReference<Bitmap>(bitmap); } Bitmap getBitmap() { return weakBitmap == null ? bitmap : weakBitmap.get(); } } private ImageManager() { // unreachable private constructor } private static long start; private static boolean logging = true; static Map<ImageManagerRequest, LoadedBitmap> loaded = new ConcurrentHashMap<ImageManagerRequest, LoadedBitmap>(); static List<ImageManagerRequest> requests = new ArrayList<ImageManagerRequest>(); static BlockingQueue<ImageManagerRequest> loadQueue = new LinkedBlockingQueue<ImageManagerRequest>(); /** * Load image request. Loads synchronously image specified by request. Adds * loaded image to cache. * * @param req * image request * @param preview * loading preview or not. * @return loaded image. */ public static Bitmap loadImage(final ImageManagerRequest req, final boolean preview) { // no request if (req == null) { return null; } if (logging) { if (preview) { Log.d(TAG, "Loading preview image " + req); } else { Log.d(TAG, "Loading full image " + req); } } Bitmap bmp = null; // loading options final Options opts = new Options(); // sub-sampling options opts.inSampleSize = preview ? 8 : req.subsample; // load from filename if (req.filename != null) { final File file = new File(req.filename); if (!file.exists() || file.isDirectory()) { if (logging) { Log.d(TAG, "Error while loading image " + req + ". File does not exist."); } return null; } bmp = BitmapFactory.decodeFile(req.filename, opts); } // load from resources if (req.resId >= 0) { bmp = BitmapFactory.decodeResource(req.resources, req.resId, opts); } // scaling options if (!preview && (req.width > 0 && req.height > 0)) { final Bitmap sBmp = Bitmap.createScaledBitmap(bmp, req.width, req.height, true); if (sBmp != null) { bmp.recycle(); bmp = sBmp; } } return bmp; } /** * Unload image specified by image request and remove it from cache. * * @param req * image request. */ public static void unloadImage(final ImageManagerRequest req) { if (logging) { Log.d(TAG, "Unloading image " + req); } requests.remove(req); loadQueue.remove(req); final Bitmap bmp = loaded.get(req).getBitmap(); if (bmp != null) { bmp.recycle(); } loaded.remove(req); } /** * Clean up image manager. Unloads all cached images. */ public static synchronized void cleanUp() { if (logging) { Log.d(TAG, "Image manager clean up"); } for (final ImageManagerRequest req : loaded.keySet()) { if (logging) { Log.d(TAG, "Unloading image " + req); } final Bitmap bmp = loaded.get(req).getBitmap(); if (bmp != null) { bmp.recycle(); } } loaded.clear(); loadQueue.clear(); requests.clear(); if (logging) { logImageManagerStatus(); } } /** * Initialize image manager loading thread. This is asynchronous thread * where image request are processed and loaded to cache. */ public static void initLoadingThread() { final Thread t = new Thread(TAG) { @Override public void run() { // save start time start = System.currentTimeMillis(); if (logging) { Log.d(TAG, "Image loading thread started"); } // loop final boolean exit = false; while (!exit) { // get loading request ImageManagerRequest req; try { req = loadQueue.take(); } catch (final InterruptedException e) { break; } try { // load bitmap final Bitmap bmp = loadImage(req, false); // remove preview image if (loaded.containsKey(req)) { final Bitmap prevbmp = loaded.get(req).getBitmap(); if (prevbmp != null && !prevbmp.isRecycled()) { if (logging) { Log.d(TAG, "Unloading preview image " + req); } prevbmp.recycle(); } } // save bitmap loaded.put(req, new LoadedBitmap(bmp, req.strong)); // logImageManagerStatus(); } catch (final OutOfMemoryError err) { // oh noes! we have no memory for image if (logging) { Log.e(TAG, "Error while loading full image " + req + ". Out of memory."); } cleanUp(); } } // while(!exit) if (logging) { Log.d(TAG, "Image loading thread ended"); } } }; t.start(); } /** * Check if image manager logging is enabled. * * @return true if image manager logging is enabled, false otherwise. */ public static boolean isLoggingEnabled() { return logging; } /** * Enable/disable image manager logging. * * @param logging * enable/disable image manager logging. */ public static void setLoggingEnabled(final boolean logging) { ImageManager.logging = logging; } /** * Log image manager current status. Logs: * <ul> * <li>manager uptime in seconds * <li>all loaded images details * <li>used memory * </ul> */ public static void logImageManagerStatus() { final float t = 0.001f * (System.currentTimeMillis() - start); if (logging) { Log.d(TAG, "Uptime: " + t + "[s]"); } final int imgn = loaded.size(); if (logging) { Log.d(TAG, "Loaded images: " + imgn); } if (imgn > 0) { int totalSize = 0; for (final LoadedBitmap limg : loaded.values()) { final Bitmap bmp = limg.getBitmap(); // no bitmap if (bmp == null) { continue; } // get bits per pixel int bpp = 0; if (bmp.getConfig() != null) { switch (bmp.getConfig()) { case ALPHA_8: bpp = 1; break; case RGB_565: case ARGB_4444: bpp = 2; break; case ARGB_8888: default: bpp = 4; break; } } // count total size totalSize += bmp.getWidth() * bmp.getHeight() * bpp; } if (logging) { Log.d(TAG, "Loaded images size: " + totalSize / 1024 + "[kB]"); } } if (logging) { Log.d(TAG, "Queued images: " + loadQueue.size()); } } /** * Get size of image specified by image request. * * @param req * image request. * @return image dimensions. */ public static Point getImageSize(final ImageManagerRequest req) { final Options options = new Options(); options.inJustDecodeBounds = true; if (req.filename != null) { BitmapFactory.decodeFile(req.filename, options); } if (req.resId >= 0) { BitmapFactory.decodeResource(req.resources, req.resId, options); } return new Point(options.outWidth, options.outHeight); } /** * Get image specified by image request. This returns image as currently * available in manager, which means: * <ul> * <li>not loaded at all: NULL - no image * <li>loaded preview * <li>loaded full * </ul> * If image is not available in cache, image request is posted to * asynchronous loading and will be available soon. All image options are * specified in image request. * * @param req * image request. * @return image as currently available in manager (preview/full) or NULL if * it's not available at all. * @see pl.polidea.imagemanager.ImageManagerRequest */ public static Bitmap getImage(final ImageManagerRequest req) { Bitmap bmp = null; // save bitmap request synchronized (requests) { requests.remove(req); requests.add(req); } // look for bitmap in already loaded resources if (loaded.containsKey(req)) { bmp = loaded.get(req).getBitmap(); } // bitmap found if (bmp != null) { return bmp; } // load preview image quickly if (req.preview) { try { bmp = loadImage(req, true); if (bmp == null) { return null; } // save preview image loaded.put(req, new LoadedBitmap(bmp, req.strong)); // logImageManagerStatus(); } catch (final OutOfMemoryError err) { // oh noes! we have no memory for image if (logging) { Log.e(TAG, "Error while loading preview image " + req + ". Out of memory."); logImageManagerStatus(); } } } // add image to loading queue if (!loadQueue.contains(req)) { if (logging) { Log.d(TAG, "Queuing image " + req + " to load"); } loadQueue.add(req); } return bmp; } static { initLoadingThread(); } }
package libraryFunctions; import ast.ASTNode; import ast.ASTVisitor; import ast.ASTVisitorException; import java.util.ArrayList; import environment.Environment; import environment.FunctionEnv; import ast.Statement; import ast.ExpressionStatement; import ast.Block; import ast.Expression; import ast.FunctionDef; import ast.visitors.ToStringASTVisitor; import dataStructures.FoxObject; import dataStructures.FoxArray; import dataStructures.AFoxDataStructure; import symbols.value.Value; import symbols.value.Value_t; import symbols.value.StaticVal; import static utils.Constants.LIBRARY_FUNC_ARG; public class LibraryFunctions { public static void print(Environment env) throws ASTVisitorException { if (!checkArgumentsNum(LibraryFunction_t.PRINT, env)) { return; } int totalActuals = env.totalActuals(); for (int i = 0; i < totalActuals; i++) { String data; Value argument = env.getActualArgument(LIBRARY_FUNC_ARG + i); if (argument.isUndefined()) { data = "UNDEFINED"; } else if (argument.isNull()) { data = "NULL"; } else if (argument.isUserFunction() || argument.isAST()) { ASTNode program = (ASTNode) argument.getData(); ASTVisitor astVisitor = new ToStringASTVisitor(); program.accept(astVisitor); data = astVisitor.toString(); } else if (argument.isLibraryFunction()) { //Get Library Function Name String func = argument.getData().toString() .replace("public static void libraryFunctions.LibraryFunctions.", "") .replace("(environment.Environment)", "") .replace(" throws ast.ASTVisitorException", ""); //Get Total Arguments int totalArgs = LibraryFunction_t.totalArgs(func); //Library Function toString StringBuilder msg = new StringBuilder(); msg.append("LibraryFunctions.").append(func).append("( "); if (totalArgs == -1) { msg.append("arg0, arg1, arg2, ... )"); } else if (totalArgs == -2) { msg.append("arg0key, arg0value, arg1key, arg1value, ... )"); } else { for (int j = 0; i < totalArgs; i++) { msg.append("arg, "); } msg.setCharAt(msg.length() - 1, ')'); msg.setCharAt(msg.length() - 2, ' '); } data = msg.toString(); } else { data = argument.getData().toString(); } System.out.print(data); } } public static void println(Environment env) throws ASTVisitorException { if (!checkArgumentsNum(LibraryFunction_t.PRINT_LN, env)) { return; } print(env); System.out.println(""); } public static void len(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.LEN, env)) { return; } AFoxDataStructure fdataStructure = getObjectArgument(env); if (fdataStructure == null) { return; } StaticVal retVal = new StaticVal(Value_t.INTEGER, fdataStructure.size()); ((FunctionEnv) env).setReturnVal(retVal); } public static void keys(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.KEYS, env)) { return; } AFoxDataStructure fobject = getObjectArgument(env); if (!(fobject instanceof FoxObject)) { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument must be of type Object."); ((FunctionEnv) env).setReturnVal(retVal); return; } FoxArray farray = new FoxArray(((FoxObject) fobject).keys()); StaticVal retVal = new StaticVal(Value_t.TABLE, farray); ((FunctionEnv) env).setReturnVal(retVal); } public static void values(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.VALUES, env)) { return; } AFoxDataStructure fdataStructure = getObjectArgument(env); if (fdataStructure == null) { return; } FoxArray farray = new FoxArray(fdataStructure.values()); StaticVal retVal = new StaticVal(Value_t.TABLE, farray); ((FunctionEnv) env).setReturnVal(retVal); } public static void diagnose(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.DIAGNOSE, env)) { return; } //Prepare environment for Library function call: addFirst FunctionEnv tmpEnv = new FunctionEnv(); tmpEnv.insert(LIBRARY_FUNC_ARG + 0, env.getActualArgument(LIBRARY_FUNC_ARG + 0)); tmpEnv.insert(LIBRARY_FUNC_ARG + 1, env.getActualArgument(LIBRARY_FUNC_ARG + 1)); addFirst(tmpEnv); ((FunctionEnv) env).setReturnVal(tmpEnv.getReturnVal()); if (tmpEnv.getReturnVal().getType().equals(Value_t.ERROR)) { return; } //Prepare environment for Library function call: addOnExitPoints tmpEnv = new FunctionEnv(); tmpEnv.insert(LIBRARY_FUNC_ARG + 0, env.getActualArgument(LIBRARY_FUNC_ARG + 0)); tmpEnv.insert(LIBRARY_FUNC_ARG + 1, env.getActualArgument(LIBRARY_FUNC_ARG + 2)); addOnExitPoints(tmpEnv); ((FunctionEnv) env).setReturnVal(tmpEnv.getReturnVal()); } public static void addFirst(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ADDFIRST, env)) { return; } FunctionDef funcdef = getFunctionArgument(env); if (funcdef == null) { return; } Value onEnterValue = env.getActualArgument(LIBRARY_FUNC_ARG + 1); Block funcBody = funcdef.getBody(); if (onEnterValue.getData() instanceof Expression) { ExpressionStatement exstmtEnter = new ExpressionStatement((Expression) onEnterValue.getData()); funcBody.prependStatement(exstmtEnter); } else if (onEnterValue.getData() instanceof ArrayList<?>) { funcBody.prependStatements((ArrayList<Statement>) onEnterValue.getData()); } else { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument must be either an expression or a statement list."); ((FunctionEnv) env).setReturnVal(retVal); } } public static void addOnExitPoints(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ADDONEXITPOINTS, env)) { return; } FunctionDef funcdef = getFunctionArgument(env); if (funcdef == null) { return; } Value onExitValue = env.getActualArgument(LIBRARY_FUNC_ARG + 1); Block funcBody = funcdef.getBody(); if (onExitValue.getData() instanceof Expression) { ExpressionStatement exstmtExit = new ExpressionStatement((Expression) onExitValue.getData()); funcBody.addStatementOnExit(exstmtExit); funcBody.appendStatement(exstmtExit); } else if (onExitValue.getData() instanceof ArrayList<?>) { funcBody.addStatementsOnExit((ArrayList<Statement>) onExitValue.getData()); funcBody.appendStatements((ArrayList<Statement>) onExitValue.getData()); } else { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument must be either an expression or a statement list."); ((FunctionEnv) env).setReturnVal(retVal); } } private static Value isType(Value val, Value_t type) { if (val.getType().equals(type)) { return new StaticVal<>(Value_t.BOOLEAN, true); } else { return new StaticVal<>(Value_t.BOOLEAN, false); } } public static void isNull(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISNULL, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.NULL); ((FunctionEnv) env).setReturnVal(ret); } public static void isUndefined(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISUNDEFINED, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.UNDEFINED); ((FunctionEnv) env).setReturnVal(ret); } public static void isInteger(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISINTEGER, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.INTEGER); ((FunctionEnv) env).setReturnVal(ret); } public static void isReal(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISREAL, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.REAL); ((FunctionEnv) env).setReturnVal(ret); } public static void isString(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISSTRING, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.STRING); ((FunctionEnv) env).setReturnVal(ret); } public static void isBoolean(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISBOOLEAN, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.BOOLEAN); ((FunctionEnv) env).setReturnVal(ret); } public static void isTable(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISTABLE, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.TABLE); ((FunctionEnv) env).setReturnVal(ret); } public static void isFunc(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISFUNC, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.USER_FUNCTION); ((FunctionEnv) env).setReturnVal(ret); } public static void isLibFunc(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISLIBFUNC, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.LIBRARY_FUNCTION); ((FunctionEnv) env).setReturnVal(ret); } public static void isObject(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISOBJECT, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.OBJECT); ((FunctionEnv) env).setReturnVal(ret); } public static void isAST(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.ISAST, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = isType(val, Value_t.AST); ((FunctionEnv) env).setReturnVal(ret); } public static void str(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.STR, env)) { return; } Value val = env.getActualArgument(LIBRARY_FUNC_ARG + 0); Value ret = new StaticVal<>(Value_t.STRING, val.getData().toString()); ((FunctionEnv) env).setReturnVal(ret); } public static void sqrt(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.SQRT, env)) { return; } Double data = getDoubleArgument(env); if (data == null) { return; } StaticVal retVal; data = Math.sqrt(data); //Return sprt if ((data == Math.floor(data)) && !Double.isInfinite(data)) { retVal = new StaticVal(Value_t.INTEGER, data); } else { retVal = new StaticVal(Value_t.REAL, data); } ((FunctionEnv) env).setReturnVal(retVal); } public static void cos(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.COS, env)) { return; } Double data = getDoubleArgument(env); if (data == null) { return; } data = Math.cos(data); StaticVal retVal = new StaticVal(Value_t.REAL, data); ((FunctionEnv) env).setReturnVal(retVal); } public static void sin(Environment env) { if (!checkArgumentsNum(LibraryFunction_t.SIN, env)) { return; } Double data = getDoubleArgument(env); if (data == null) { return; } data = Math.sin(data); StaticVal retVal = new StaticVal(Value_t.REAL, data); ((FunctionEnv) env).setReturnVal(retVal); } private static boolean checkArgumentsNum(LibraryFunction_t func, Environment env) { if (func.equals(LibraryFunction_t.PRINT) || func.equals(LibraryFunction_t.PRINT_LN)) { return true; } else { if (env.totalActuals() != func.totalArgs()) { String msg = "Call to this lib function " + "requires (" + func.totalArgs() + ") arguments BUT (" + env.totalActuals() + ") found."; StaticVal retVal = new StaticVal(Value_t.ERROR, msg); ((FunctionEnv) env).setReturnVal(retVal); return false; } else { return true; } } } private static Double getDoubleArgument(Environment env) { double data; Value value = env.getActualArgument(LIBRARY_FUNC_ARG + 0); if (value.isReal()) { data = (double) value.getData(); } else if (value.isInteger()) { data = (double) (int) value.getData(); } else if (value.isString() && value.isConvertedToNumeric()) { data = Double.parseDouble((String) value.getData()); } else if (value.isUndefined()) { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument is UNDEFINED."); ((FunctionEnv) env).setReturnVal(retVal); return null; } else { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument can not cast to Double."); ((FunctionEnv) env).setReturnVal(retVal); return null; } return data; } private static AFoxDataStructure getObjectArgument(Environment env) { Value value = env.getActualArgument(LIBRARY_FUNC_ARG + 0); if (!value.isObject() && !value.isTable()) { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument must be of type Array or Object."); ((FunctionEnv) env).setReturnVal(retVal); return null; } AFoxDataStructure fdataStructure = (AFoxDataStructure) value.getData(); return fdataStructure; } private static FunctionDef getFunctionArgument(Environment env) { Value value = env.getActualArgument(LIBRARY_FUNC_ARG + 0); if (!value.isUserFunction()) { StaticVal retVal = new StaticVal(Value_t.ERROR, "Argument must be a user function."); ((FunctionEnv) env).setReturnVal(retVal); return null; } FunctionDef funcdef = (FunctionDef) value.getData(); return funcdef; } }
package ActiveMQ; import java.util.Map; import java.util.Timer; import java.util.Map.Entry; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import plugincore.PluginEngine; import shared.MsgEvent; public class ActiveProducer { public Map<String,ActiveProducerWorker> producerWorkers; private String URI; private Timer timer; class ClearProducerTask extends TimerTask { public void run() { for (Entry<String, ActiveProducerWorker> entry : producerWorkers.entrySet()) { System.out.println("Cleanup: " + entry.getKey() + "/" + entry.getValue()); ActiveProducerWorker apw = entry.getValue(); if(apw.isActive) { apw.isActive = false; producerWorkers.put(entry.getKey(),apw); } else { if(apw.shutdown()) { producerWorkers.remove(entry.getKey()); } } } } } public ActiveProducer(String URI) { try { producerWorkers = new ConcurrentHashMap<String,ActiveProducerWorker>(); this.URI = URI; timer = new Timer(); timer.scheduleAtFixedRate(new ClearProducerTask(), 5000, 5000);//start at 5000 end at 5000 } catch(Exception ex) { ex.printStackTrace(); System.out.println("ActiveProducer Init " + ex.toString()); } } public boolean sendMessage(MsgEvent sm) { boolean isSent = false; try { String agentPath = sm.getMsgRegion() + "_" + sm.getMsgAgent(); ActiveProducerWorker apw = null; if(producerWorkers.containsKey(agentPath)) { if(PluginEngine.isReachableAgent(agentPath)) { apw = producerWorkers.get(agentPath); } else { System.out.println(agentPath + " is unreachable..."); } } else { if (PluginEngine.isReachableAgent(agentPath)) { apw = new ActiveProducerWorker(agentPath, URI); } else { System.out.println(agentPath + " is unreachable..."); } } if(apw != null) { apw.sendMessage(sm); isSent = true; } else { System.out.println("apw is null"); } } catch(Exception ex) { System.out.println("ActiveProducer : sendMessage Error " + ex.toString()); } return isSent; } }
package biweekly.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a UTC offset. * @author Michael Angstadt */ public final class UtcOffset { private final int hour; private final int minute; /** * Creates a new UTC offset. * @param hour the hour component (may be negative) * @param minute the minute component (must be between 0 and 59) */ public UtcOffset(int hour, int minute) { this.hour = hour; this.minute = minute; } public static UtcOffset parse(String text) { Pattern timeZoneRegex = Pattern.compile("^([-\\+])?(\\d{1,2})(:?(\\d{2}))?$"); Matcher m = timeZoneRegex.matcher(text); if (!m.find()) { throw new IllegalArgumentException("Offset string is not in ISO8610 format: " + text); } String sign = m.group(1); boolean positive; if ("-".equals(sign)) { positive = false; } else { positive = true; } String hourStr = m.group(2); int hourOffset = Integer.parseInt(hourStr); if (!positive) { hourOffset *= -1; } String minuteStr = m.group(4); int minuteOffset = (minuteStr == null) ? 0 : Integer.parseInt(minuteStr); return new UtcOffset(hourOffset, minuteOffset); } /** * Gets the hour component. * @return the hour component */ public int getHour() { return hour; } /** * Gets the minute component. * @return the minute component */ public int getMinute() { return minute; } /** * Converts this offset to its ISO string representation using "basic" * format. * @return the ISO string representation (e.g. "-0500") */ @Override public String toString() { return toString(false); } /** * Converts this offset to its ISO string representation. * @param extended true to use extended format (e.g. "-05:00"), false to use * basic format (e.g. "-0500") * @return the ISO string representation */ public String toString(boolean extended) { StringBuilder sb = new StringBuilder(); boolean positive = hour >= 0; sb.append(positive ? '+' : '-'); int hour = Math.abs(this.hour); if (hour < 10) { sb.append('0'); } sb.append(hour); if (extended) { sb.append(':'); } if (minute < 10) { sb.append('0'); } sb.append(minute); return sb.toString(); } /** * Converts the offset to milliseconds. * @return the offset in milliseconds. */ public long toMillis() { return (hour * 60 + minute) * 60 * 1000; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hour; result = prime * result + minute; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UtcOffset other = (UtcOffset) obj; if (hour != other.hour) return false; if (minute != other.minute) return false; return true; } }
package com.akiban.util; import com.akiban.server.error.InvalidParameterValueException; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.JarURLConnection; import java.net.URL; import java.util.*; import java.util.Map.Entry; import java.util.jar.JarEntry; /** * String utils. */ public abstract class Strings { public static String NL = nl(); private static final int BASE_CHAR = 10 -'a'; private static final Set<Character> LEGAL_HEX = new HashSet<Character>(); static { for (char ch = 'a'; ch <= 'f'; ++ch) LEGAL_HEX.add(ch); for (char ch = '0'; ch <= '9'; ++ch) LEGAL_HEX.add(ch); } /** * Gets the system <tt>line.separator</tt> newline. * @return <tt>System.getProperty("line.separator")</tt> */ public static String nl() { String nl = System.getProperty("line.separator"); if (nl == null) { throw new NullPointerException("couldn't find system property line.separator"); } return nl; } /** * Joins the given Strings into a single, newline-delimited String. Newline is the system-dependent one as * defined by the system property <tt>line.separator</tt>. * @param strings the strings * @return the String */ public static String join(Collection<?> strings) { return join(strings, nl()); } /** * Joins the given Strings into a single, newline-delimited String. Newline is the system-dependent one as * defined by the system property <tt>line.separator</tt>. * @param strings the strings * @return the String */ public static String join(Object... strings) { return join(Arrays.asList(strings)); } /** * Joins the given Strings into a single String with the given delimiter. The last String in the list will * not have the delimiter appended. If the list is empty, this returns an empty string. * @param strings a list of strings. May not be null. * @param delimiter the delimiter between strings; this will be inserted <tt>(strings.size() - 1)</tt> times. * May not be null. * @return the joined string */ public static String join(Collection<?> strings, String delimiter) { if (strings.size() == 0) { return ""; } StringBuilder builder = new StringBuilder(30 * strings.size()); // rough guess for capacity! for (Object string : strings) { builder.append(string).append(delimiter); } builder.setLength(builder.length() - delimiter.length()); return builder.toString(); } public static List<String> stringAndSort(Collection<?> inputs) { List<String> results = new ArrayList<String>(inputs.size()); for (Object item : inputs) { String asString = stringAndSort(item); results.add(asString); } Collections.sort(results); return results; } public static List<String> stringAndSort(Map<?,?> inputs) { // step 1: get the key-value pairs into a multimap. We need a multimap because multiple keys may have the // same toString. For instance, { 1 : "int", 1L : "long" } would become a multimap { "1" : ["int", "long"] } Multimap<String,String> multiMap = ArrayListMultimap.create(); for (Map.Entry<?,?> inputEntry : inputs.entrySet()) { String keyString = stringAndSort(inputEntry.getKey()); String valueString = stringAndSort(inputEntry.getValue()); multiMap.put(keyString, valueString); } // step 2: Flatten the multimap into a Map<String,String>, sorting by keys as you go. Map<String,String> sortedAndFlattened = new TreeMap<String,String>(); for (Entry<String,Collection<String>> multiMapEntry : multiMap.asMap().entrySet()) { String keyString = multiMapEntry.getKey(); String valueString = stringAndSort(multiMapEntry.getValue()).toString(); String duplicate = sortedAndFlattened.put(keyString, valueString); assert duplicate == null : duplicate; } // step 3: Flatten the map into a List<String> List<String> results = new ArrayList<String>(inputs.size()); for (Entry<String,String> entry : sortedAndFlattened.entrySet()) { results.add(entry.toString()); } return results; } private static String stringAndSort(Object item) { if (item instanceof Collection) { return stringAndSort((Collection<?>)item).toString(); } else if (item instanceof Map) { return stringAndSort((Map<?,?>)item).toString(); } else { return String.valueOf(item); } } /** * Dumps the content of a resource into a List<String>, where each element is one line of the resource. * @param forClass the class whose resource we should get; if null, will get the default * <tt>ClassLoader.getSystemResourceAsStream</tt>. * @param path the name of the resource * @return a list of lines in the resource * @throws IOException if the given resource doesn't exist or can't be properly read */ public static List<String> dumpResource(Class<?> forClass, String path) throws IOException { InputStream is = (forClass == null) ? ClassLoader.getSystemResourceAsStream(path) : forClass.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("For class " + forClass + ": " + path); } return readStream(is); } public static List<String> dumpURLs(Enumeration<URL> urls) throws IOException { List<String> result = new ArrayList<String>(); while (urls.hasMoreElements()) { URL next = urls.nextElement(); LOG.debug("reading URL: {}", next); boolean readAsStream = true; if ("jar".equals(next.getProtocol())) { JarURLConnection connection = (JarURLConnection)next.openConnection(); if (connection.getJarEntry().isDirectory()) { readJarConnectionTo(connection, result); readAsStream = false; } } if (readAsStream) { InputStream is = next.openStream(); readStreamTo(is, result); } } return result; } @SuppressWarnings("unused") // primarily useful in debuggers public static String[] dumpException(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); t.printStackTrace(printWriter); printWriter.flush(); stringWriter.flush(); return stringWriter.toString().split("\\n"); } public static String hex(byte[] bytes, int start, int length) { ArgumentValidation.isGTE("start", start, 0); ArgumentValidation.isGTE("length", length, 0); StringBuilder sb = new StringBuilder("0x"); Formatter formatter = new Formatter(sb, Locale.US); for (int i=start; i < start+length; ++i) { formatter.format("%02X", bytes[i]); if ((i-start) % 2 == 1) { sb.append(' '); } } return sb.toString().trim(); } public static String hex(ByteSource byteSource) { return hex(byteSource.byteArray(), byteSource.byteArrayOffset(), byteSource.byteArrayLength()); } /** * @param c: character * @return the HEX value of this char * @throws InvalidParameterValueException if c is not a valid hex digit * * Eg., 'a' would return 10 */ private static int getHex (char c) { if (!LEGAL_HEX.contains(c |= 32)) throw new InvalidParameterValueException("Invalid HEX digit: " + c); return c > 'a' ? c + BASE_CHAR : c - '0'; } private static byte getByte (char highChar, char lowChar) { return (byte)((getHex(highChar) << 4) + getHex(lowChar)); } public static ByteSource parseHexWithout0x (String st) { double quotient = st.length() / 2.0; byte ret[] = new byte[(int)Math.ceil(quotient)]; int stIndex = 0, retIndex = 0; // if all the chars in st can be evenly divided into pairs if (ret.length == (int)quotient) // two first hex digits make a byte ret[retIndex++] = getByte(st.charAt(stIndex), st.charAt(++stIndex)); else // if not // only the first one does ret[retIndex++] = (byte)getHex(st.charAt(stIndex)); // starting from here, all characters should be evenly divided into pair for (; retIndex < ret.length; ++retIndex) ret[retIndex] = getByte(st.charAt(++stIndex), st.charAt(++stIndex)); return new WrappingByteSource(ret); } public static ByteSource parseHex(String string) { if (!string.startsWith("0x")) { throw new RuntimeException("not a hex string"); } byte[] ret = new byte[ (string.length()-2) / 2 ]; int resultIndex = 0; for (int strIndex=2; strIndex < string.length(); ++strIndex) { final char strChar = string.charAt(strIndex); if (!Character.isWhitespace(strChar)) { int high = (Character.digit(strChar, 16)) << 4; char lowChar = string.charAt(++strIndex); int low = (Character.digit(lowChar, 16)); ret[resultIndex++] = (byte) (low + high); } } return new WrappingByteSource().wrap(ret, 0, resultIndex); } private static List<String> readStream(InputStream is) throws IOException { List<String> result = new ArrayList<String>(); readStreamTo(is, result); return result; } private static void readStreamTo(InputStream is, List<String> outList) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line=reader.readLine()) != null) { outList.add(line); } } finally { is.close(); } } private static void readJarConnectionTo(JarURLConnection connection, List<String> result) throws IOException { assert connection.getJarEntry().isDirectory() : "not a dir: " + connection.getJarEntry(); // put into entries only the children of the connection's entry, and trim off the entry prefix String base = connection.getEntryName(); Enumeration<JarEntry> enumeration = connection.getJarFile().entries(); while (enumeration.hasMoreElements()) { JarEntry entry = enumeration.nextElement(); if (entry.getName().startsWith(base)) result.add(entry.getName().substring(base.length())); } } public static <T> String toString(Multimap<T,?> map) { StringBuilder sb = new StringBuilder(); for (Iterator<T> keysIter = map.keySet().iterator(); keysIter.hasNext(); ) { T key = keysIter.next(); sb.append(key).append(" => "); for (Iterator<?> valsIter = map.get(key).iterator(); valsIter.hasNext(); ) { sb.append(valsIter.next()); if (valsIter.hasNext()) sb.append(", "); } if (keysIter.hasNext()) sb.append(nl()); } return sb.toString(); } public static String stripr(String input, String suffix) { if (input == null || suffix == null) return input; return input.endsWith(suffix) ? input.substring(0, input.length() - suffix.length()) : input; } private static final Logger LOG = LoggerFactory.getLogger(Strings.class); public static List<String> dumpFile(File file) throws IOException { List<String> results = new ArrayList<String>(); FileReader reader = new FileReader(file); try { BufferedReader buffered = new BufferedReader(reader); for (String line; (line=buffered.readLine()) != null; ) { results.add(line); } } finally { reader.close(); } return results; } public static List<String> mapToString(Collection<?> collection) { // are lambdas here yet?! List<String> strings = new ArrayList<String>(collection.size()); for (Object o : collection) strings.add(String.valueOf(o)); return strings; } }
package com.hearthsim.card; import com.hearthsim.card.minion.Hero; import com.hearthsim.card.minion.Minion; import com.hearthsim.card.spellcard.SpellCard; import com.hearthsim.card.spellcard.SpellRandomInterface; import com.hearthsim.event.CharacterFilter; import com.hearthsim.event.deathrattle.DeathrattleAction; import com.hearthsim.event.effect.CardEffectOnResolveAoeInterface; import com.hearthsim.event.effect.CardEffectCharacter; import com.hearthsim.event.effect.CardEffectOnResolveRandomCharacterInterface; import com.hearthsim.event.effect.CardEffectOnResolveTargetableInterface; import com.hearthsim.exception.HSException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.DeepCopyable; import com.hearthsim.util.HearthAction; import com.hearthsim.util.HearthAction.Verb; import com.hearthsim.util.factory.BoardStateFactoryBase; import com.hearthsim.util.tree.HearthTreeNode; import com.hearthsim.util.tree.RandomEffectNode; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; public class Card implements DeepCopyable<Card> { protected final Logger log = LoggerFactory.getLogger(getClass()); /** * Name of the card */ protected String name_ = ""; /** * Mana cost of the card */ protected byte baseManaCost; protected boolean hasBeenUsed; protected boolean isInHand_; /** * Overload handling */ private byte overload; protected DeathrattleAction deathrattleAction_; /** * Constructor * * @param name Name of the card * @param baseManaCost Base mana cost of the card * @param hasBeenUsed Has the card been used? * @param isInHand Is the card in your hand? */ public Card() { ImplementedCardList cardList = ImplementedCardList.getInstance(); ImplementedCardList.ImplementedCard implementedCard = cardList.getCardForClass(this.getClass()); this.initFromImplementedCard(implementedCard); } protected void initFromImplementedCard(ImplementedCardList.ImplementedCard implementedCard) { if (implementedCard != null) { this.name_ = implementedCard.name_; this.baseManaCost = (byte) implementedCard.mana_; this.overload = (byte) implementedCard.overload; } this.hasBeenUsed = false; this.isInHand_ = true; } /** * Get the name of the card * * @return Name of the card */ public String getName() { return name_; } /** * Set the name of the card */ public void setName(String value) { name_ = value; } /** * Get the mana cost of the card * * @param side The PlayerSide of the card for which you want the mana cost * @param board The BoardModel representing the current board state * * @return Mana cost of the card */ public byte getManaCost(PlayerSide side, BoardModel board) { return baseManaCost; } /** * Set the mana cost of the card * * @param mana The new mana cost */ public void setBaseManaCost(byte mana) { this.baseManaCost = mana; } /** * Get the base mana cost of the card * * @return Mana cost of the card */ public byte getBaseManaCost() { return baseManaCost; } /** * Returns whether the card has been used or not * * @return */ public boolean hasBeenUsed() { return hasBeenUsed; } /** * Sets whether the card has been used or not * * @param value The new hasBeenUsed value */ public void hasBeenUsed(boolean value) { hasBeenUsed = value; } public void isInHand(boolean value) { isInHand_ = value; } protected boolean isInHand() { return isInHand_; } // This deepCopy pattern is required because we use the class of each card to recreate it under certain circumstances @Override public Card deepCopy() { Card copy = null; try { copy = getClass().newInstance(); } catch(InstantiationException e) { log.error("instantiation error", e); } catch(IllegalAccessException e) { log.error("illegal access error", e); } if (copy == null) { throw new RuntimeException("unable to instantiate card."); } copy.name_ = this.name_; copy.baseManaCost = this.baseManaCost; copy.hasBeenUsed = this.hasBeenUsed; copy.isInHand_ = this.isInHand_; copy.overload = this.overload; return copy; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (this.getClass() != other.getClass()) { return false; } // More logic here to be discuss below... if (baseManaCost != ((Card)other).baseManaCost) return false; if (hasBeenUsed != ((Card)other).hasBeenUsed) return false; if (isInHand_ != ((Card)other).isInHand_) return false; if (!name_.equals(((Card)other).name_)) return false; if (overload != ((Card)other).overload) return false; return true; } @Override public int hashCode() { int result = name_ != null ? name_.hashCode() : 0; result = 31 * result + baseManaCost; result = 31 * result + overload; result = 31 * result + (hasBeenUsed ? 1 : 0); result = 31 * result + (isInHand_ ? 1 : 0); return result; } /** * Returns whether this card can be used on the given target or not * * This function is an optional optimization feature. Some cards in Hearthstone have limited targets; Shadow Bolt cannot be used on heroes, Mind Blast can only target enemy heroes, etc. Even in this situation though, BoardStateFactory * will still try to play non- sensical moves because it doesn't know that such moves are invalid until it tries to play them. The problem is, the BoardStateFactory has to go and make a deep copy of the current BoardState before it can * go and try to play the invalid move, and it turns out that 98% of execution time in HearthSim is BoardStateFactory calling BoardState.deepCopy(). By overriding this function and returning false on appropriate occasions, we can save * some calls to deepCopy and get better performance out of the code. * * By default, this function only checks mana cost. * * @param playerSide * @param boardModel * @return */ public boolean canBeUsedOn(PlayerSide playerSide, Minion minion, BoardModel boardModel) { if (!(this.getManaCost(PlayerSide.CURRENT_PLAYER, boardModel) <= boardModel.getCurrentPlayer().getMana())) { return false; } if (this instanceof CardEffectOnResolveTargetableInterface) { if(!((CardEffectOnResolveTargetableInterface)this).getTargetableFilter().targetMatches(PlayerSide.CURRENT_PLAYER, this, playerSide, minion, boardModel)) { return false; } } else if (this instanceof SpellCard) { // TODO ignore minion cards for now if (playerSide != PlayerSide.CURRENT_PLAYER || !minion.isHero()) { return false; } } return true; } public boolean canBeUsedOn(PlayerSide playerSide, int targetIndex, BoardModel boardModel) { Minion targetMinion = boardModel.modelForSide(playerSide).getCharacter(targetIndex); return this.canBeUsedOn(playerSide, targetMinion, boardModel); } public final HearthTreeNode useOn(PlayerSide side, Minion targetMinion, HearthTreeNode boardState) throws HSException { return this.useOn(side, targetMinion, boardState, false); } public HearthTreeNode useOn(PlayerSide side, int targetIndex, HearthTreeNode boardState) throws HSException { return this.useOn(side, targetIndex, boardState, false); } public HearthTreeNode useOn(PlayerSide side, int targetIndex, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { Minion target = boardState.data_.modelForSide(side).getCharacter(targetIndex); return this.useOn(side, target, boardState, singleRealizationOnly); } /** * Use the card on the given target * * @param side * @param targetMinion The target minion (can be a Hero) * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @param singleRealizationOnly For cards with random effects, setting this to true will return only a single realization of the random event. * * @return The boardState is manipulated and returned */ private HearthTreeNode useOn(PlayerSide side, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { if (!this.canBeUsedOn(side, targetMinion, boardState.data_)) return null; PlayerModel currentPlayer = boardState.data_.getCurrentPlayer(); PlayerModel targetPlayer = boardState.data_.modelForSide(side); // Need to record card and target index *before* the board state changes int cardIndex = currentPlayer.getHand().indexOf(this); int targetIndex = targetMinion instanceof Hero ? 0 : targetPlayer.getMinions() .indexOf(targetMinion) + 1; currentPlayer.addNumCardsUsed((byte)1); HearthTreeNode toRet = this.notifyCardPlayBegin(boardState, singleRealizationOnly); if (toRet != null) { toRet = this.use_core(side, targetMinion, toRet, singleRealizationOnly); } if (toRet != null) { // we need to resolve each RNG child separately if (toRet instanceof RandomEffectNode && toRet.numChildren() > 0) { for (HearthTreeNode child : toRet.getChildren()) { this.resolveCardPlayedAndNotify(child, singleRealizationOnly); // TODO deal with null return } } else { toRet = this.resolveCardPlayedAndNotify(toRet, singleRealizationOnly); } } if (toRet != null) { toRet.setAction(new HearthAction(Verb.USE_CARD, PlayerSide.CURRENT_PLAYER, cardIndex, side, targetIndex)); } return toRet; } private HearthTreeNode resolveCardPlayedAndNotify(HearthTreeNode boardState, boolean singleRealizationOnly) { if (boardState != null && this.triggersOverload()) { boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).addOverload(this.getOverload()); } if (boardState != null) { boardState = this.notifyCardPlayResolve(boardState, singleRealizationOnly); } return boardState; } /** * Use the card on the given target * <p> * This is the core implementation of card's ability * * @param side * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * @return The boardState is manipulated and returned */ protected HearthTreeNode use_core( PlayerSide side, Minion targetMinion, HearthTreeNode boardState, boolean singleRealizationOnly) throws HSException { HearthTreeNode toRet = boardState; int originIndex = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getHand().indexOf(this); int targetIndex = boardState.data_.modelForSide(side).getIndexForCharacter(targetMinion); CardEffectCharacter targetableEffect = null; if (this instanceof CardEffectOnResolveTargetableInterface) { targetableEffect = ((CardEffectOnResolveTargetableInterface) this).getTargetableEffect(); } // TODO this is to workaround using super.use_core since we no longer have an accurate reference to the origin card (specifically, Soulfire messes things up) byte manaCost = this.getManaCost(PlayerSide.CURRENT_PLAYER, boardState.data_); Collection<HearthTreeNode> rngChildren = null; // different interfaces have different usage patterns // TODO right now these don't stack well with each other if (this instanceof SpellRandomInterface) { rngChildren = ((SpellRandomInterface) this).createChildren(PlayerSide.CURRENT_PLAYER, originIndex, toRet); } else if (this instanceof CardEffectOnResolveRandomCharacterInterface) { CardEffectOnResolveRandomCharacterInterface that = (CardEffectOnResolveRandomCharacterInterface) this; rngChildren = this.effectRandomCharacterUsingFilter(that.getRandomTargetEffect(), that.getRandomTargetFilter(), toRet); } else if (this instanceof CardEffectOnResolveAoeInterface) { toRet = this.effectAllUsingFilter(((CardEffectOnResolveAoeInterface) this).getAoeEffect(), ((CardEffectOnResolveAoeInterface) this).getAoeFilter(), toRet); } if (toRet == null) { return null; } if (rngChildren != null) { toRet = new RandomEffectNode(toRet, new HearthAction(HearthAction.Verb.USE_CARD, side, 0, side, 0)); switch (rngChildren.size()) { case 0: toRet = null; // no valid targets; this is an invalid action break; case 1: toRet = rngChildren.stream().findAny().get(); // if only one RNG child, just use it toRet.data_.modelForSide(PlayerSide.CURRENT_PLAYER).subtractMana(manaCost); if (targetableEffect != null) { toRet = targetableEffect.applyEffect(PlayerSide.CURRENT_PLAYER, null, side, targetIndex, toRet); } break; default: // more than 1 // create an RNG "base" that is untouched. This allows us to recreate the RNG children during history traversal. toRet = new RandomEffectNode(toRet, new HearthAction(HearthAction.Verb.USE_CARD, side, 0, side, 0)); // for each child, apply the effect and mana cost. we want to do as much as we can with the non-random effect portion (e.g., the damage part of Soulfire) for (HearthTreeNode child : rngChildren) { if (targetableEffect != null) { child = targetableEffect.applyEffect(PlayerSide.CURRENT_PLAYER, null, side, targetIndex, child); } child.data_.modelForSide(PlayerSide.CURRENT_PLAYER).subtractMana(manaCost); toRet.addChild(child); } } } else { if (targetableEffect != null) { toRet = targetableEffect.applyEffect(PlayerSide.CURRENT_PLAYER, this, side, targetMinion, toRet); } if (toRet != null) { // apply standard card played effects PlayerModel currentPlayer = toRet.data_.getCurrentPlayer(); toRet.data_.modelForSide(PlayerSide.CURRENT_PLAYER).subtractMana(manaCost); currentPlayer.getHand().remove(this); } } return toRet; } // Various notifications private HearthTreeNode notifyCardPlayBegin(HearthTreeNode boardState, boolean singleRealizationOnly) { PlayerModel currentPlayer = boardState.data_.getCurrentPlayer(); PlayerModel waitingPlayer = boardState.data_.getWaitingPlayer(); HearthTreeNode toRet = boardState; ArrayList<CardPlayBeginInterface> matches = new ArrayList<>(); for (Card card : currentPlayer.getHand()) { if (card instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)card); } } Card hero = currentPlayer.getHero(); if (hero instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)hero); } for (Minion minion : currentPlayer.getMinions()) { if (!minion.isSilenced() && minion instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)minion); } } for (CardPlayBeginInterface match : matches) { toRet = match.onCardPlayBegin(PlayerSide.CURRENT_PLAYER, PlayerSide.CURRENT_PLAYER, this, toRet, singleRealizationOnly); } matches.clear(); for (Card card : waitingPlayer.getHand()) { if (card instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)card); } } hero = waitingPlayer.getHero(); if (hero instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)hero); } for (Minion minion : waitingPlayer.getMinions()) { if (!minion.isSilenced() && minion instanceof CardPlayBeginInterface) { matches.add((CardPlayBeginInterface)minion); } } for (CardPlayBeginInterface match : matches) { toRet = match.onCardPlayBegin(PlayerSide.WAITING_PLAYER, PlayerSide.CURRENT_PLAYER, this, toRet, singleRealizationOnly); } // check for and remove dead minions toRet = BoardStateFactoryBase.handleDeadMinions(toRet, singleRealizationOnly); return toRet; } private HearthTreeNode notifyCardPlayResolve(HearthTreeNode boardState, boolean singleRealizationOnly) { PlayerModel currentPlayer = boardState.data_.getCurrentPlayer(); PlayerModel waitingPlayer = boardState.data_.getWaitingPlayer(); HearthTreeNode toRet = boardState; ArrayList<CardPlayAfterInterface> matches = new ArrayList<>(); for (Card card : currentPlayer.getHand()) { if (card instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)card); } } Card hero = currentPlayer.getHero(); if (hero instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)hero); } for (Minion minion : currentPlayer.getMinions()) { if (!minion.isSilenced() && minion instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)minion); } } for (CardPlayAfterInterface match : matches) { toRet = match.onCardPlayResolve(PlayerSide.CURRENT_PLAYER, PlayerSide.CURRENT_PLAYER, this, toRet, singleRealizationOnly); } matches.clear(); for (Card card : waitingPlayer.getHand()) { if (card instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)card); } } hero = waitingPlayer.getHero(); if (hero instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)hero); } for (Minion minion : waitingPlayer.getMinions()) { if (!minion.isSilenced() && minion instanceof CardPlayAfterInterface) { matches.add((CardPlayAfterInterface)minion); } } for (CardPlayAfterInterface match : matches) { toRet = match.onCardPlayResolve(PlayerSide.WAITING_PLAYER, PlayerSide.CURRENT_PLAYER, this, toRet, singleRealizationOnly); } // check for and remove dead minions toRet = BoardStateFactoryBase.handleDeadMinions(toRet, singleRealizationOnly); return toRet; } protected HearthTreeNode effectAllUsingFilter(CardEffectCharacter effect, CharacterFilter filter, HearthTreeNode boardState) { if (boardState != null && filter != null) { for (BoardModel.CharacterLocation location : boardState.data_) { Minion character = boardState.data_.getCharacter(location); if (filter.targetMatches(PlayerSide.CURRENT_PLAYER, this, location.getPlayerSide(), character, boardState.data_)) { boardState = effect.applyEffect(PlayerSide.CURRENT_PLAYER, this, location.getPlayerSide(), character, boardState); } } } return boardState; } protected Collection<HearthTreeNode> effectRandomCharacterUsingFilter(CardEffectCharacter effect, CharacterFilter filter, HearthTreeNode boardState) { int originIndex = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getHand().indexOf(this); ArrayList<HearthTreeNode> children = new ArrayList<>(); for (BoardModel.CharacterLocation location : boardState.data_) { if (filter.targetMatches(PlayerSide.CURRENT_PLAYER, this, location.getPlayerSide(), location.getIndex(), boardState.data_)) { HearthTreeNode newState = new HearthTreeNode(boardState.data_.deepCopy()); Card origin = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getHand().get(originIndex); effect.applyEffect(PlayerSide.CURRENT_PLAYER, origin, location.getPlayerSide(), location.getIndex(), newState); newState.data_.modelForSide(PlayerSide.CURRENT_PLAYER).getHand().remove(originIndex); children.add(newState); } } return children; } public JSONObject toJSON() { JSONObject json = new JSONObject(); json.put("name", name_); json.put("mana", baseManaCost); if (hasBeenUsed) json.put("hasBeenUsed", hasBeenUsed); return json; } @Override public String toString() { return this.toJSON().toString(); } protected boolean isWaitingPlayer(PlayerSide side) { return PlayerSide.WAITING_PLAYER == side; } @Deprecated protected boolean isNotHero(Minion targetMinion) { return !isHero(targetMinion); } protected boolean isCurrentPlayer(PlayerSide side) { return PlayerSide.CURRENT_PLAYER == side; } protected byte getOverload() { return overload; } public void setOverload(byte value) { overload = value; } public boolean triggersOverload() { return overload > 0; } public boolean hasDeathrattle() { return deathrattleAction_ != null; } public DeathrattleAction getDeathrattle() { return deathrattleAction_; } public void setDeathrattle(DeathrattleAction action) { deathrattleAction_ = action; } @Deprecated public Card(String name, byte baseManaCost, boolean hasBeenUsed, boolean isInHand, byte overload) { this.baseManaCost = baseManaCost; this.hasBeenUsed = hasBeenUsed; isInHand_ = isInHand; name_ = name; this.overload = overload; } @Deprecated public Card(byte baseManaCost, boolean hasBeenUsed, boolean isInHand) { ImplementedCardList cardList = ImplementedCardList.getInstance(); ImplementedCardList.ImplementedCard implementedCard = cardList.getCardForClass(this.getClass()); name_ = implementedCard.name_; this.baseManaCost = baseManaCost; this.hasBeenUsed = hasBeenUsed; isInHand_ = isInHand; this.overload = (byte) implementedCard.overload; } @Deprecated public final HearthTreeNode useOn(PlayerSide side, Minion targetMinion, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.useOn(side, targetMinion, boardState, false); } @Deprecated public HearthTreeNode useOn(PlayerSide side, int targetIndex, HearthTreeNode boardState, Deck deckPlayer0, Deck deckPlayer1) throws HSException { return this.useOn(side, targetIndex, boardState, false); } @Deprecated protected boolean isHero(Minion targetMinion) { return targetMinion instanceof Hero; } }
package com.jaamsim.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.SpinnerNumberModel; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileNameExtensionFilter; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.basicsim.Simulation; import com.jaamsim.controllers.RateLimiter; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.EventErrorListener; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.Parser; import com.jaamsim.math.Vec3d; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends JFrame implements EventTimeListener, EventErrorListener { private static GUIFrame instance; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu viewMenu; private JMenu windowMenu; private JMenu windowList; private JMenu optionMenu; private JMenu helpMenu; private JCheckBoxMenuItem showPosition; private static JCheckBoxMenuItem xyzAxis; private static JCheckBoxMenuItem grid; private JCheckBoxMenuItem alwaysTop; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JToggleButton controlRealTime; private JSpinner spinner; private RoundToggleButton controlStartResume; private JToggleButton controlStop; private JTextField pauseTime; private JLabel locatorPos; private JLabel locatorLabel; JButton toolButtonIsometric; JButton toolButtonXYPlane; private int lastValue = -1; private JProgressBar progressBar; private static Image iconImage; private static final RateLimiter rateLimiter; private static boolean SAFE_GRAPHICS; // Collection of default window parameters public static int DEFAULT_GUI_WIDTH = 1160; public static int COL1_WIDTH; public static int COL2_WIDTH; public static int COL3_WIDTH; public static int COL1_START; public static int COL2_START; public static int COL3_START; public static int HALF_TOP; public static int HALF_BOTTOM; public static int TOP_START; public static int BOTTOM_START; public static int LOWER_HEIGHT; public static int LOWER_START; public static int VIEW_HEIGHT; public static int VIEW_WIDTH; private static final String RUN_TOOLTIP = GUIFrame.formatToolTip("Run", "Starts or resumes the simulation run."); private static final String PAUSE_TOOLTIP = "<html><b>Pause</b></html>"; // Use a small tooltip for Pause so that it does not block the simulation time display static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { URL file = GUIFrame.class.getResource("/resources/images/icon.png"); iconImage = Toolkit.getDefaultToolkit().getImage(file); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); iconImage = null; } shuttingDown = new AtomicBoolean(false); rateLimiter = RateLimiter.create(60); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); this.addWindowListener(new CloseListener()); // Initialize the working environment initializeMenus(); initializeMainToolBars(); initializeStatusBar(); this.setIconImage(GUIFrame.getWindowIcon()); //Set window size and make visible pack(); setSize(DEFAULT_GUI_WIDTH, getPreferredSize().height); setResizable( false ); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); setProgress( 0 ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); } public static synchronized GUIFrame instance() { if (instance == null) instance = new GUIFrame(); return instance; } public static final RateLimiter getRateLimiter() { return rateLimiter; } /** * Listens for window events for the GUI. * */ private class CloseListener extends WindowAdapter implements ActionListener { @Override public void windowClosing(WindowEvent e) { GUIFrame.this.close(); } @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.close(); } @Override public void windowDeiconified(WindowEvent e) { // Re-open the view windows for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Re-open the tools Simulation.showActiveTools(); FrameBox.reSelectEntity(); } @Override public void windowIconified(WindowEvent e) { // Close all the tools Simulation.closeAllTools(); // Save whether each window is open or closed for (View v : View.getAll()) { v.setKeepWindowOpen(v.showWindow()); } // Close all the view windows RenderManager.clear(); } } /** * Perform exit window duties */ void close() { // check for unsaved changes if (InputAgent.isSessionEdited()) { boolean confirmed = GUIFrame.showSaveChangesDialog(); if (!confirmed) return; } InputAgent.closeLogFile(); GUIFrame.shutdown(0); } /** * Clears the simulation and user interface for a new run */ public void clear() { currentEvt.clear(); currentEvt.setTraceListener(null); // Clear the simulation Simulation.clear(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_LOADED); // Clear the title bar setTitle(Simulation.getModelName()); // Clear the status bar setProgress( 0 ); speedUpDisplay.setText(""); remainingDisplay.setText(""); locatorPos.setText( "" ); // Read the autoload configuration file InputAgent.clear(); InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); } /** * Sets up the Control Panel's menu bar. */ public void initializeMenus() { // Set up the individual menus this.initializeFileMenu(); this.initializeViewMenu(); this.initializeWindowMenu(); this.initializeOptionsMenu(); this.initializeHelpMenu(); // Add the individual menu to the main menu JMenuBar mainMenuBar = new JMenuBar(); mainMenuBar.add( fileMenu ); mainMenuBar.add( viewMenu ); mainMenuBar.add( windowMenu ); mainMenuBar.add( optionMenu ); mainMenuBar.add( helpMenu ); // Add main menu to the window setJMenuBar( mainMenuBar ); } // MENU BAR /** * Sets up the File menu in the Control Panel's menu bar. */ private void initializeFileMenu() { // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); fileMenu.setEnabled( false ); // 1) "New" menu item JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setMnemonic( 'N' ); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { boolean confirmed = GUIFrame.showSaveChangesDialog(); if (!confirmed) { return; } } clear(); InputAgent.setRecordEdits(true); InputAgent.loadDefault(); displayWindows(); FrameBox.setSelectedEntity(Simulation.getInstance()); } } ); fileMenu.add( newMenuItem ); // 2) "Open" menu item JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setMnemonic( 'O' ); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { boolean confirmed = GUIFrame.showSaveChangesDialog(); if (!confirmed) { return; } } GUIFrame.this.load(); } } ); fileMenu.add( configMenuItem ); // 3) "Save" menu item saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setMnemonic( 'S' ); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.save(); } } ); fileMenu.add( saveConfigurationMenuItem ); // 4) "Save As..." menu item JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic( 'V' ); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.saveAs(); } } ); fileMenu.add( saveConfigurationAsMenuItem ); // 5) "Import..." menu item JMenuItem importGraphicsMenuItem = new JMenuItem( "Import..." ); importGraphicsMenuItem.setMnemonic( 'I' ); importGraphicsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.importGraphics(GUIFrame.this); } } ); fileMenu.add( importGraphicsMenuItem ); // 6) "Print Input Report" menu item printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic( 'I' ); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(); } } ); fileMenu.add( printInputItem ); // 7) "Exit" menu item JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic( 'x' ); exitMenuItem.addActionListener(new CloseListener()); fileMenu.add( exitMenuItem ); } /** * Sets up the View menu in the Control Panel's menu bar. */ private void initializeViewMenu() { // View menu creation viewMenu = new JMenu( "Tools" ); viewMenu.setMnemonic( 'T' ); // 1) "Show Basic Tools" menu item JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic( 'B' ); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( showBasicToolsMenuItem ); // 2) "Close All Tools" menu item JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic( 'C' ); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<>(1); arg.add("FALSE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowPropertyViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( closeAllToolsMenuItem ); // 3) "Model Builder" menu item JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic( 'O' ); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowModelBuilder", arg, null)); } } ); viewMenu.add( objectPalletMenuItem ); // 4) "Object Selector" menu item JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic( 'S' ); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowObjectSelector", arg, null)); } } ); viewMenu.add( objectSelectorMenuItem ); // 5) "Input Editor" menu item JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic( 'I' ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowInputEditor", arg, null)); } } ); viewMenu.add( inputEditorMenuItem ); // 6) "Output Viewer" menu item JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic( 'U' ); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( outputMenuItem ); // 7) "Property Viewer" menu item JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic( 'P' ); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowPropertyViewer", arg, null)); } } ); viewMenu.add( propertiesMenuItem ); // 8) "Log Viewer" menu item JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic( 'L' ); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( logMenuItem ); } /** * Sets up the Window menu in the Control Panel's menu bar. */ private void initializeWindowMenu() { // Window menu creation windowMenu = new NewRenderWindowMenu("Views"); windowMenu.setMnemonic( 'V' ); // Initialize list of windows windowList = new WindowMenu("Select Window"); windowList.setMnemonic( 'S' ); } /** * Sets up the Options menu in the Control Panel's menu bar. */ private void initializeOptionsMenu() { optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic( 'O' ); // 1) "Show Position" check box showPosition = new JCheckBoxMenuItem( "Show Position", true ); showPosition.setMnemonic( 'P' ); optionMenu.add( showPosition ); showPosition.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { setShowPositionXY(); } } ); // 2) "Show Axes" check box xyzAxis = new JCheckBoxMenuItem( "Show Axes", true ); xyzAxis.setMnemonic( 'X' ); optionMenu.add( xyzAxis ); xyzAxis.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { DisplayEntity ent = (DisplayEntity) Entity.getNamedEntity("XYZ-Axis"); if (ent != null) { ArrayList<String> arg = new ArrayList<>(1); if (xyzAxis.isSelected()) arg.add("TRUE"); else arg.add("FALSE"); InputAgent.apply(ent, new KeywordIndex("Show", arg, null)); } } } ); // 3) "Show Grid" check box grid = new JCheckBoxMenuItem( "Show Grid", true ); grid.setMnemonic( 'G' ); optionMenu.add( grid ); grid.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { DisplayEntity ent = (DisplayEntity) Entity.getNamedEntity("XY-Grid"); if (ent != null) { ArrayList<String> arg = new ArrayList<>(1); if (grid.isSelected()) arg.add("TRUE"); else arg.add("FALSE"); InputAgent.apply(ent, new KeywordIndex("Show", arg, null)); } } } ); // 4) "Always on top" check box alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic( 'A' ); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); // 5) "Graphics Debug Info" check box graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic( 'D' ); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { RenderManager.setDebugInfo(graphicsDebug.getState()); } } ); } /** * Sets up the Help menu in the Control Panel's menu bar. */ private void initializeHelpMenu() { // Help menu creation helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); // 1) "About" menu item JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic( 'A' ); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox.instance().setVisible(true); } } ); helpMenu.add( aboutMenu ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } // TOOL BAR /** * Sets up the Control Panel's main tool bar. */ public void initializeMainToolBars() { // Insets used in setting the toolbar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initilize the main toolbar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); // 1) Run/Pause button controlStartResume = new RoundToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run-24.png"))); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-24.png"))); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStartResume.setMargin( noMargin ); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); startResume.setEnabled(false); if(startResume.isSelected()) { GUIFrame.this.startSimulation(); } else { GUIFrame.this.pauseSimulation(); } controlStartResume.grabFocus(); } } ); mainToolBar.add( controlStartResume ); // 2) Stop button controlStop = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/stop.png"))); controlStop.setToolTipText(formatToolTip("Stop", "Stops and resets the simulation run.")); controlStop.setMargin( noMargin ); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if( getSimState() == SIM_STATE_RUNNING ) { GUIFrame.this.pauseSimulation(); } boolean confirmed = GUIFrame.showConfirmStopDialog(); if (!confirmed) return; GUIFrame.this.stopSimulation(); lastSimTime = 0.0d; lastSystemTime = System.currentTimeMillis(); setSpeedUp(0.0d); } } ); int hght = controlStop.getPreferredSize().height; // Separators have 5 pixels before and after and the preferred height of controlStartResume button Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); // dimension for 5 pixels gaps Dimension gapDim = new Dimension(5, separatorDim.height); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( controlStop ); // 3) Real time button controlRealTime = new JToggleButton( " Real Time " ); controlRealTime.setToolTipText(formatToolTip("Real Time Mode", "When selected, the simulation runs at a fixed multiple of wall clock time.")); controlRealTime.setMargin( smallMargin ); controlRealTime.addActionListener(new RealTimeActionListener()); mainToolBar.addSeparator(separatorDim); mainToolBar.add( controlRealTime ); // 4) Speed Up spinner SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; dim.height = hght; spinner.setMaximumSize(dim); spinner.addChangeListener(new SpeedFactorListener()); spinner.setToolTipText(formatToolTip("Speed Multiplier (up/down key)", "Target ratio of simulation time to wall clock time when Real Time mode is selected.")); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( spinner ); // 5) Pause time label JLabel pauseAt = new JLabel( "Pause at:" ); mainToolBar.addSeparator(separatorDim); mainToolBar.add(pauseAt); // 6) Pause time value box pauseTime = new JTextField("0000-00-00T00:00:00") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.instance.setPauseTime(this.getText()); } else if (fe.getID() == FocusEvent.FOCUS_GAINED) { pauseTime.selectAll(); } super.processFocusEvent( fe ); } }; // avoid height increase for pauseTime pauseTime.setMaximumSize(pauseTime.getPreferredSize()); // avoid stretching for pauseTime when focusing in and out pauseTime.setPreferredSize(new Dimension(pauseTime.getPreferredSize().width, hght)); pauseTime.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.instance.setPauseTime(pauseTime.getText()); controlStartResume.grabFocus(); } }); pauseTime.setText(""); pauseTime.setHorizontalAlignment(JTextField.RIGHT); pauseTime.setToolTipText(formatToolTip("Pause Time", "Time at which to pause the run, e.g. 3 h, 10 s, etc.")); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add(pauseTime); // 7) View Control buttons mainToolBar.addSeparator(separatorDim); JLabel viewLabel = new JLabel( "View Control:" ); mainToolBar.add( viewLabel ); // 8) Perspective button toolButtonIsometric = new JButton( "Perspective" ); toolButtonIsometric.setMargin( smallMargin ); toolButtonIsometric.setToolTipText(formatToolTip("Perspective View", "Sets the camera position to show an oblique view of the 3D scene.")); toolButtonIsometric.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setIsometricView(); } } ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( toolButtonIsometric ); // 9) XY-Plane button toolButtonXYPlane = new JButton( "XY-Plane" ); toolButtonXYPlane.setMargin( smallMargin ); toolButtonXYPlane.setToolTipText(formatToolTip("XY-Plane View", "Sets the camera position to show a bird's eye view of the 3D scene.")); toolButtonXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setXYPlaneView(); } } ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( toolButtonXYPlane ); // Add the main tool bar to the display getContentPane().add( mainToolBar, BorderLayout.NORTH ); } // VIEW WINDOWS private static class WindowMenu extends JMenu implements MenuListener { WindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { if (!RenderManager.isGood()) { return; } ArrayList<Integer> windowIDs = RenderManager.inst().getOpenWindowIDs(); for (int id : windowIDs) { String windowName = RenderManager.inst().getWindowName(id); this.add(new WindowSelector(id, windowName)); } } } private static class WindowSelector extends JMenuItem implements ActionListener { private final int windowID; WindowSelector(int windowID, String windowName) { this.windowID = windowID; this.setText(windowName); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { return; } RenderManager.inst().focusWindow(windowID); } } private static class NewRenderWindowMenu extends JMenu implements MenuListener { NewRenderWindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuSelected(MenuEvent e) { for (View view : View.getAll()) { this.add(new NewRenderWindowLauncher(view)); } this.addSeparator(); this.add(new ViewDefiner()); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } } private static class NewRenderWindowLauncher extends JMenuItem implements ActionListener { private final View view; NewRenderWindowLauncher(View v) { view = v; this.setText(view.getName()); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(view, new KeywordIndex("ShowWindow", arg, null)); RenderManager.inst().createWindow(view); FrameBox.setSelectedEntity(view); } } private static class ViewDefiner extends JMenuItem implements ActionListener { ViewDefiner() {} { this.setText("Define new View"); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } View tmp = InputAgent.defineEntityWithUniqueName(View.class, "View", "", true); RenderManager.inst().createWindow(tmp); FrameBox.setSelectedEntity(tmp); ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(tmp, new KeywordIndex("ShowWindow", arg, null)); } } /** * Sets up the Control Panel's status bar. */ public void initializeStatusBar() { // Create the status bar JPanel statusBar = new JPanel(); statusBar.setBorder( BorderFactory.createLineBorder( Color.darkGray ) ); statusBar.setLayout( new FlowLayout( FlowLayout.LEFT, 10, 5 ) ); // Create the display clock and label JLabel clockLabel = new JLabel( "Simulation Time:" ); clockDisplay = new JLabel( "", JLabel.CENTER ); clockDisplay.setPreferredSize( new Dimension( 90, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); clockDisplay.setToolTipText(formatToolTip("Simulation Time", "The present simulation time")); statusBar.add( clockLabel ); statusBar.add( clockDisplay ); // Create the progress bar progressBar = new JProgressBar( 0, 100 ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); progressBar.setToolTipText(formatToolTip("Run Progress", "Percent of the present simulation run that has been completed.")); statusBar.add( progressBar ); // Create a remaining run time display remainingDisplay = new JLabel( "", JLabel.CENTER ); remainingDisplay.setPreferredSize( new Dimension( 90, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); remainingDisplay.setToolTipText(formatToolTip("Remaining Time", "The remaining time required to complete the present simulation run.")); statusBar.add( remainingDisplay ); // Create a speed-up factor display JLabel speedUpLabel = new JLabel( "Speed Up:" ); speedUpDisplay = new JLabel( "", JLabel.CENTER ); speedUpDisplay.setPreferredSize( new Dimension( 90, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); speedUpDisplay.setToolTipText(formatToolTip("Achieved Speedup", "The ratio of elapsed simulation time to elasped wall clock time that was achieved.")); statusBar.add( speedUpLabel ); statusBar.add( speedUpDisplay ); // Create a cursor position display locatorPos = new JLabel( "", JLabel.LEFT ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorLabel = new JLabel( "Position:" ); statusBar.add( locatorLabel ); statusBar.add( locatorPos ); // Add the status bar to the window getContentPane().add( statusBar, BorderLayout.SOUTH ); } // RUN STATUS UPDATES private long lastSystemTime = System.currentTimeMillis(); private double lastSimTime = 0.0d; private double speedUp = 0.0d; /** * Sets the values for the simulation time, run progress, speedup factor, * and remaining run time in the Control Panel's status bar. * * @param simTime - the present simulation time in seconds. */ public void setClock(double simTime) { // Set the simulation time display TimeUnit u = (TimeUnit) Unit.getPreferredUnit(TimeUnit.class); if (u == null) clockDisplay.setText(String.format("%,.2f %s", simTime, Unit.getSIUnit(TimeUnit.class))); else clockDisplay.setText(String.format("%,.2f %s", simTime/u.getConversionFactorToSI(), u.getName())); if (getSimState() != SIM_STATE_RUNNING) return; // Set the run progress bar display long cTime = System.currentTimeMillis(); double duration = Simulation.getRunDuration() + Simulation.getInitializationTime(); double timeElapsed = simTime - Simulation.getStartTime(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); // Set the speedup factor display if (cTime - lastSystemTime > 5000) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimTime = timeElapsed - lastSimTime; // Determine the speed-up factor speedUp = (elapsedSimTime * 1000.0d) / elapsedMillis; setSpeedUp(speedUp); lastSystemTime = cTime; lastSimTime = timeElapsed; } // Set the remaining time display if (speedUp > 0.0) setRemaining( (duration - timeElapsed)/speedUp ); } /** * Displays the given value on the Control Panel's progress bar. * * @param val - the percent of the run that has completed. */ public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (getSimState() >= SIM_STATE_CONFIGURED) { String title = String.format("%d%% %s - %s", val, Simulation.getModelName(), InputAgent.getRunName()); setTitle(title); } } /** * Write the given text on the Control Panel's progress bar. * * @param txt - the text to write. */ public void setProgressText( String txt ) { progressBar.setString( txt ); } /** * Write the given value on the Control Panel's speed up factor box. * * @param val - the speed up factor to write. */ public void setSpeedUp( double val ) { speedUpDisplay.setText(String.format("%,.0f", val)); } /** * Write the given value on the Control Panel's remaining run time box. * * @param val - the remaining run time in seconds. */ public void setRemaining( double val ) { if (val == 0.0) remainingDisplay.setText("-"); else if (val < 60.0) remainingDisplay.setText(String.format("%.0f seconds left", val)); else if (val < 3600.0) remainingDisplay.setText(String.format("%.1f minutes left", val/60.0)); else if (val < 3600.0*24.0) remainingDisplay.setText(String.format("%.1f hours left", val/3600.0)); else if (val < 3600.0*8760.0) remainingDisplay.setText(String.format("%.1f days left", val/(3600.0*24.0))); else remainingDisplay.setText(String.format("%.1f years left", val/(3600.0*8760.0))); } // SIMULATION CONTROLS /** * Starts or resumes the simulation run. */ public void startSimulation() { if( getSimState() <= SIM_STATE_CONFIGURED ) { if (InputAgent.isSessionEdited()) { this.saveAs(); } Simulation.start(currentEvt); } else if( getSimState() == SIM_STATE_PAUSED ) { currentEvt.resume(currentEvt.secondsToNearestTick(Simulation.getPauseTime())); } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } /** * Pauses the simulation run. */ private void pauseSimulation() { if( getSimState() == SIM_STATE_RUNNING ) currentEvt.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } /** * Stops the simulation run. */ public void stopSimulation() { if( getSimState() == SIM_STATE_RUNNING || getSimState() == SIM_STATE_PAUSED ) { currentEvt.pause(); currentEvt.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } else throw new ErrorException( "Invalid Simulation State for stop" ); } /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; private int simState; public int getSimState() { return simState; } EventManager currentEvt; public void setEventManager(EventManager e) { currentEvt = e; } /** * Sets the state of the simulation run to the given state value. * * @param state - an index that designates the state of the simulation run. */ public void updateForSimulationState(int state) { simState = state; switch( getSimState() ) { case SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( false ); controlStop.setSelected( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); showPosition.setState( true ); setShowPositionXY(); break; case SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case SIM_STATE_RUNNING: speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText(PAUSE_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } /** * updates RealTime button and Spinner */ public void updateForRealTime(boolean executeRT, int factorRT) { currentEvt.setExecuteRealTime(executeRT, factorRT); controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); if (executeRT) spinner.setEnabled(true); else spinner.setEnabled(false); } /** * updates PauseTime entry */ public void updateForPauseTime(String str) { pauseTime.setText(str); } /** * Sets the PauseTime keyword for Simulation. * @param str - value to assign. */ private void setPauseTime(String str) { Input<?> pause = Simulation.getInstance().getInput("PauseTime"); String prevVal = pause.getValueString(); if (prevVal.equals(str)) return; ArrayList<String> tokens = new ArrayList<>(); Parser.tokenize(tokens, str); // if we only got one token, and it isn't RFC8601 - add a unit if (tokens.size() == 1 && !tokens.get(0).contains(" ")) { Unit u = Unit.getPreferredUnit(TimeUnit.class); if (u == null) tokens.add(Unit.getSIUnit(TimeUnit.class)); else tokens.add(u.getName()); } try { // Parse the keyword inputs KeywordIndex kw = new KeywordIndex("PauseTime", tokens, null); InputAgent.apply(Simulation.getInstance(), kw); } catch (InputErrorException e) { pauseTime.setText(prevVal); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } public static Image getWindowIcon() { return iconImage; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public void showLocatorPosition(Vec3d pos) { // null indicates nothing to display if( pos == null ) { locatorPos.setText( " } else { if( showPosition.getState() ) { DistanceUnit u = (DistanceUnit) Unit.getPreferredUnit(DistanceUnit.class); if (u == null) { locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x, pos.y, pos.z, Unit.getSIUnit(DistanceUnit.class))); } else { double factor = u.getConversionFactorToSI(); locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x/factor, pos.y/factor, pos.z/factor, u.getName())); } } } } public void setShowPositionXY() { boolean show = showPosition.getState(); showPosition.setState( show ); locatorLabel.setVisible( show ); locatorPos.setVisible( show ); locatorLabel.setText( "Position: " ); locatorPos.setText( " } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } /** * Sets variables used to determine the position and size of various * windows based on the size of the computer display being used. */ private static void calcWindowDefaults() { Dimension guiSize = GUIFrame.instance().getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); COL1_WIDTH = 220; COL2_WIDTH = Math.min(520, (winSize.width - COL1_WIDTH) / 2); COL3_WIDTH = Math.min(420, winSize.width - COL1_WIDTH - COL2_WIDTH); COL1_START = 0; COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); TOP_START = guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_HEIGHT = (winSize.height - guiSize.height) / 3; LOWER_START = winSize.height - LOWER_HEIGHT; VIEW_WIDTH = COL2_WIDTH + COL3_WIDTH; VIEW_HEIGHT = winSize.height - TOP_START - LOWER_HEIGHT; } /** * Displays the view windows and tools on startup. */ public static void displayWindows() { // Show the view windows specified in the configuration file for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Set the initial state for the "Show Axes" and "Show Grid" check boxes DisplayEntity ent = (DisplayEntity) Entity.getNamedEntity("XYZ-Axis"); if (ent != null) xyzAxis.setSelected(ent.getShow()); ent = (DisplayEntity) Entity.getNamedEntity("XY-Grid"); if (ent != null) grid.setSelected(ent.getShow()); } // MAIN public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); EventManager evt = new EventManager("DefaultEventManager"); GUIFrame gui = GUIFrame.instance(); gui.setEventManager(evt); gui.updateForSimulationState(SIM_STATE_LOADED); evt.setTimeListener(gui); evt.setErrorListener(gui); LogBox.logLine("Simulation Environment Loaded"); if (batch) InputAgent.setBatch(true); if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // Show the Control Panel gui.setVisible(true); GUIFrame.calcWindowDefaults(); // Load the autoload file InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); gui.setTitle(Simulation.getModelName()); // Resolve all input arguments against the current working directory File user = new File(System.getProperty("user.dir")); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { //InputAgent.configure(gui, new File(configFiles.get(i))); File abs = new File((File)null, configFiles.get(i)); File loadFile; if (abs.exists()) loadFile = abs.getAbsoluteFile(); else loadFile = new File(user, configFiles.get(i)); Throwable t = gui.configure(loadFile); if (t != null) { // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } handleConfigError(t, loadFile); } } // If no configuration files were specified on the command line, then load the default configuration file if( configFiles.size() == 0 ) { InputAgent.setRecordEdits(true); InputAgent.loadDefault(); gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); } // Show the view windows if(!quiet && !batch) { displayWindows(); } // If in batch or quiet mode, close the any tools that were opened if (quiet || batch) Simulation.closeAllTools(); // Set RecordEdits mode (if it has not already been set in the configuration file) InputAgent.setRecordEdits(true); // Start the model if in batch mode if (batch) { if (InputAgent.numErrors() > 0) GUIFrame.shutdown(0); Simulation.start(evt); return; } // Wait to allow the renderer time to finish initialisation try { Thread.sleep(1000); } catch (InterruptedException e) {} // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } // Bring the Control Panel to the front (along with any open Tools) gui.toFront(); // Set the selected entity to the Simulation object FrameBox.setSelectedEntity(Simulation.getInstance()); } public static class SpeedFactorListener implements ChangeListener { @Override public void stateChanged( ChangeEvent e ) { ArrayList<String> arg = new ArrayList<>(1); arg.add(String.format("%d", ((JSpinner)e.getSource()).getValue())); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTimeFactor", arg, null)); } } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private int value; public SpinnerModel( int val, int min, int max, int stepSize) { super(val, min, max, stepSize); } @Override public Object getPreviousValue() { value = this.getNumber().intValue() / 2; // Avoid going beyond limit Integer min = (Integer)this.getMinimum(); if (min.intValue() > value) { return min; } return value; } @Override public Object getNextValue() { value = this.getNumber().intValue() * 2; // Avoid going beyond limit Integer max = (Integer)this.getMaximum(); if (max.intValue() < value) { return max; } return value; } } public static class RealTimeActionListener implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); if (((JToggleButton)event.getSource()).isSelected()) arg.add("TRUE"); else arg.add("FALSE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTime", arg, null)); } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void tickUpdate(long tick) { FrameBox.timeUpdate(tick); } @Override public void timeRunning(boolean running) { if (running) { updateForSimulationState(SIM_STATE_RUNNING); } else { updateForSimulationState(SIM_STATE_PAUSED); } } @Override public void handleError(EventManager evt, Throwable t, long currentTick) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; InputAgent.logMessage("Out of Memory use the -Xmx flag during execution for more memory"); InputAgent.logMessage("Further debug information:"); InputAgent.logMessage("Error: %s", e.getMessage()); for (StackTraceElement each : e.getStackTrace()) InputAgent.logMessage(each.toString()); GUIFrame.shutdown(1); return; } else { double curSec = evt.ticksToSeconds(currentTick); InputAgent.logMessage("EXCEPTION AT TIME: %f s", curSec); InputAgent.logMessage("Error: %s", t.getMessage()); for (StackTraceElement each : t.getStackTrace()) InputAgent.logMessage(each.toString()); } GUIFrame.showErrorDialog("Runtime Error", "JaamSim has detected the following runtime error condition:\n\n%s\n\n" + "Programmers can find more information by opening the Log Viewer.\n" + "The simulation run must be stopped before it can be restarted.", t.getMessage()); } /** * Shows the Error Message dialog box * @param title - text for the dialog box name * @param fmt - format string for the error message * @param args - inputs to the error message */ public static void showErrorDialog(String title, String fmt, Object... args) { if (InputAgent.getBatch()) GUIFrame.shutdown(1); final String msg = String.format(fmt, args); JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE); } void load() { LogBox.logLine("Loading..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); // Show the file chooser and wait for selection int returnVal = chooser.showOpenDialog(this); // Load the selected file if (returnVal == JFileChooser.APPROVE_OPTION) { File temp = chooser.getSelectedFile(); final GUIFrame gui1 = this; final File chosenfile = temp; new Thread(new Runnable() { @Override public void run() { InputAgent.setRecordEdits(false); gui1.clear(); Throwable ret = gui1.configure(chosenfile); if (ret != null) handleConfigError(ret, chosenfile); InputAgent.setRecordEdits(true); GUIFrame.displayWindows(); FrameBox.setSelectedEntity(Simulation.getInstance()); } }).start(); } } Throwable configure(File file) { InputAgent.setConfigFile(file); this.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED); Throwable ret = null; try { InputAgent.loadConfigurationFile(file); } catch (Throwable t) { ret = t; } if (ret == null) LogBox.logLine("Configuration File Loaded"); else LogBox.logLine("Configuration File Loaded - errors found"); // show the present state in the user interface this.setProgressText(null); this.setProgress(0); this.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); this.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); this.enableSave(InputAgent.getRecordEditsFound()); return ret; } static void handleConfigError(Throwable t, File file) { if (t instanceof InputErrorException) { LogBox.logLine("Input Error: " + t.getMessage()); GUIFrame.showErrorDialog("Input Error", "Input errors were detected while loading file: '%s'\n\n%s\n\n" + "Check the log file '%s' for more information.", file.getName(), t.getMessage(), InputAgent.getRunName() + ".log"); return; } LogBox.format("Fatal Error while loading file '%s': %s\n", file.getName(), t.getMessage()); GUIFrame.showErrorDialog("Fatal Error", "A fatal error has occured while loading the file '%s':\n\n%s", file.getName(), t.getMessage()); } /** * Saves the configuration file. * @param gui = Control Panel window for JaamSim * @param fileName = absolute file path and file name for the file to be saved */ private void setSaveFile(String fileName) { // Set root directory File temp = new File(fileName); // Save the configuration file InputAgent.printNewConfigurationFileWithName( fileName ); InputAgent.setConfigFile(temp); // Set the title bar to match the new run name this.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); } void save() { LogBox.logLine("Saving..."); if( InputAgent.getConfigFile() != null ) { setSaveFile(InputAgent.getConfigFile().getPath()); } else { saveAs(); } } void saveAs() { LogBox.logLine("Save As..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); chooser.setSelectedFile(InputAgent.getConfigFile()); // Show the file chooser and wait for selection int returnVal = chooser.showSaveDialog(this); // Load the selected file if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filePath = file.getPath(); // Add the file extension ".cfg" if needed filePath = filePath.trim(); if (filePath.indexOf(".") == -1) filePath = filePath.concat(".cfg"); // Confirm overwrite if file already exists File temp = new File(filePath); if (temp.exists()) { boolean confirmed = GUIFrame.showSaveAsDialog(file.getName()); if (!confirmed) { return; } } // Save the configuration file setSaveFile(filePath); } } // DIALOG BOXES /** * Shows the "Confirm Save As" dialog box * @param fileName - name of the file to be saved * @return true if the file is to be overwritten. */ public static boolean showSaveAsDialog(String fileName) { int userOption = JOptionPane.showConfirmDialog(null, String.format("The file '%s' already exists.\n" + "Do you want to replace it?", fileName), "Confirm Save As", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Confirm Stop" dialog box. * @return true if the run is to be stopped. */ public static boolean showConfirmStopDialog() { int userOption = JOptionPane.showConfirmDialog( null, "WARNING: If you stop the run, it can only be re-started from time 0.\n" + "Do you really want to stop?", "Confirm Stop", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Save Changes" dialog box * @return true for any response other than Cancel. */ public static boolean showSaveChangesDialog() { String message; if (InputAgent.getConfigFile() == null) message = "Do you want to save the changes you made?"; else message = String.format("Do you want to save the changes you made to '%s'?", InputAgent.getConfigFile().getName()); Object[] options = {"Save", "Don't Save", "Cancel"}; int userOption = JOptionPane.showOptionDialog( null, message, "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (userOption == JOptionPane.YES_OPTION) GUIFrame.instance().save(); return (userOption != JOptionPane.CANCEL_OPTION); } // TOOL TIPS public static String formatToolTip(String name, String desc) { return String.format("<html><p width=\"200px\"><b>%s</b><br>%s</p></html>", name, desc); } public static String formatKeywordToolTip(String key, String desc, String examp) { return String.format("<html><p width=\"250px\"><b>%s</b><br>%s<br><br><u>Example:</u><br>%s</p></html>", key, desc, examp); } public static String formatOutputToolTip(String key, String desc) { return String.format("<html><p width=\"250px\"><b>%s</b><br>%s</p></html>", key, desc); } }
package com.leafriend.flix; public class Flix { private Options options; public static void main(String[] args) { Options options = new Options(); new Flix(options).run(); } public Flix(Options options) { this.options = options; } public void run() { } }
package com.ppa8ball; import java.util.ArrayList; import java.util.List; import com.ppa8ball.stats.PlayerStat; import com.ppa8ball.stats.PlayersStat; import com.ppa8ball.stats.TeamStat; public class TeamRoster { public Player[] players = new Player[5]; public String name; public int number; public TeamRoster() { } public TeamRoster(TeamStat teamStat) { this(teamStat, new ArrayList<PlayerStat>()); } public TeamRoster(TeamStat teamStat, PlayersStat playersStat) { this(teamStat, playersStat.players); } public TeamRoster(TeamStat teamStat, List<PlayerStat> playerStats) { this.name = teamStat.name; this.number = teamStat.number; int i=0; for (PlayerStat playerStat : playerStats) { players[i++] = new Player(playerStat); } } public TeamRoster(TeamStat teamStat, Player [] players) { this.name = teamStat.name; this.number = teamStat.number; for (int i=players.length;i <5;i++) { players[i-1] = new Player(); } this.players = players; } }
package com.rarchives.ripme; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.swing.SwingUtilities; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.SystemUtils; import org.apache.log4j.Logger; import com.rarchives.ripme.ripper.AbstractRipper; import com.rarchives.ripme.ui.History; import com.rarchives.ripme.ui.HistoryEntry; import com.rarchives.ripme.ui.MainWindow; import com.rarchives.ripme.ui.UpdateUtils; import com.rarchives.ripme.utils.Proxy; import com.rarchives.ripme.utils.RipUtils; import com.rarchives.ripme.utils.Utils; /** * Entry point to application. * This is where all the fun happens, with the main method. * Decides to display UI or to run silently via command-line. * * As the "controller" to all other classes, it parses command line parameters and loads the history. */ public class App { public static final Logger logger = Logger.getLogger(App.class); private static final History HISTORY = new History(); /** * Where everything starts. Takes in, and tries to parse as many commandline arguments as possible. * Otherwise, it launches a GUI. * * @param args Array of command line arguments. */ public static void main(String[] args) throws MalformedURLException { CommandLine cl = getArgs(args); if (args.length > 0 && cl.hasOption('v')){ logger.info(UpdateUtils.getThisJarVersion()); System.exit(0); } if (Utils.getConfigString("proxy.http", null) != null) { Proxy.setHTTPProxy(Utils.getConfigString("proxy.http", null)); } else if (Utils.getConfigString("proxy.socks", null) != null) { Proxy.setSocks(Utils.getConfigString("proxy.socks", null)); } if (GraphicsEnvironment.isHeadless() || args.length > 0) { handleArguments(args); } else { if (SystemUtils.IS_OS_MAC_OSX) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "RipMe"); } Utils.configureLogger(); logger.info("Initialized ripme v" + UpdateUtils.getThisJarVersion()); MainWindow mw = new MainWindow(); SwingUtilities.invokeLater(mw); } } /** * Creates an abstract ripper and instructs it to rip. * @param url URL to be ripped * @throws Exception Nothing too specific here, just a catch-all. * */ private static void rip(URL url) throws Exception { AbstractRipper ripper = AbstractRipper.getRipper(url); ripper.setup(); ripper.rip(); } /** * For dealing with command-line arguments. * @param args Array of Command-line arguments */ private static void handleArguments(String[] args) { CommandLine cl = getArgs(args); //Help (list commands) if (cl.hasOption('h') || args.length == 0) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar ripme.jar [OPTIONS]", getOptions()); System.exit(0); } Utils.configureLogger(); logger.info("Initialized ripme v" + UpdateUtils.getThisJarVersion()); //Allow file overwriting if (cl.hasOption('w')) { Utils.setConfigBoolean("file.overwrite", true); } //SOCKS proxy server if (cl.hasOption('s')) { String sservfull = cl.getOptionValue('s').trim(); Proxy.setSocks(sservfull); } //HTTP proxy server if (cl.hasOption('p')) { String proxyserverfull = cl.getOptionValue('p').trim(); Proxy.setHTTPProxy(proxyserverfull); } //Number of threads if (cl.hasOption('t')) { Utils.setConfigInteger("threads.size", Integer.parseInt(cl.getOptionValue('t'))); } //Ignore 404 if (cl.hasOption('4')) { Utils.setConfigBoolean("errors.skip404", true); } //Re-rip <i>all</i> previous albums if (cl.hasOption('r')) { // Re-rip all via command-line List<String> history = Utils.getConfigList("download.history"); for (String urlString : history) { try { URL url = new URL(urlString.trim()); rip(url); } catch (Exception e) { logger.error("[!] Failed to rip URL " + urlString, e); continue; } try { Thread.sleep(500); } catch (InterruptedException e) { logger.warn("[!] Interrupted while re-ripping history"); System.exit(-1); } } // Exit System.exit(0); } //Re-rip all <i>selected</i> albums if (cl.hasOption('R')) { loadHistory(); if (HISTORY.toList().isEmpty()) { logger.error("There are no history entries to re-rip. Rip some albums first"); System.exit(-1); } int added = 0; for (HistoryEntry entry : HISTORY.toList()) { if (entry.selected) { added++; try { URL url = new URL(entry.url); rip(url); } catch (Exception e) { logger.error("[!] Failed to rip URL " + entry.url, e); continue; } try { Thread.sleep(500); } catch (InterruptedException e) { logger.warn("[!] Interrupted while re-ripping history"); System.exit(-1); } } } if (added == 0) { logger.error("No history entries have been 'Checked'\n" + "Check an entry by clicking the checkbox to the right of the URL or Right-click a URL to check/uncheck all items"); System.exit(-1); } } //Save the order of images in album if (cl.hasOption('d')) { Utils.setConfigBoolean("download.save_order", true); } //Don't save the order of images in album if (cl.hasOption('D')) { Utils.setConfigBoolean("download.save_order", false); } //In case specify both, break and exit since it isn't possible. if ((cl.hasOption('d'))&&(cl.hasOption('D'))) { logger.error("\nCannot specify '-d' and '-D' simultaneously"); System.exit(-1); } //Destination directory if (cl.hasOption('l')) { // change the default rips directory Utils.setConfigString("rips.directory", cl.getOptionValue('l')); } //Read URLs from File if (cl.hasOption('f')) { String filename = cl.getOptionValue('f'); try { String url; BufferedReader br = new BufferedReader(new FileReader(filename)); while ((url = br.readLine()) != null) { if (url.startsWith("//") || url.startsWith(" logger.debug("Skipping over line \"" + url + "\"because it is a comment"); } else { // loop through each url in the file and process each url individually. ripURL(url.trim(), cl.hasOption("n")); } } } catch (FileNotFoundException fne) { logger.error("[!] File containing list of URLs not found. Cannot continue."); } catch (IOException ioe) { logger.error("[!] Failed reading file containing list of URLs. Cannot continue."); } } //The URL to rip. if (cl.hasOption('u')) { String url = cl.getOptionValue('u').trim(); ripURL(url, cl.hasOption("n")); } } /** * Attempt to rip targetURL. * @param targetURL URL to rip * @param saveConfig Whether or not you want to save the config (?) */ private static void ripURL(String targetURL, boolean saveConfig) { try { URL url = new URL(targetURL); rip(url); List<String> history = Utils.getConfigList("download.history"); if (!history.contains(url.toExternalForm())) {//if you haven't already downloaded the file before history.add(url.toExternalForm());//add it to history so you won't have to redownload Utils.setConfigList("download.history", Arrays.asList(history.toArray())); if (saveConfig) { Utils.saveConfig(); } } } catch (MalformedURLException e) { logger.error("[!] Given URL is not valid. Expected URL format is http://domain.com/..."); // System.exit(-1); } catch (Exception e) { logger.error("[!] Error while ripping URL " + targetURL, e); // System.exit(-1); } } /** * Creates an Options object, returns it. * @return Returns all acceptable command-line options. */ private static Options getOptions() { Options opts = new Options(); opts.addOption("h", "help", false, "Print the help"); opts.addOption("u", "url", true, "URL of album to rip"); opts.addOption("t", "threads", true, "Number of download threads per rip"); opts.addOption("w", "overwrite", false, "Overwrite existing files"); opts.addOption("r", "rerip", false, "Re-rip all ripped albums"); opts.addOption("R", "rerip-selected", false, "Re-rip all selected albums"); opts.addOption("d", "saveorder", false, "Save the order of images in album"); opts.addOption("D", "nosaveorder", false, "Don't save order of images"); opts.addOption("4", "skip404", false, "Don't retry after a 404 (not found) error"); opts.addOption("l", "ripsdirectory", true, "Rips Directory (Default: ./rips)"); opts.addOption("n", "no-prop-file", false, "Do not create properties file."); opts.addOption("f", "urls-file", true, "Rip URLs from a file."); opts.addOption("v", "version", false, "Show current version"); opts.addOption("s", "socks-server", true, "Use socks server ([user:password]@host[:port])"); opts.addOption("p", "proxy-server", true, "Use HTTP Proxy server ([user:password]@host[:port])"); return opts; } /** * Tries to parse commandline arguments. * @param args Array of commandline arguments. * @return CommandLine object containing arguments. */ private static CommandLine getArgs(String[] args) { BasicParser parser = new BasicParser(); try { return parser.parse(getOptions(), args, false); } catch (ParseException e) { logger.error("[!] Error while parsing command-line arguments: " + Arrays.toString(args), e); System.exit(-1); return null; } } /** * Loads history from history file into memory. */ private static void loadHistory() { File historyFile = new File(Utils.getConfigDir() + File.separator + "history.json"); HISTORY.clear(); if (historyFile.exists()) { try { logger.info("Loading history from " + historyFile.getCanonicalPath()); HISTORY.fromFile(historyFile.getCanonicalPath()); } catch (IOException e) { logger.error("Failed to load history from file " + historyFile, e); logger.warn( "RipMe failed to load the history file at " + historyFile.getAbsolutePath() + "\n\n" + "Error: " + e.getMessage() + "\n\n" + "Closing RipMe will automatically overwrite the contents of this file,\n" + "so you may want to back the file up before closing RipMe!"); } } else { logger.info("Loading history from configuration"); HISTORY.fromList(Utils.getConfigList("download.history")); if (HISTORY.toList().size() == 0) { // Loaded from config, still no entries. // Guess rip history based on rip folder String[] dirs = Utils.getWorkingDirectory().list((dir, file) -> new File(dir.getAbsolutePath() + File.separator + file).isDirectory()); for (String dir : dirs) { String url = RipUtils.urlFromDirectoryName(dir); if (url != null) { // We found one, add it to history HistoryEntry entry = new HistoryEntry(); entry.url = url; HISTORY.add(entry); } } } } } }
package com.tek271.funj; import com.google.common.annotations.Beta; import com.google.common.collect.Lists; import java.util.List; import static com.tek271.funj.CollectionTools.isEmpty; @Beta public class Reducer { /** * interface to be implemented by reduce functions * @param <T> type of value to reduce. */ public static interface ReduceFunction<T> { T reduceValue(T buffer, T value); } /** * Left reduce the given iterable into a single value using the given reduceFunction * @param iterable values to reduce starting at the first item * @param reduceFunction the function to apply on each item * @param initialValue the start value for the reduction * @param <T> Type of values in iterable * @return the reduced value */ public static <T> T reduce(Iterable<T> iterable, ReduceFunction<T> reduceFunction, T initialValue) { if (isEmpty(iterable)) return initialValue; T r = initialValue; for (T i: iterable) { r = reduceFunction.reduceValue(r, i); } return r; } /** * Right reduce the given iterable into a single value using the given reduceFunction * @param iterable values to reduce starting at the last item * @param reduceFunction the function to apply on each item * @param initialValue the start value for the reduction * @param <T> Type of values in iterable * @return the reduced value */ public static <T> T reduceRight(Iterable<T> iterable, ReduceFunction<T> reduceFunction, T initialValue) { if (isEmpty(iterable)) return initialValue; List<T> list = Lists.reverse(Lists.newLinkedList(iterable)); T r = initialValue; for (T i:list) { r = reduceFunction.reduceValue(r, i); } return r; } }
package com.cj.votron; import java.util.ArrayList; import java.util.Arrays; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; /** * @author gvamos * */ public class ElectionsActivity extends Activity { private ListView electionListView ; private ArrayAdapter<String> listAdapter ; private Config.Elections elections; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(this.getClass().getName(),":onCreate"); setContentView(R.layout.activity_elections); elections = Config.getInstance().getElections(); elections.updateElections(); // Shave the yak. electionListView = (ListView) findViewById( R.id.electionsListView ); listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, (elections.getElectionsList())); electionListView.setAdapter( listAdapter ); } }
package DataStructures.linkedlistpack; import DataStructures.exceptions.ItemNotFoundException; public class List < T > implements Iterable<T> { final static int NOTFOUND = -1; private ListNode< T > _Head; private ListNode< T > _Tail; private int _Size; public List( ) { this._Head = this._Tail = null; } public int size( ) { return this._Size; } public boolean isEmpty( ) { return _Head == null; } public void add( T pDato ) { this.addManager(this.size(), pDato); } public void addToStart( T pDato ) { this.addManager(0, pDato); } public void add( T pDato, int pIndex ) { this.addManager(pIndex, pDato); } private void addManager(int pIndice, T pDato) { if(pIndice <= this._Size) { ListNode<T> tmp = new ListNode<T>(pDato); //Anadir un primer elemento if(this._Size == 0) { this._Head = tmp; this._Tail = tmp; } //Anadir al inicio else if(pIndice == 0) { tmp.setNext(this._Head); this._Head.setPrev(tmp); this._Head = tmp; } //Anadir al final else if(pIndice == this._Size) { this._Tail.setNext(tmp); tmp.setPrev(this._Tail); this._Tail = tmp; } //Anadir en un determinado indice else { ListNode<T> pivote = this._Head; for(int x = 0; x < pIndice - 1; x++) { pivote = pivote.getNext(); } tmp.setPrev(pivote); tmp.setNext(pivote.getNext()); pivote.getNext().setPrev(tmp); pivote.setNext(tmp); } this._Size++; } else System.out.print("Indice Fuera de Rango"); } public void print() { ListIterator<T> iterator = this.iterator(); System.out.print("[ "); while(iterator.hasNext()) { System.out.print(iterator.next() + ", "); } System.out.println(" ]"); } /** * * @param pIndice * @return * @throws ArrayIndexOutOfBoundsException */ public T search(int pIndice) { if(pIndice < this._Size) { ListIterator<T> iterator = this.iterator(); T tmp = iterator.next(); for(int x = 0 ; x != pIndice; x++) tmp = iterator.next(); return tmp; } else throw new IndexOutOfBoundsException("Indice " + pIndice); } /** * Remover por medio de un indice un elemento de la lista. * @param pIndex {@link Integer} * @throws ArrayIndexOutOfBoundsException */ public void remove(int pIndex) { if(pIndex < this._Size) { //Eliminar el ultimo elemento de la lista if(this._Size == 1) { this._Head = this._Tail = null; } //Eliminar el primer elemento de la lista else if(pIndex == 0) { this._Head.getNext().setPrev(null); this._Head = this._Head.getNext(); } //Eliminar el ultimo elemento de la lista else if(pIndex == this._Size - 1) { this._Tail.getPrev().setNext(null); this._Tail = this._Tail.getPrev(); } //Eliminar un elemento en otra posicion else { ListNode<T> tmp = this._Head; for(int x = 0; x != pIndex; x++) { tmp = tmp.getNext(); } tmp.getPrev().setNext(tmp.getNext()); tmp.getNext().setPrev(tmp.getPrev()); } this._Size } else throw new IndexOutOfBoundsException("Indice Incorrecto: " + pIndex ); } @Override public ListIterator<T> iterator() { return new ListIterator<T>(this); } public void remove(T pDato) { this.remove( this.search(pDato) ); } public int search(T pDato) { int index = List.NOTFOUND; ListIterator<T> iterador = this.iterator(); for(int x = 0; iterador.hasNext(); x++) { if( iterador.next().equals(pDato) ) { index = x; break; } } if(index == List.NOTFOUND) throw new ItemNotFoundException(pDato.toString()); return index; } protected ListNode<T> getHead() { return this._Head; } public boolean contains(T pDato) { boolean state = false; ListIterator<T> iterador = this.iterator(); while(iterador.hasNext()) { if( iterador.next().equals(pDato) ) { state = true; break; } } return state; } public void set(T pDato, int pIndice) { if(pIndice < this._Size) { ListNode<T> tmp = this.getHead(); for(int x = 0 ; x < pIndice; x++) tmp = tmp.getNext(); tmp.setData(pDato); } else throw new IndexOutOfBoundsException("Indice " + pIndice); } }
package hudson.remoting; import edu.umd.cs.findbugs.annotations.SuppressWarnings; import hudson.remoting.CommandTransport.CommandReceiver; import hudson.remoting.ExportTable.ExportList; import hudson.remoting.PipeWindow.Key; import hudson.remoting.PipeWindow.Real; import hudson.remoting.forward.ListeningPort; import hudson.remoting.forward.ForwarderFactory; import hudson.remoting.forward.PortForwarder; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.Hashtable; import java.util.Locale; import java.util.Map; import java.util.Vector; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * Represents a communication channel to the remote peer. * * <p> * A {@link Channel} is a mechanism for two JVMs to communicate over * bi-directional {@link InputStream}/{@link OutputStream} pair. * {@link Channel} represents an endpoint of the stream, and thus * two {@link Channel}s are always used in a pair. * * <p> * Communication is established as soon as two {@link Channel} instances * are created at the end fo the stream pair * until the stream is terminated via {@link #close()}. * * <p> * The basic unit of remoting is an executable {@link Callable} object. * An application can create a {@link Callable} object, and execute it remotely * by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method. * * <p> * In this sense, {@link Channel} is a mechanism to delegate/offload computation * to other JVMs and somewhat like an agent system. This is bit different from * remoting technologies like CORBA or web services, where the server exposes a * certain functionality that clients invoke. * * <p> * {@link Callable} object, as well as the return value / exceptions, * are transported by using Java serialization. All the necessary class files * are also shipped over {@link Channel} on-demand, so there's no need to * pre-deploy such classes on both JVMs. * * * <h2>Implementor's Note</h2> * <p> * {@link Channel} builds its features in a layered model. Its higher-layer * features are built on top of its lower-layer features, and they * are called layer-0, layer-1, etc. * * <ul> * <li> * <b>Layer 0</b>: * See {@link Command} for more details. This is for higher-level features, * and not likely useful for applications directly. * <li> * <b>Layer 1</b>: * See {@link Request} for more details. This is for higher-level features, * and not likely useful for applications directly. * </ul> * * @author Kohsuke Kawaguchi */ public class Channel implements VirtualChannel, IChannel, Closeable { private final CommandTransport transport; /** * {@link OutputStream} that's given to the constructor. This is the hand-off with the lower layer. * * @deprecated * See {@link #getUnderlyingOutput()}. */ private final OutputStream underlyingOutput; /** * Human readable description of where this channel is connected to. Used during diagnostic output * and error reports. */ private final String name; private volatile boolean isRestricted; /*package*/ final InterceptingExecutorService executor; /** * If non-null, the incoming link is already shut down, * and reader is already terminated. The {@link Throwable} object indicates why the outgoing channel * was closed. */ private volatile Throwable inClosed = null; /** * If non-null, the outgoing link is already shut down, * and no command can be sent. The {@link Throwable} object indicates why the outgoing channel * was closed. */ private volatile Throwable outClosed = null; /** * Requests that are sent to the remote side for execution, yet we are waiting locally until * we hear back their responses. */ /*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>(); /** * Remembers last I/O ID issued from locally to the other side, per thread. * int[1] is used as a holder of int. */ private final ThreadLocal<int[]> lastIoId = new ThreadLocal<int[]>() { @Override protected int[] initialValue() { return new int[1]; } }; /** * Records the {@link Request}s being executed on this channel, sent by the remote peer. */ /*package*/ final Map<Integer,Request<?,?>> executingCalls = Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>()); /** * {@link ClassLoader}s that are proxies of the remote classloaders. */ /*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this); /** * Objects exported via {@link #export(Class, Object)}. */ /*package (for test)*/ final ExportTable<Object> exportedObjects = new ExportTable<Object>(); /** * {@link PipeWindow}s keyed by their OIDs (of the OutputStream exported by the other side.) * * <p> * To make the GC of {@link PipeWindow} automatic, the use of weak references here are tricky. * A strong reference to {@link PipeWindow} is kept from {@link ProxyOutputStream}, and * this is the only strong reference. Thus while {@link ProxyOutputStream} is alive, * it keeps {@link PipeWindow} referenced, which in turn keeps its {@link PipeWindow.Real#key} * referenced, hence this map can be looked up by the OID. When the {@link ProxyOutputStream} * will be gone, the key is no longer strongly referenced, so it'll get cleaned up. * * <p> * In some race condition situation, it might be possible for us to lose the tracking of the collect * window size. But as long as we can be sure that there's only one {@link PipeWindow} instance * per OID, it will only result in a temporary spike in the effective window size, * and therefore should be OK. */ private final WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>> pipeWindows = new WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>>(); /** * Registered listeners. */ private final Vector<Listener> listeners = new Vector<Listener>(); private int gcCounter; private int commandsSent; /** * Total number of nanoseconds spent for remote class loading. * <p> * Remote code execution often results in classloading activity * (more precisely, when the remote peer requests some computation * on this channel, this channel often has to load necessary * classes from the remote peer.) * <p> * This counter represents the total amount of time this channel * had to spend loading classes from the remote peer. The time * measurement doesn't include the time locally spent to actually * define the class (as the local classloading would have incurred * the same cost.) */ public final AtomicLong classLoadingTime = new AtomicLong(); /** * Total counts of remote classloading activities. Used in a pair * with {@link #classLoadingTime}. */ public final AtomicInteger classLoadingCount = new AtomicInteger(); /** * Prefetch cache hits. * * Out of all the counts in {@link #classLoadingCount}, how many times * were we able to resolve them by ourselves, saving a remote roundtrip call? * @since XXX prefetch-JENKINS-15120 */ public final AtomicInteger classLoadingPrefetchCacheCount = new AtomicInteger(); /** * Total number of nanoseconds spent for remote resource loading. * @see #classLoadingTime */ public final AtomicLong resourceLoadingTime = new AtomicLong(); /** * Total count of remote resource loading. * @see #classLoadingCount */ public final AtomicInteger resourceLoadingCount = new AtomicInteger(); private final AtomicInteger ioId = new AtomicInteger(); /** * Property bag that contains application-specific stuff. */ private final Hashtable<Object,Object> properties = new Hashtable<Object,Object>(); /** * Proxy to the remote {@link Channel} object. */ private final IChannel remoteChannel; /** * Capability of the remote {@link Channel}. */ public final Capability remoteCapability; /** * When did we receive any data from this slave the last time? * This can be used as a basis for detecting dead connections. * <p> * Note that this doesn't include our sender side of the operation, * as successfully returning from {@link #send(Command)} doesn't mean * anything in terms of whether the underlying network was able to send * the data (for example, if the other end of a socket connection goes down * without telling us anything, the {@link SocketOutputStream#write(int)} will * return right away, and the socket only really times out after 10s of minutes. */ private volatile long lastHeard; /** * Single-thread executor for running pipe I/O operations. * * It is executed in a separate thread to avoid blocking the channel reader thread * in case read/write blocks. It is single thread to ensure FIFO; I/O needs to execute * in the same order the remote peer told us to execute them. */ /*package*/ final PipeWriter pipeWriter; /** * ClassLaoder that remote classloaders should use as the basis. */ /*package*/ final ClassLoader baseClassLoader; private JarCache jarCache; /*package*/ final JarLoaderImpl jarLoader; /** * Communication mode used in conjunction with {@link ClassicCommandTransport}. * * @since 1.161 */ public enum Mode { /** * Send binary data over the stream. Most efficient. */ BINARY(new byte[]{0,0,0,0}), /** * Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%, * but this is useful where stream is binary-unsafe, such as telnet. */ TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") { @Override protected OutputStream wrap(OutputStream os) { return BinarySafeStream.wrap(os); } @Override protected InputStream wrap(InputStream is) { return BinarySafeStream.wrap(is); } }, /** * Let the remote peer decide the transmission mode and follow that. * Note that if both ends use NEGOTIATE, it will dead lock. */ NEGOTIATE(new byte[0]); /** * Preamble used to indicate the tranmission mode. * Because of the algorithm we use to detect the preamble, * the string cannot be any random string. For example, * if the preamble is "AAB", we'll fail to find a preamble * in "AAAB". */ /*package*/ final byte[] preamble; Mode(String preamble) { try { this.preamble = preamble.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new Error(e); } } Mode(byte[] preamble) { this.preamble = preamble; } protected OutputStream wrap(OutputStream os) { return os; } protected InputStream wrap(InputStream is) { return is; } } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException { this(name,exec,Mode.BINARY,is,os,null); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException { this(name,exec,mode,is,os,null); } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,Mode.BINARY,is,os,header); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,mode,is,os,header,false); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException { this(name,exec,mode,is,os,header,restricted,null); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException { this(name,exec,mode,is,os,header,restricted,base,new Capability()); } /*package*/ Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base, Capability capability) throws IOException { this(name,exec, ClassicCommandTransport.create(mode, is, os, header, base, capability),restricted,base); } /** * @since 2.13 */ public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base) throws IOException { this(name,exec,transport,restricted,base,null); } /** * Creates a new channel. * * @param name * See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)} * @param exec * See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)} * @param transport * The transport that we run {@link Channel} on top of. * @param base * See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)} * @param restricted * See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)} * @param jarCache * * @since XXX prefetch-JENKINS-15120 */ public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base, JarCache jarCache) throws IOException { this.name = name; this.executor = new InterceptingExecutorService(exec); this.isRestricted = restricted; this.underlyingOutput = transport.getUnderlyingStream(); this.jarCache = jarCache; if (base==null) base = getClass().getClassLoader(); this.baseClassLoader = base; if(export(this,false)!=1) throw new AssertionError(); // export number 1 is reserved for the channel itself remoteChannel = RemoteInvocationHandler.wrap(this,1,IChannel.class,true,false); this.remoteCapability = transport.getRemoteCapability(); this.pipeWriter = new PipeWriter(createPipeWriterExecutor()); this.transport = transport; this.jarLoader = new JarLoaderImpl(); // TODO: figure out a mechanism to allow the user to share this across Channels setProperty(JarLoader.OURS,export(JarLoader.class,jarLoader,false)); transport.setup(this, new CommandReceiver() { public void handle(Command cmd) { lastHeard = System.currentTimeMillis(); if (logger.isLoggable(Level.FINE)) logger.fine("Received " + cmd); try { cmd.execute(Channel.this); } catch (Throwable t) { logger.log(Level.SEVERE, "Failed to execute command " + cmd + " (channel " + Channel.this.name + ")", t); logger.log(Level.SEVERE, "This command is created here", cmd.createdAt); } } public void terminate(IOException e) { Channel.this.terminate(e); } }); } /** * Callback "interface" for changes in the state of {@link Channel}. */ public static abstract class Listener { /** * When the channel was closed normally or abnormally due to an error. * * @param cause * if the channel is closed abnormally, this parameter * represents an exception that has triggered it. * Otherwise null. */ public void onClosed(Channel channel, IOException cause) {} } /*package*/ boolean isOutClosed() { return outClosed!=null; } /** * Creates the {@link ExecutorService} for writing to pipes. * * <p> * If the throttling is supported, use a separate thread to free up the main channel * reader thread (thus prevent blockage.) Otherwise let the channel reader thread do it, * which is the historical behaviour. */ private ExecutorService createPipeWriterExecutor() { if (remoteCapability.supportsPipeThrottling()) return Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(r,"Pipe writer thread: "+name); } }); return new SynchronousExecutorService(); } /** * Sends a command to the remote end and executes it there. * * <p> * This is the lowest layer of abstraction in {@link Channel}. * {@link Command}s are executed on a remote system in the order they are sent. */ /*package*/ synchronized void send(Command cmd) throws IOException { if(outClosed!=null) throw new ChannelClosedException(outClosed); if(logger.isLoggable(Level.FINE)) logger.fine("Send "+cmd); transport.write(cmd, cmd instanceof CloseCommand); commandsSent++; } /** * {@inheritDoc} */ public <T> T export(Class<T> type, T instance) { return export(type, instance, true); } /** * @param userProxy * If true, the returned proxy will be capable to handle classes * defined in the user classloader as parameters and return values. * Such proxy relies on {@link RemoteClassLoader} and related mechanism, * so it's not usable for implementing lower-layer services that are * used by {@link RemoteClassLoader}. * * To create proxies for objects inside remoting, pass in false. */ /*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) { if(instance==null) return null; // every so often perform GC on the remote system so that // unused RemoteInvocationHandler get released, which triggers // unexport operation. if((++gcCounter)%10000==0) try { send(new GCCommand()); } catch (IOException e) { // for compatibility reason we can't change the export method signature logger.log(Level.WARNING, "Unable to send GC command",e); } // either local side will auto-unexport, or the remote side will unexport when it's GC-ed boolean autoUnexportByCaller = exportedObjects.isRecording(); final int id = export(instance,autoUnexportByCaller); return RemoteInvocationHandler.wrap(null, id, type, userProxy, autoUnexportByCaller); } /*package*/ int export(Object instance) { return exportedObjects.export(instance); } /*package*/ int export(Object instance, boolean automaticUnexport) { return exportedObjects.export(instance, automaticUnexport); } /*package*/ Object getExportedObject(int oid) { return exportedObjects.get(oid); } /*package*/ void unexport(int id) { exportedObjects.unexportByOid(id); } /** * Increase reference count so much to effectively prevent de-allocation. * * @see ExportTable.Entry#pin() */ public void pin(Object instance) { exportedObjects.pin(instance); } /** * {@linkplain #pin(Object) Pin down} the exported classloader. */ public void pinClassLoader(ClassLoader cl) { RemoteClassLoader.pin(cl,this); } /** * Preloads jar files on the remote side. * * <p> * This is a performance improvement method that can be safely * ignored if your goal is just to make things working. * * <p> * Normally, classes are transferred over the network one at a time, * on-demand. This design is mainly driven by how Java classloading works * &mdash; we can't predict what classes will be necessarily upfront very easily. * * <p> * Classes are loaded only once, so for long-running {@link Channel}, * this is normally an acceptable overhead. But sometimes, for example * when a channel is short-lived, or when you know that you'll need * a majority of classes in certain jar files, then it is more efficient * to send a whole jar file over the network upfront and thereby * avoiding individual class transfer over the network. * * <p> * That is what this method does. It ensures that a series of jar files * are copied to the remote side (AKA "preloading.") * Classloading will consult the preloaded jars before performing * network transfer of class files. * * <p><strong>Beware</strong> that this method is not useful in all configurations. * If a {@link RemoteClassLoader} has another {@link RemoteClassLoader} as a * {@linkplain ClassLoader#getParent parent}, which would be typical, then preloading * a JAR in it will not reduce network round-trips: each class load still has to call * {@link ClassLoader#loadClass(String, boolean) loadClass} on the parent, which will * wind up checking the remote side just to get a negative answer. * * @param classLoaderRef * This parameter is used to identify the remote classloader * that will prefetch the specified jar files. That is, prefetching * will ensure that prefetched jars will kick in * when this {@link Callable} object is actually executed remote side. * * <p> * {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader}, * so this parameter doesn't have to be exactly the same {@link Callable} * to be executed later &mdash; it just has to be of the same class. * @param classesInJar * {@link Class} objects that identify jar files to be preloaded. * Jar files that contain the specified classes will be preloaded into the remote peer. * You just need to specify one class per one jar. * @return * true if the preloading actually happened. false if all the jars * are already preloaded. This method is implemented in such a way that * unnecessary jar file transfer will be avoided, and the return value * will tell you if this optimization kicked in. Under normal circumstances * your program shouldn't depend on this return value. It's just a hint. * @throws IOException * if the preloading fails. */ public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException { return preloadJar(UserRequest.getClassLoader(classLoaderRef), classesInJar); } public boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException { URL[] jars = new URL[classesInJar.length]; for (int i = 0; i < classesInJar.length; i++) jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL(); return call(new PreloadJarTask(jars, local)); } public boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException { return call(new PreloadJarTask(jars,local)); } /** * If this channel is built with jar file caching, return the object that manages this cache. * @since XXX prefetch-JENKINS-15120 */ public JarCache getJarCache() { return jarCache; } /** * You can change the {@link JarCache} while the channel is in operation, * but doing so doesn't impact {@link RemoteClassLoader}s that are already created. * * So to best avoid performance loss due to race condition, please set a JarCache in the constructor, * unless your call sequence guarantees that you call this method before remote classes are loaded. * @since XXX prefetch-JENKINS-15120 */ public void setJarCache(JarCache jarCache) { this.jarCache = jarCache; } /*package*/ PipeWindow getPipeWindow(int oid) { synchronized (pipeWindows) { Key k = new Key(oid); WeakReference<PipeWindow> v = pipeWindows.get(k); if (v!=null) { PipeWindow w = v.get(); if (w!=null) return w; } PipeWindow w; if (remoteCapability.supportsPipeThrottling()) w = new Real(k, PIPE_WINDOW_SIZE); else w = new PipeWindow.Fake(); pipeWindows.put(k,new WeakReference<PipeWindow>(w)); return w; } } /** * {@inheritDoc} */ public <V,T extends Throwable> V call(Callable<V,T> callable) throws IOException, T, InterruptedException { UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); // re-wrap the exception so that we can capture the stack trace of the caller. } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { // since this is synchronous operation, when the round trip is over // we assume all the exported objects are out of scope. // (that is, the operation shouldn't spawn a new thread or altter // global state in the remote system. if(request!=null) request.releaseExports(); } } /** * {@inheritDoc} */ public <V,T extends Throwable> Future<V> callAsync(final Callable<V,T> callable) throws IOException { final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this); return new FutureAdapter<V,UserResponse<V,T>>(f) { protected V adapt(UserResponse<V,T> r) throws ExecutionException { try { return r.retrieve(Channel.this, UserRequest.getClassLoader(callable)); } catch (Throwable t) {// really means catch(T t) throw new ExecutionException(t); } } }; } /** * Aborts the connection in response to an error. * * @param e * The error that caused the connection to be aborted. Never null. */ @java.lang.SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument") @SuppressWarnings("ITA_INEFFICIENT_TO_ARRAY") // intentionally; race condition on listeners otherwise protected void terminate(IOException e) { try { synchronized (this) { if (e == null) throw new IllegalArgumentException(); outClosed = inClosed = e; try { transport.closeRead(); } catch (IOException x) { logger.log(Level.WARNING, "Failed to close down the reader side of the transport", x); } try { synchronized (pendingCalls) { for (Request<?, ?> req : pendingCalls.values()) req.abort(e); pendingCalls.clear(); } synchronized (executingCalls) { for (Request<?, ?> r : executingCalls.values()) { java.util.concurrent.Future<?> f = r.future; if (f != null) f.cancel(true); } executingCalls.clear(); } } finally { notifyAll(); } } // JENKINS-14909: leave synch block } finally { if (e instanceof OrderlyShutdown) e = null; for (Listener l : listeners.toArray(new Listener[0])) l.onClosed(this, e); } } /** * Registers a new {@link Listener}. * * @see #removeListener(Listener) */ public void addListener(Listener l) { listeners.add(l); } /** * Removes a listener. * * @return * false if the given listener has not been registered to begin with. */ public boolean removeListener(Listener l) { return listeners.remove(l); } /** * Adds a {@link CallableFilter} that gets a chance to decorate every {@link Callable}s that run locally * sent by the other peer. * * This is useful to tweak the environment those closures are run, such as setting up the thread context * environment. */ public void addLocalExecutionInterceptor(CallableFilter filter) { executor.addFilter(filter); } /** * Rmoves the filter introduced by {@link #addLocalExecutionInterceptor(CallableFilter)}. */ public void removeLocalExecutionInterceptor(CallableFilter filter) { executor.removeFilter(filter); } /** * Waits for this {@link Channel} to be closed down. * * The close-down of a {@link Channel} might be initiated locally or remotely. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. */ public synchronized void join() throws InterruptedException { while(inClosed==null || outClosed==null) wait(); } /** * If the receiving end of the channel is closed (that is, if we are guaranteed to receive nothing further), * this method returns true. */ /*package*/ boolean isInClosed() { return inClosed!=null; } /** * Returns true if this channel is currently does not load classes from the remote peer. */ public boolean isRestricted() { return isRestricted; } public void setRestricted(boolean b) { isRestricted = b; } /** * Waits for this {@link Channel} to be closed down, but only up the given milliseconds. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. * @since 1.299 */ public synchronized void join(long timeout) throws InterruptedException { long start = System.currentTimeMillis(); while(System.currentTimeMillis()-start<timeout && (inClosed==null || outClosed==null)) wait(timeout+start-System.currentTimeMillis()); } /** * Notifies the remote peer that we are closing down. * * Execution of this command also triggers the {@link SynchronousCommandTransport.ReaderThread} to shut down * and quit. The {@link CloseCommand} is always the last command to be sent on * {@link ObjectOutputStream}, and it's the last command to be read. */ private static final class CloseCommand extends Command { private CloseCommand(Channel channel, Throwable cause) { super(channel,cause); } protected void execute(Channel channel) { try { channel.close(); channel.terminate(new OrderlyShutdown(createdAt)); } catch (IOException e) { logger.log(Level.SEVERE,"close command failed on "+channel.name,e); logger.log(Level.INFO,"close command created at",createdAt); } } @Override public String toString() { return "close"; } // this value is compatible with remoting < 2.8. I made an incompatible change in 2.8 that got corrected in 2.11. static final long serialVersionUID = 972857271608138115L; } /** * Signals the orderly shutdown of the channel, but captures * where the termination was initiated as a nested exception. */ private static final class OrderlyShutdown extends IOException { private OrderlyShutdown(Throwable cause) { super(cause.getMessage()); initCause(cause); } private static final long serialVersionUID = 1L; } /** * Resets all the performance counters. */ public void resetPerformanceCounters() { classLoadingCount.set(0); classLoadingTime.set(0); classLoadingPrefetchCacheCount.set(0); resourceLoadingCount.set(0); resourceLoadingTime.set(0); } /** * Print the performance counters. * @since XXX prefetch-JENKINS-15120 */ public void dumpPerformanceCounters(PrintWriter w) throws IOException { // locale fixed to English to get ',' for every 3 digits int l = classLoadingCount.get(); int p = classLoadingPrefetchCacheCount.get(); w.printf(Locale.ENGLISH, "Class loading count=%d\n", l); w.printf(Locale.ENGLISH, "Class loading prefetch hit=%s (%d%%)\n", p, p*100/l); w.printf(Locale.ENGLISH, "Class loading time=%,dms\n", classLoadingTime.get() / (1000 * 1000)); w.printf(Locale.ENGLISH, "Resource loading count=%d\n", resourceLoadingCount.get()); w.printf(Locale.ENGLISH, "Resource loading time=%,dms\n",resourceLoadingTime.get()/(1000*1000)); } /** * {@inheritDoc} */ public synchronized void close() throws IOException { close(null); } /** * Closes the channel. * * @param diagnosis * If someone (either this side or the other side) tries to use a channel that's already closed, * they'll get a stack trace indicating that the channel has already been closed. This diagnosis, * if provided, will further chained to that exception, providing more contextual information * about why the channel was closed. * * @since 2.8 */ public synchronized void close(Throwable diagnosis) throws IOException { if(outClosed!=null) return; // already closed send(new CloseCommand(this,diagnosis)); outClosed = new IOException().initCause(diagnosis); // last command sent. no further command allowed. lock guarantees that no command will slip inbetween try { transport.closeWrite(); } catch (IOException e) { // there's a race condition here. // the remote peer might have already responded to the close command // and closed the connection, in which case our close invocation // could fail with errors like // "java.io.IOException: The pipe is being closed" // so let's ignore this error. } // termination is done by CloseCommand when we received it. } public Object getProperty(Object key) { return properties.get(key); } public <T> T getProperty(ChannelProperty<T> key) { return key.type.cast(getProperty((Object) key)); } /** * Works like {@link #getProperty(Object)} but wait until some value is set by someone. */ public Object waitForProperty(Object key) throws InterruptedException { synchronized (properties) { while(true) { Object v = properties.get(key); if(v!=null) return v; properties.wait(); } } } public <T> T waitForProperty(ChannelProperty<T> key) throws InterruptedException { return key.type.cast(waitForProperty((Object) key)); } /** * Sets the property value on this side of the channel. * * @see #getProperty(Object) */ public Object setProperty(Object key, Object value) { synchronized (properties) { Object old = value!=null ? properties.put(key, value) : properties.remove(key); properties.notifyAll(); return old; } } public <T> T setProperty(ChannelProperty<T> key, T value) { return key.type.cast(setProperty((Object) key, value)); } /** * Gets the property set on the remote peer. * * @return null * if the property of the said key isn't set. */ public Object getRemoteProperty(Object key) { return remoteChannel.getProperty(key); } public <T> T getRemoteProperty(ChannelProperty<T> key) { return key.type.cast(getRemoteProperty((Object) key)); } /** * Gets the property set on the remote peer. * This method blocks until the property is set by the remote peer. */ public Object waitForRemoteProperty(Object key) throws InterruptedException { return remoteChannel.waitForProperty(key); } /** * @deprecated * Because {@link ChannelProperty} is identity-equality, this method would never work. * This is a design error. */ public <T> T waitForRemoteProperty(ChannelProperty<T> key) throws InterruptedException { return key.type.cast(waitForRemoteProperty((Object) key)); } /** * Obtain the output stream passed to the constructor. * * @deprecated * Future version of the remoting module may add other modes of creating channel * that doesn't involve stream pair. Therefore, we aren't committing to this method. * This method isn't a part of the committed API of the channel class. * @return * While the current version always return a non-null value, the caller must not * make that assumption for the above reason. This method may return null in the future version * to indicate that the {@link Channel} is not sitting on top of a stream pair. */ public OutputStream getUnderlyingOutput() { return underlyingOutput; } /** * Starts a local to remote port forwarding (the equivalent of "ssh -L"). * * @param recvPort * The port on this local machine that we'll listen to. 0 to let * OS pick a random available port. If you specify 0, use * {@link ListeningPort#getPort()} to figure out the actual assigned port. * @param forwardHost * The remote host that the connection will be forwarded to. * Connection to this host will be made from the other JVM that * this {@link Channel} represents. * @param forwardPort * The remote port that the connection will be forwarded to. * @return */ public ListeningPort createLocalToRemotePortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException { PortForwarder portForwarder = new PortForwarder(recvPort, ForwarderFactory.create(this, forwardHost, forwardPort)); portForwarder.start(); return portForwarder; } /** * Starts a remote to local port forwarding (the equivalent of "ssh -R"). * * @param recvPort * The port on the remote JVM (represented by this {@link Channel}) * that we'll listen to. 0 to let * OS pick a random available port. If you specify 0, use * {@link ListeningPort#getPort()} to figure out the actual assigned port. * @param forwardHost * The remote host that the connection will be forwarded to. * Connection to this host will be made from this JVM. * @param forwardPort * The remote port that the connection will be forwarded to. * @return */ public ListeningPort createRemoteToLocalPortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException { return PortForwarder.create(this,recvPort, ForwarderFactory.create(forwardHost, forwardPort)); } /** * Dispenses the unique I/O ID. * * When a {@link Channel} requests an activity that happens in {@link #pipeWriter}, * the sender assigns unique I/O ID to this request, which enables later * commands to sync up with their executions. * * @see PipeWriter */ /*package*/ int newIoId() { int v = ioId.incrementAndGet(); lastIoId.get()[0] = v; return v; } /** * Gets the last I/O ID issued by the calling thread, or 0 if none is recorded. */ /*package*/ int lastIoId() { return lastIoId.get()[0]; } /** * Blocks until all the I/O packets sent before this gets fully executed by the remote side, then return. * * @throws IOException * If the remote doesn't support this operation, or if sync fails for other reasons. */ public void syncIO() throws IOException, InterruptedException { call(new IOSyncer()); } // Barrier doesn't work because IOSyncer is a Callable and not Command // (yet making it Command would break JENKINS-5977, which introduced this split in the first place!) // /** // * Non-blocking version of {@link #syncIO()} that has a weaker commitment. // * // * This method only guarantees that any later remote commands will happen after all the I/O packets sent before // * this method call gets fully executed. This is faster in that it it doesn't wait for a response // * from the other side, yet it normally achieves the desired semantics. // */ // public void barrierIO() throws IOException { // callAsync(new IOSyncer()); public void syncLocalIO() throws InterruptedException { Thread t = Thread.currentThread(); String old = t.getName(); t.setName("I/O sync: "+old); try { // no one waits for the completion of this Runnable, so not using I/O ID pipeWriter.submit(0,new Runnable() { public void run() { // noop } }).get(); } catch (ExecutionException e) { throw new AssertionError(e); // impossible } finally { t.setName(old); } } private static final class IOSyncer implements Callable<Object, InterruptedException> { public Object call() throws InterruptedException { Channel.current().syncLocalIO(); return null; } private static final long serialVersionUID = 1L; } public String getName() { return name; } @Override public String toString() { return super.toString()+":"+name; } /** * Dumps the list of exported objects and their allocation traces to the given output. */ public void dumpExportTable(PrintWriter w) throws IOException { exportedObjects.dump(w); } public ExportList startExportRecording() { return exportedObjects.startRecording(); } /** * @see #lastHeard */ public long getLastHeard() { return lastHeard; } /*package*/ static Channel setCurrent(Channel channel) { Channel old = CURRENT.get(); CURRENT.set(channel); return old; } /** * This method can be invoked during the serialization/deserialization of * objects when they are transferred to the remote {@link Channel}, * as well as during {@link Callable#call()} is invoked. * * @return null * if the calling thread is not performing serialization. */ public static Channel current() { return CURRENT.get(); } /** * Remembers the current "channel" associated for this thread. */ private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>(); private static final Logger logger = Logger.getLogger(Channel.class.getName()); /** * Default pipe window size. * * <p> * This controls the amount of bytes that can be in flight. Value too small would fail to efficiently utilize * a high-latency/large-bandwidth network, but a value too large would cause the risk of a large memory consumption * when a pipe clogs (that is, the receiver isn't consuming bytes we are sending fast enough.) * * <p> * If we have a gigabit ethernet (with effective transfer rate of 100M bps) and 20ms latency, the pipe will hold * (100M bits/sec * 0.02sec / 8 bits/byte = 0.25MB. So 1MB or so is big enough for most network, and hopefully * this is an acceptable enough memory consumption in case of clogging. * * @see PipeWindow */ public static final int PIPE_WINDOW_SIZE = Integer.getInteger(Channel.class.getName()+".pipeWindowSize",1024*1024); static { if (Boolean.getBoolean("hudson.remoting.debug")) { ConsoleHandler h = new ConsoleHandler(); h.setFormatter(new Formatter(){ public synchronized String format(LogRecord record) { StringBuilder sb = new StringBuilder(); if (false) { sb.append((record.getMillis()%100000)+100000); sb.append(" "); if (record.getSourceClassName() != null) { sb.append(record.getSourceClassName()); } else { sb.append(record.getLoggerName()); } if (record.getSourceMethodName() != null) { sb.append(" "); sb.append(record.getSourceMethodName()); } sb.append('\n'); } String message = formatMessage(record); sb.append(record.getLevel().getLocalizedName()); sb.append(": "); sb.append(message); sb.append('\n'); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { } } return sb.toString(); } }); h.setLevel(Level.FINER); Logger l = Logger.getLogger(RemoteClassLoader.class.getName()); l.addHandler(h); l.setLevel(Level.FINER); l = Logger.getLogger(FileSystemJarCache.class.getName()); l.addHandler(h); l.setLevel(Level.FINER); l = Logger.getLogger(ResourceImageDirect.class.getName()); l.addHandler(h); l.setLevel(Level.FINER); } } }
package interpreter.scheme; import interpreter.*; import interpreter.type.*; import java.lang.IllegalArgumentException; public class Base extends Library { public class Plus extends Primitive { public SchemeObject apply(Interpreter interpreter, SchemePair args) { double total = 0.0; while(args != null) { SchemeObject element = args.head; if(element instanceof SchemeNumber) { total += ((SchemeNumber)element).value; } else { throw new IllegalArgumentException("argument is not a Number"); } args = SchemePair.of(args.tail); } return new SchemeNumber(total); } } public class Minus extends Primitive { public SchemeObject apply(Interpreter interpreter, SchemePair args) { if(args == null) { throw new IllegalArgumentException("not enough arguments"); } if(!(args.head instanceof SchemeNumber)) { throw new IllegalArgumentException("argument is not a Number"); } double total = ((SchemeNumber)args.head).value; if(args.tail == null) { return new SchemeNumber(-total); } args = SchemePair.of(args.tail); while(args != null) { SchemeObject element = args.head; if(!(element instanceof SchemeNumber)) { throw new IllegalArgumentException("argument is not a Number"); } total -= ((SchemeNumber)element).value; args = SchemePair.of(args.tail); } return new SchemeNumber(total); } } public class Times extends Primitive { public SchemeObject apply(Interpreter interpreter, SchemePair args) { double total = 1.0; while(args != null) { SchemeObject element = args.head; if(element instanceof SchemeNumber) { total *= ((SchemeNumber)element).value; } else { throw new IllegalArgumentException("argument is not a Number"); } args = SchemePair.of(args.tail); } return new SchemeNumber(total); } } public class Divide extends Primitive { public SchemeObject apply(Interpreter interpreter, SchemePair args) { if(args == null) { throw new IllegalArgumentException("not enough arguments"); } if(!(args.head instanceof SchemeNumber)) { throw new IllegalArgumentException("argument is not a Number"); } double total = ((SchemeNumber)args.head).value; if(args.tail == null) { return new SchemeNumber(1 / total); } args = SchemePair.of(args.tail); while(args != null) { SchemeObject element = args.head; if(!(element instanceof SchemeNumber)) { throw new IllegalArgumentException("argument is not a Number"); } total /= ((SchemeNumber)element).value; args = SchemePair.of(args.tail); } return new SchemeNumber(total); } } public class Equality extends Primitive { public SchemeObject apply(Interpreter interpreter, SchemePair args) { boolean result = true; SchemeNumber num = null; while(args != null) { SchemeObject element = args.head; if(!(element instanceof SchemeNumber)) { throw new IllegalArgumentException("argument is not a Number"); } if(num == null) { num = ((SchemeNumber)element); } else { result = result && num.value == ((SchemeNumber)element).value; } args = SchemePair.of(args.tail); } return new SchemeBoolean(result); } } public void importLib(Environment env) { env.define("+", new Plus()); env.define("-", new Minus()); env.define("*", new Times()); env.define("/", new Divide()); env.define("=", new Equality()); // Special forms env.define("if", new Syntax(Syntax.Special.IF)); env.define("lambda", new Syntax(Syntax.Special.LAMBDA)); env.define("begin", new Syntax(Syntax.Special.BEGIN)); env.define("define", new Syntax(Syntax.Special.DEFINE)); env.define("quote", new Syntax(Syntax.Special.QUOTE)); env.define("set!", new Syntax(Syntax.Special.SET)); } }
package net.glowstone; import lombok.ToString; import net.glowstone.ChunkManager.ChunkLock; import net.glowstone.GlowChunk.ChunkSection; import net.glowstone.GlowChunk.Key; import net.glowstone.GlowChunkSnapshot.EmptySnapshot; import net.glowstone.block.GlowBlock; import net.glowstone.block.ItemTable; import net.glowstone.block.blocktype.BlockType; import net.glowstone.constants.*; import net.glowstone.entity.*; import net.glowstone.entity.objects.GlowFallingBlock; import net.glowstone.entity.objects.GlowItem; import net.glowstone.entity.physics.BoundingBox; import net.glowstone.generator.structures.GlowStructure; import net.glowstone.io.WorldMetadataService.WorldFinalValues; import net.glowstone.io.WorldStorageProvider; import net.glowstone.io.anvil.AnvilWorldStorageProvider; import net.glowstone.net.message.play.entity.EntityStatusMessage; import net.glowstone.net.message.play.player.ServerDifficultyMessage; import net.glowstone.util.BlockStateDelegate; import net.glowstone.util.GameRuleManager; import org.bukkit.*; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.*; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.weather.LightningStrikeEvent; import org.bukkit.event.weather.ThunderChangeEvent; import org.bukkit.event.weather.WeatherChangeEvent; import org.bukkit.event.world.*; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.MetadataStore; import org.bukkit.metadata.MetadataStoreBase; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.messaging.StandardMessenger; import org.bukkit.util.Vector; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; /** * A class which represents the in-game world. * * @author Graham Edgecombe */ @ToString(of = "name") public final class GlowWorld implements World { /** * The length in ticks of one Minecraft day. */ public static final long DAY_LENGTH = 24000; /** * The metadata store for world objects. */ private static final MetadataStore<World> metadata = new WorldMetadataStore(); private static final int TICKS_PER_SECOND = 20; private static final int HALF_DAY_IN_TICKS = 12000; private static final int WEEK_IN_TICKS = 14 * HALF_DAY_IN_TICKS; /** * The length in ticks between autosaves (5 minutes). */ private static final int AUTOSAVE_TIME = TICKS_PER_SECOND * 60 * 5; /** * The maximum height of ocean water. */ private static final int SEA_LEVEL = 64; /** * The server of this world. */ private final GlowServer server; /** * The name of this world. */ private final String name; /** * The chunk manager. */ private final ChunkManager chunks; /** * A lock kept on the spawn chunks. */ private final ChunkLock spawnChunkLock; /** * The world metadata service used. */ private final WorldStorageProvider storageProvider; /** * The world's UUID */ private final UUID uid; /** * The entity manager. */ private final EntityManager entities = new EntityManager(); /** * This world's Random instance. */ private final Random random = new Random(); /** * The world populators for this world. */ private final List<BlockPopulator> populators; /** * The game rules used in this world. */ private final GameRuleManager gameRules = new GameRuleManager(); /** * The environment. */ private final Environment environment; /** * The world type. */ private final WorldType worldType; /** * Whether structure generation is enabled. */ private final boolean generateStructures; /** * The world seed. */ private final long seed; /** * Contains how regular blocks should be pulsed. */ private final ConcurrentHashMap<Location, Map.Entry<Long, Boolean>> tickMap = new ConcurrentHashMap<>(); private final Spigot spigot = new Spigot() { @Override public void playEffect(Location location, Effect effect) { playEffect_(location, effect, 0); } @Override public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) { showParticle(location, effect, id, data, offsetX, offsetY, offsetZ, speed, particleCount, radius); } }; /** * The spawn position. */ private Location spawnLocation; /** * Whether to keep the spawn chunks in memory (prevent them from being unloaded). */ private boolean keepSpawnLoaded = true; /** * Whether to populate chunks when they are anchored. */ private boolean populateAnchoredChunks; /** * Whether PvP is allowed in this world. */ private boolean pvpAllowed = true; /** * Whether animals can spawn in this world. */ private boolean spawnAnimals = true; /** * Whether monsters can spawn in this world. */ private boolean spawnMonsters = true; /** * Whether it is currently raining/snowing on this world. */ private boolean currentlyRaining = true; /** * How many ticks until the rain/snow status is expected to change. */ private int rainingTicks; /** * Whether it is currently thundering on this world. */ private boolean currentlyThundering = true; /** * How many ticks until the thundering status is expected to change. */ private int thunderingTicks; /** * The rain density on the current world tick. */ private float currentRainDensity; /** * The sky darkness on the current world tick. */ private float currentSkyDarkness; /** * The age of the world, in ticks. */ private long worldAge; /** * The current world time. */ private long time; /** * The time until the next full-save. */ private int saveTimer = AUTOSAVE_TIME; /** * The check to autosave */ private boolean autosave = true; /** * The world's gameplay difficulty. */ private Difficulty difficulty = Difficulty.PEACEFUL; /** * Ticks between when various types of entities are spawned. */ private long ticksPerAnimal, ticksPerMonster; /** * Per-chunk spawn limits on various types of entities. */ private int monsterLimit, animalLimit, waterAnimalLimit, ambientLimit; private Map<Integer, GlowStructure> structures; /** * The maximum height at which players may place blocks. */ private int maxBuildHeight; private Set<Key> activeChunksSet = new HashSet<>(); /** * Creates a new world from the options in the given WorldCreator. * * @param server The server for the world. * @param creator The WorldCreator to use. */ public GlowWorld(GlowServer server, WorldCreator creator) { this.server = server; // set up values from WorldCreator name = creator.name(); environment = creator.environment(); worldType = creator.type(); generateStructures = creator.generateStructures(); ChunkGenerator generator = creator.generator(); storageProvider = new AnvilWorldStorageProvider(new File(server.getWorldContainer(), name)); storageProvider.setWorld(this); populators = generator.getDefaultPopulators(this); // set up values from server defaults ticksPerAnimal = server.getTicksPerAnimalSpawns(); ticksPerMonster = server.getTicksPerMonsterSpawns(); monsterLimit = server.getMonsterSpawnLimit(); animalLimit = server.getAnimalSpawnLimit(); waterAnimalLimit = server.getWaterAnimalSpawnLimit(); ambientLimit = server.getAmbientSpawnLimit(); keepSpawnLoaded = server.keepSpawnLoaded(); populateAnchoredChunks = server.populateAnchoredChunks(); difficulty = server.getDifficulty(); maxBuildHeight = server.getMaxBuildHeight(); // read in world data WorldFinalValues values = null; values = storageProvider.getMetadataService().readWorldData(); if (values != null) { if (values.getSeed() == 0L) { seed = creator.seed(); } else { seed = values.getSeed(); } uid = values.getUuid(); } else { seed = creator.seed(); uid = UUID.randomUUID(); } chunks = new ChunkManager(this, storageProvider.getChunkIoService(), generator); structures = storageProvider.getStructureDataService().readStructuresData(); server.addWorld(this); server.getLogger().info("Preparing spawn for " + name + "..."); EventFactory.callEvent(new WorldInitEvent(this)); spawnChunkLock = keepSpawnLoaded ? newChunkLock("spawn") : null; // determine the spawn location if we need to if (spawnLocation == null) { // no location loaded, look for fixed spawn Location spawn = generator.getFixedSpawnLocation(this, random); setSpawnLocation(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()); } else { setKeepSpawnInMemory(keepSpawnLoaded); } server.getLogger().info("Preparing spawn for " + name + ": done"); EventFactory.callEvent(new WorldLoadEvent(this)); } // Various internal mechanisms /** * Get the world chunk manager. * * @return The ChunkManager for the world. */ public ChunkManager getChunkManager() { return chunks; } /** * Get the world's parent server. * * @return The GlowServer for the world. */ public GlowServer getServer() { return server; } /** * Get a new chunk lock object a player or other party can use to keep chunks loaded. * * @param desc A description for this chunk lock. * @return The ChunkLock. */ public ChunkLock newChunkLock(String desc) { return new ChunkLock(chunks, name + ": " + desc); } /** * Updates all the entities within this world. */ public void pulse() { List<GlowEntity> allEntities = new ArrayList<>(entities.getAll()); List<GlowPlayer> players = new LinkedList<>(); activeChunksSet.clear(); // We should pulse our tickmap, so blocks get updated. pulseTickMap(); // pulse players last so they actually see that other entities have // moved. unfortunately pretty hacky. not a problem for players b/c for (GlowEntity entity : allEntities) { if (entity instanceof GlowPlayer) { players.add((GlowPlayer) entity); updateActiveChunkCollection(entity); } else { entity.pulse(); } } updateBlocksInActiveChunks(); // why update blocks before Players or Entities? if there is a specific reason we should document it here. pulsePlayers(players); resetEntities(allEntities); updateWorldTime(); informPlayersOfTime(); updateOverworldWeather(); handleSleepAndWake(players); saveWorld(); } private void updateActiveChunkCollection(GlowEntity entity) { // build a set of chunks around each player in this world, the // server view distance is taken here int radius = server.getViewDistance(); Location playerLocation = entity.getLocation(); if (playerLocation.getWorld() == this) { int cx = playerLocation.getBlockX() >> 4; int cz = playerLocation.getBlockZ() >> 4; for (int x = cx - radius; x <= cx + radius; x++) { for (int z = cz - radius; z <= cz + radius; z++) { if (isChunkLoaded(cx, cz)) { activeChunksSet.add(new Key(x, z)); } } } } } private void updateBlocksInActiveChunks() { for (Key key : activeChunksSet) { int cx = key.getX(); int cz = key.getZ(); // check the chunk is loaded if (isChunkLoaded(cx, cz)) { GlowChunk chunk = getChunkAt(cx, cz); // thunder maybeStrikeLightningInChunk(cx, cz); // block ticking // we will choose 3 blocks per chunk's section ChunkSection[] sections = chunk.getSections(); for (int i = 0; i < sections.length; i++) { updateBlocksInSection(chunk, sections[i], i); } } } } private void updateBlocksInSection(GlowChunk chunk, ChunkSection section, int i) { if (section != null) { for (int j = 0; j < 3; j++) { int n = random.nextInt(); int x = n & 0xF; int z = n >> 8 & 0xF; int y = n >> 16 & 0xF; int type = section.types[y << 8 | z << 4 | x] >> 4; if (type != 0) { // filter air blocks BlockType blockType = ItemTable.instance().getBlock(type); // does this block needs random tick ? if (blockType != null && blockType.canTickRandomly()) { blockType.updateBlock(chunk.getBlock(x, y + (i << 4), z)); } } } } } private void saveWorld() { if (--saveTimer <= 0) { saveTimer = AUTOSAVE_TIME; chunks.unloadOldChunks(); if (autosave) { save(true); } } } private void updateOverworldWeather() { // only tick weather in a NORMAL world if (environment == Environment.NORMAL) { if (--rainingTicks <= 0) { setStorm(!currentlyRaining); } if (--thunderingTicks <= 0) { setThundering(!currentlyThundering); } updateWeather(); } } private void informPlayersOfTime() { if (worldAge % (30 * TICKS_PER_SECOND) == 0) { // Only send the time every 30 seconds; clients are smart. getRawPlayers().forEach(GlowPlayer::sendTime); } } // Tick the world age and time of day private void updateWorldTime() { worldAge++; // worldAge is used to determine when to (periodically) update clients of server time (time of day - "time") // also used to occasionally pulse some blocks (see "tickMap" and "requestPulse()") // Modulus by 24000, the tick length of a day if (gameRules.getBoolean("doDaylightCycle")) { time = (time + 1) % DAY_LENGTH; } } private void resetEntities(List<GlowEntity> entities) { entities.forEach(GlowEntity::reset); } private void pulsePlayers(List<GlowPlayer> players) { players.stream().filter(entity -> entity != null).forEach(GlowEntity::pulse); } private void handleSleepAndWake(List<GlowPlayer> players) { // Skip checking for sleeping players if no one is online if (!players.isEmpty()) { // If the night is over, wake up all players // Tick values for day/night time taken from the minecraft wiki if (getTime() < 12541 || getTime() > 23458) { wakeUpAllPlayers(players); // no need to send them the time - handle that normally } else { // otherwise check whether everyone is asleep boolean skipNight = gameRules.getBoolean("doDaylightCycle") && areAllPlayersSleeping(players); // check gamerule before iterating players (micro-optimization) if (skipNight) { skipRestOfNight(players); } } } } private void skipRestOfNight(List<GlowPlayer> players) { worldAge = (worldAge / DAY_LENGTH + 1) * DAY_LENGTH; time = 0; wakeUpAllPlayers(players, true); // true = send time to all players because we just changed it (to 0), above setStorm(false); setThundering(false); } private void wakeUpAllPlayers(List<GlowPlayer> players) { wakeUpAllPlayers(players, false); } private void wakeUpAllPlayers(List<GlowPlayer> players, boolean sendTime) { for (GlowPlayer player : players) { if (sendTime) { player.sendTime(); } if (player.isSleeping()) { player.leaveBed(true); } } } private boolean areAllPlayersSleeping(List<GlowPlayer> players) { for (GlowPlayer player : players) { if (!(player.isSleeping() && player.getSleepTicks() >= 100) && !player.isSleepingIgnored()) { return false; } } return true; } private void maybeStrikeLightningInChunk(int cx, int cz) { if (environment == Environment.NORMAL && currentlyRaining && currentlyThundering) { if (random.nextInt(100000) == 0) { strikeLightningInChunk(cx, cz); } } } private void strikeLightningInChunk(int cx, int cz) { int n = random.nextInt(); // get lightning target block int x = (cx << 4) + (n & 0xF); int z = (cz << 4) + (n >> 8 & 0xF); int y = getHighestBlockYAt(x, z); // target block up to the world height BoundingBox searchBox = BoundingBox.fromPositionAndSize(new Vector(x, y, z), new Vector(0, 0, 0)); Vector vec = new Vector(3, 3, 3); Vector vec2 = new Vector(0, getMaxHeight(), 0); searchBox.minCorner.subtract(vec); searchBox.maxCorner.add(vec).add(vec2); List<LivingEntity> livingEntities = new LinkedList<>(); // make sure entity can see sky getEntityManager().getEntitiesInside(searchBox, null).stream().filter(entity -> entity instanceof LivingEntity && !entity.isDead()).forEach(entity -> { Vector pos = entity.getLocation().toVector(); int minY = getHighestBlockYAt(pos.getBlockX(), pos.getBlockZ()); if (pos.getBlockY() >= minY) { livingEntities.add((LivingEntity) entity); } }); // re-target lightning if required if (!livingEntities.isEmpty()) { // randomly choose an entity LivingEntity entity = livingEntities.get(random.nextInt(livingEntities.size())); // re-target lightning on this living entity Vector newTarget = entity.getLocation().toVector(); x = newTarget.getBlockX(); z = newTarget.getBlockZ(); y = newTarget.getBlockY(); } // lightning strike if the target block is under rain if (GlowBiomeClimate.isRainy(getBiome(x, z), x, y, z)) { strikeLightning(new Location(this, x, y, z)); } } /** * Calculates how much the rays from the location to the entity's bounding box is blocked. * * @param location The location for the rays to start * @param entity The entity that's bounding box is the ray's end point * @return a value between 0 and 1, where 0 = all rays blocked and 1 = all rays unblocked */ public float rayTrace(Location location, GlowEntity entity) { // TODO: calculate how much of the entity is visible (not blocked by blocks) from the location /* * To calculate this step through the entity's bounding box and check whether the ray to the point * in the bounding box is blocked. * * Return (unblockedRays / allRays) */ return 1; } /** * Gets the entity manager. * * @return The entity manager. */ public EntityManager getEntityManager() { return entities; } public Collection<GlowPlayer> getRawPlayers() { return entities.getAll(GlowPlayer.class); } // Entity lists @Override public List<Player> getPlayers() { return new ArrayList<>(entities.getAll(GlowPlayer.class)); } /** * Returns a list of entities within a bounding box centered around a Location. * <p> * Some implementations may impose artificial restrictions on the size of the search bounding box. * * @param location The center of the bounding box * @param x 1/2 the size of the box along x axis * @param y 1/2 the size of the box along y axis * @param z 1/2 the size of the box along z axis * @return the collection of entities near location. This will always be a non-null collection. */ @Override public Collection<Entity> getNearbyEntities(Location location, double x, double y, double z) { Vector minCorner = new Vector(location.getX() - x, location.getY() - y, location.getZ() - z); Vector maxCorner = new Vector(location.getX() + x, location.getY() + y, location.getZ() + z); BoundingBox searchBox = BoundingBox.fromCorners(minCorner, maxCorner); // TODO: test GlowEntity except = null; return entities.getEntitiesInside(searchBox, except); } @Override public List<Entity> getEntities() { return new ArrayList<>(entities.getAll()); } @Override public List<LivingEntity> getLivingEntities() { return entities.getAll().stream().filter(e -> e instanceof GlowLivingEntity).map(e -> (GlowLivingEntity) e).collect(Collectors.toCollection(LinkedList::new)); } @Override @Deprecated @SuppressWarnings("unchecked") public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... classes) { return (Collection<T>) getEntitiesByClasses(classes); } @Override @SuppressWarnings("unchecked") public <T extends Entity> Collection<T> getEntitiesByClass(Class<T> cls) { return entities.getAll().stream().filter(e -> cls.isAssignableFrom(e.getClass())).map(e -> (T) e).collect(Collectors.toCollection(ArrayList::new)); } @Override public Collection<Entity> getEntitiesByClasses(Class<?>... classes) { ArrayList<Entity> result = new ArrayList<>(); for (Entity e : entities.getAll()) { for (Class<?> cls : classes) { if (cls.isAssignableFrom(e.getClass())) { result.add(e); break; } } } return result; } // Various malleable world properties @Override public Location getSpawnLocation() { return spawnLocation.clone(); } @Override public boolean setSpawnLocation(int x, int y, int z) { Location oldSpawn = spawnLocation; Location newSpawn = new Location(this, x, y, z); if (newSpawn.equals(oldSpawn)) { return false; } spawnLocation = newSpawn; setKeepSpawnInMemory(keepSpawnLoaded); EventFactory.callEvent(new SpawnChangeEvent(this, oldSpawn)); return true; } @Override public boolean getPVP() { return pvpAllowed; } @Override public void setPVP(boolean pvp) { pvpAllowed = pvp; } @Override public boolean getKeepSpawnInMemory() { return keepSpawnLoaded; } @Override public void setKeepSpawnInMemory(boolean keepLoaded) { keepSpawnLoaded = keepLoaded; if (spawnChunkLock != null) { // update the chunk lock as needed spawnChunkLock.clear(); if (keepSpawnLoaded) { int centerX = spawnLocation.getBlockX() >> 4; int centerZ = spawnLocation.getBlockZ() >> 4; int radius = 4 * server.getViewDistance() / 3; long loadTime = System.currentTimeMillis(); int total = (radius * 2 + 1) * (radius * 2 + 1), current = 0; for (int x = centerX - radius; x <= centerX + radius; ++x) { for (int z = centerZ - radius; z <= centerZ + radius; ++z) { ++current; if (populateAnchoredChunks) { getChunkManager().forcePopulation(x, z); } else { loadChunk(x, z); } spawnChunkLock.acquire(new Key(x, z)); if (System.currentTimeMillis() >= loadTime + 1000) { int progress = 100 * current / total; GlowServer.logger.info("Preparing spawn for " + name + ": " + progress + "%"); loadTime = System.currentTimeMillis(); } } } } else { // attempt to immediately unload the spawn chunks.unloadOldChunks(); } } } @Override public boolean isAutoSave() { return autosave; } @Override public void setAutoSave(boolean value) { autosave = value; } @Override public Difficulty getDifficulty() { return difficulty; } @Override public void setDifficulty(Difficulty difficulty) { this.difficulty = difficulty; ServerDifficultyMessage message = new ServerDifficultyMessage(difficulty.getValue()); for (GlowPlayer player : getRawPlayers()) { player.getSession().send(message); } } // Entity spawning properties @Override public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { spawnMonsters = allowMonsters; spawnAnimals = allowAnimals; } @Override public boolean getAllowAnimals() { return spawnAnimals; } @Override public boolean getAllowMonsters() { return spawnMonsters; } @Override public long getTicksPerAnimalSpawns() { return ticksPerAnimal; } @Override public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { ticksPerAnimal = ticksPerAnimalSpawns; } @Override public long getTicksPerMonsterSpawns() { return ticksPerMonster; } @Override public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { ticksPerMonster = ticksPerMonsterSpawns; } @Override public int getMonsterSpawnLimit() { return monsterLimit; } @Override public void setMonsterSpawnLimit(int limit) { monsterLimit = limit; } @Override public int getAnimalSpawnLimit() { return animalLimit; } @Override public void setAnimalSpawnLimit(int limit) { animalLimit = limit; } @Override public int getWaterAnimalSpawnLimit() { return waterAnimalLimit; } @Override public void setWaterAnimalSpawnLimit(int limit) { waterAnimalLimit = limit; } @Override public int getAmbientSpawnLimit() { return ambientLimit; } @Override public void setAmbientSpawnLimit(int limit) { ambientLimit = limit; } // Various fixed world properties @Override public Environment getEnvironment() { return environment; } @Override public long getSeed() { return seed; } @Override public UUID getUID() { return uid; } @Override public String getName() { return name; } @Override public int getMaxHeight() { return maxBuildHeight; } @Override public int getSeaLevel() { if (worldType == WorldType.FLAT) { return 4; } else if (environment == Environment.THE_END) { return 50; } else { return SEA_LEVEL; } } @Override public WorldType getWorldType() { return worldType; } @Override public boolean canGenerateStructures() { return generateStructures; } // force-save @Override public void save() { save(false); } public void save(boolean async) { EventFactory.callEvent(new WorldSaveEvent(this)); // save metadata writeWorldData(async); // save chunks maybeAsync(async, () -> { for (GlowChunk chunk : chunks.getLoadedChunks()) { chunks.performSave(chunk); } }); // save players for (GlowPlayer player : getRawPlayers()) { player.saveData(async); } } // map generation @Override public ChunkGenerator getGenerator() { return chunks.getGenerator(); } @Override public List<BlockPopulator> getPopulators() { return populators; } @Override public boolean generateTree(Location location, TreeType type) { return generateTree(location, type, null); } @Override public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { BlockStateDelegate blockStateDelegate = new BlockStateDelegate(); if (GlowTree.newInstance(type, random, loc, blockStateDelegate).generate()) { List<BlockState> blockStates = new ArrayList<>(blockStateDelegate.getBlockStates()); StructureGrowEvent growEvent = new StructureGrowEvent(loc, type, false, null, blockStates); EventFactory.callEvent(growEvent); if (!growEvent.isCancelled()) { for (BlockState state : blockStates) { state.update(true); if (delegate != null) { delegate.setTypeIdAndData(state.getX(), state.getY(), state.getZ(), state.getTypeId(), state.getRawData()); } } return true; } } return false; } public Map<Integer, GlowStructure> getStructures() { return structures; } // get block, chunk, id, highest methods with coords @Override public GlowBlock getBlockAt(int x, int y, int z) { return new GlowBlock(getChunkAt(x >> 4, z >> 4), x, y, z); } @Override public int getBlockTypeIdAt(int x, int y, int z) { return getChunkAt(x >> 4, z >> 4).getType(x & 0xF, z & 0xF, y); } @Override public int getHighestBlockYAt(int x, int z) { return getChunkAt(x >> 4, z >> 4).getHeight(x & 0xf, z & 0xf); } @Override public GlowChunk getChunkAt(int x, int z) { return chunks.getChunk(x, z); } // get block, chunk, id, highest with locations @Override public GlowBlock getBlockAt(Location location) { return getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public int getBlockTypeIdAt(Location location) { return getBlockTypeIdAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public int getHighestBlockYAt(Location location) { return getHighestBlockYAt(location.getBlockX(), location.getBlockZ()); } @Override public Block getHighestBlockAt(int x, int z) { return getBlockAt(x, getHighestBlockYAt(x, z), z); } @Override public Block getHighestBlockAt(Location location) { return getBlockAt(location.getBlockX(), getHighestBlockYAt(location), location.getBlockZ()); } @Override public Chunk getChunkAt(Location location) { return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); } @Override public Chunk getChunkAt(Block block) { return getChunkAt(block.getX() >> 4, block.getZ() >> 4); } @Override public void getChunkAtAsync(int x, int z, ChunkLoadCallback cb) { new Thread() { @Override public void run() { cb.onLoad(chunks.getChunk(x, z)); } }.start(); } @Override public void getChunkAtAsync(Location location, ChunkLoadCallback cb) { getChunkAtAsync(location.getBlockX() >> 4, location.getBlockZ() >> 4, cb); } @Override public void getChunkAtAsync(Block block, ChunkLoadCallback cb) { getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, cb); } // Chunk loading and unloading @Override public boolean isChunkLoaded(Chunk chunk) { return chunk.isLoaded(); } @Override public boolean isChunkLoaded(int x, int z) { return chunks.isChunkLoaded(x, z); } @Override public boolean isChunkInUse(int x, int z) { return chunks.isChunkInUse(x, z); } @Override public Chunk[] getLoadedChunks() { return chunks.getLoadedChunks(); } @Override public void loadChunk(Chunk chunk) { chunk.load(); } @Override public void loadChunk(int x, int z) { getChunkAtAsync(x, z, Chunk::load); } @Override public boolean loadChunk(int x, int z, boolean generate) { return getChunkAt(x, z).load(generate); } @Override public boolean unloadChunk(Chunk chunk) { return chunk.unload(); } @Override public boolean unloadChunk(int x, int z) { return unloadChunk(x, z, true); } @Override public boolean unloadChunk(int x, int z, boolean save) { return unloadChunk(x, z, save, true); } @Override public boolean unloadChunk(int x, int z, boolean save, boolean safe) { return !isChunkLoaded(x, z) || getChunkAt(x, z).unload(save, safe); } @Override public boolean unloadChunkRequest(int x, int z) { return unloadChunkRequest(x, z, true); } @Override public boolean unloadChunkRequest(int x, int z, boolean safe) { if (safe && isChunkInUse(x, z)) return false; server.getScheduler().runTask(null, () -> unloadChunk(x, z, safe)); return true; } @Override public boolean regenerateChunk(int x, int z) { if (!chunks.forceRegeneration(x, z)) return false; refreshChunk(x, z); return true; } @Override public boolean refreshChunk(int x, int z) { if (!isChunkLoaded(x, z)) { return false; } Key key = new Key(x, z); boolean result = false; for (GlowPlayer player : getRawPlayers()) { if (player.canSeeChunk(key)) { player.getSession().send(getChunkAt(x, z).toMessage()); result = true; } } return result; } @Override public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTempRain) { return new EmptySnapshot(x, z, this, includeBiome, includeBiomeTempRain); } // Biomes @Override public Biome getBiome(int x, int z) { if (environment == Environment.THE_END) { return Biome.SKY; } else if (environment == Environment.NETHER) { return Biome.HELL; } return GlowBiome.getBiome(getChunkAt(x >> 4, z >> 4).getBiome(x & 0xF, z & 0xF)); } @Override public void setBiome(int x, int z, Biome bio) { getChunkAtAsync(x, z, chunk -> ((GlowChunk) chunk).setBiome(x & 0xF, z & 0xF, GlowBiome.getId(bio))); } @Override public double getTemperature(int x, int z) { return GlowBiomeClimate.getBiomeTemperature(getBiome(x, z)); } @Override public double getHumidity(int x, int z) { return GlowBiomeClimate.getBiomeHumidity(getBiome(x, z)); } // Entity spawning @Override public <T extends Entity> T spawn(Location location, Class<T> clazz) throws IllegalArgumentException { return spawn(location, clazz, SpawnReason.CUSTOM); } public <T extends Entity> T spawn(Location location, Class<T> clazz, SpawnReason reason) throws IllegalArgumentException { GlowEntity entity = null; if (TNTPrimed.class.isAssignableFrom(clazz)) { entity = new GlowTNTPrimed(location, null); } if (entity == null) { try { Constructor<T> constructor = clazz.getConstructor(Location.class); entity = (GlowEntity) constructor.newInstance(location); CreatureSpawnEvent spawnEvent = new CreatureSpawnEvent((LivingEntity) entity, reason); if (!spawnEvent.isCancelled()) { entity.createSpawnMessage(); } else { // TODO: separate spawning and construction for better event cancellation entity.remove(); } } catch (NoSuchMethodException e) { GlowServer.logger.log(Level.WARNING, "Invalid entity spawn: ", e); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { GlowServer.logger.log(Level.SEVERE, "Unable to spawn entity: ", e); } } if (entity != null) { @SuppressWarnings("unchecked") T result = (T) entity; return result; } throw new UnsupportedOperationException("Not supported yet."); } @Override public GlowItem dropItem(Location location, ItemStack item) { return new GlowItem(location, item); } @Override public GlowItem dropItemNaturally(Location location, ItemStack item) { double xs = random.nextFloat() * 0.7F + (1.0F - 0.7F) * 0.5D; double ys = random.nextFloat() * 0.7F + (1.0F - 0.7F) * 0.5D; double zs = random.nextFloat() * 0.7F + (1.0F - 0.7F) * 0.5D; location = location.clone().add(xs, ys, zs); GlowItem dropItem = new GlowItem(location, item); dropItem.setVelocity(new Vector(0, 0.1F, 0)); return dropItem; } @Override public Arrow spawnArrow(Location location, Vector velocity, float speed, float spread) { Arrow arrow = spawn(location, Arrow.class); // Transformative magic Vector randVec = new Vector(random.nextGaussian(), random.nextGaussian(), random.nextGaussian()); randVec.multiply(0.0075 * spread); velocity.normalize(); velocity.add(randVec); velocity.multiply(speed); // yaw = Math.atan2(x, z) * 180.0D / 3.1415927410125732D; // pitch = Math.atan2(y, Math.sqrt(x * x + z * z)) * 180.0D / 3.1415927410125732D arrow.setVelocity(velocity); return arrow; } @Override public <T extends Arrow> T spawnArrow(Location location, Vector vector, float v, float v1, Class<T> aClass) { return null; } @Override public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { if (location == null || material == null) { throw new IllegalArgumentException(); } return new GlowFallingBlock(location, material, data); } @Override public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException { Material material = Material.getMaterial(blockId); return spawnFallingBlock(location, material, blockData); } @Override public Entity spawnEntity(Location loc, EntityType type) { return spawn(loc, type.getEntityClass()); } private GlowLightningStrike strikeLightningFireEvent(Location loc, boolean effect) { GlowLightningStrike strike = new GlowLightningStrike(loc, effect, random); LightningStrikeEvent event = new LightningStrikeEvent(this, strike); if (EventFactory.callEvent(event).isCancelled()) { return null; } return strike; } @Override public GlowLightningStrike strikeLightning(Location loc) { return strikeLightningFireEvent(loc, false); } @Override public GlowLightningStrike strikeLightningEffect(Location loc) { return strikeLightningFireEvent(loc, true); } // Time @Override public long getTime() { return time; } @Override public void setTime(long time) { this.time = (time % DAY_LENGTH + DAY_LENGTH) % DAY_LENGTH; getRawPlayers().forEach(GlowPlayer::sendTime); } @Override public long getFullTime() { return worldAge; } @Override public void setFullTime(long time) { worldAge = time; } // Weather @Override public boolean hasStorm() { return currentlyRaining; } @Override public void setStorm(boolean hasStorm) { // call event WeatherChangeEvent event = new WeatherChangeEvent(this, hasStorm); if (EventFactory.callEvent(event).isCancelled()) { return; } // change weather boolean previouslyRaining = currentlyRaining; currentlyRaining = hasStorm; // Numbers borrowed from CraftBukkit. if (currentlyRaining) { setWeatherDuration(random.nextInt(HALF_DAY_IN_TICKS) + HALF_DAY_IN_TICKS); } else { setWeatherDuration(random.nextInt(WEEK_IN_TICKS) + HALF_DAY_IN_TICKS); } // update players if (previouslyRaining != currentlyRaining) { getRawPlayers().forEach(GlowPlayer::sendWeather); } } @Override public int getWeatherDuration() { return rainingTicks; } @Override public void setWeatherDuration(int duration) { rainingTicks = duration; } @Override public boolean isThundering() { return currentlyThundering; } @Override public void setThundering(boolean thundering) { // call event ThunderChangeEvent event = new ThunderChangeEvent(this, thundering); if (EventFactory.callEvent(event).isCancelled()) { return; } // change weather currentlyThundering = thundering; // Numbers borrowed from CraftBukkit. if (currentlyThundering) { setThunderDuration(random.nextInt(HALF_DAY_IN_TICKS) + 180 * TICKS_PER_SECOND); } else { setThunderDuration(random.nextInt(WEEK_IN_TICKS) + HALF_DAY_IN_TICKS); } } @Override public int getThunderDuration() { return thunderingTicks; } @Override public void setThunderDuration(int duration) { thunderingTicks = duration; } public float getRainDensity() { return currentRainDensity; } public float getSkyDarkness() { return currentSkyDarkness; } private void updateWeather() { float previousRainDensity = currentRainDensity; float previousSkyDarkness = currentSkyDarkness; float rainDensityModifier = currentlyRaining ? .01F : -.01F; float skyDarknessModifier = currentlyThundering ? .01F : -.01F; currentRainDensity = Math.max(0, Math.min(1, previousRainDensity + rainDensityModifier)); currentSkyDarkness = Math.max(0, Math.min(1, previousSkyDarkness + skyDarknessModifier)); if (previousRainDensity != currentRainDensity) { getRawPlayers().forEach(GlowPlayer::sendRainDensity); } if (previousSkyDarkness != currentSkyDarkness) { getRawPlayers().forEach(GlowPlayer::sendSkyDarkness); } } // Explosions @Override public boolean createExplosion(Location loc, float power) { return createExplosion(loc, power, false); } @Override public boolean createExplosion(Location loc, float power, boolean setFire) { return createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire, true); } @Override public boolean createExplosion(double x, double y, double z, float power) { return createExplosion(x, y, z, power, false, true); } @Override public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { return createExplosion(x, y, z, power, setFire, true); } @Override public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { return createExplosion(null, x, y, z, power, setFire, breakBlocks); } /** * Create an explosion with a specific entity as the source. * * @param source The entity to treat as the source, or null. * @param x X coordinate * @param y Y coordinate * @param z Z coordinate * @param power The power of explosion, where 4F is TNT * @param incendiary Whether or not to set blocks on fire * @param breakBlocks Whether or not to have blocks be destroyed * @return false if explosion was canceled, otherwise true */ public boolean createExplosion(Entity source, double x, double y, double z, float power, boolean incendiary, boolean breakBlocks) { Explosion explosion = new Explosion(source, this, x, y, z, power, incendiary, breakBlocks); return explosion.explodeWithEvent(); } // Effects @Override public void playEffect(Location location, Effect effect, int data) { playEffect(location, effect, data, 64); } @Override public void playEffect(Location location, Effect effect, int data, int radius) { int radiusSquared = radius * radius; getRawPlayers().stream().filter(player -> player.getLocation().distanceSquared(location) <= radiusSquared).forEach(player -> player.playEffect(location, effect, data)); } @Override public <T> void playEffect(Location location, Effect effect, T data) { playEffect(location, effect, data, 64); } @Override public <T> void playEffect(Location location, Effect effect, T data, int radius) { playEffect(location, effect, GlowEffect.getDataValue(effect, data), radius); } public void playEffectExceptTo(Location location, Effect effect, int data, int radius, Player exclude) { int radiusSquared = radius * radius; getRawPlayers().stream().filter(player -> !player.equals(exclude) && player.getLocation().distanceSquared(location) <= radiusSquared).forEach(player -> player.playEffect(location, effect, data)); } @Override public void playSound(Location location, Sound sound, float volume, float pitch) { if (location == null || sound == null) return; double radiusSquared = Math.pow(volume * 16, 2); getRawPlayers().stream().filter(player -> player.getLocation().distanceSquared(location) <= radiusSquared).forEach(player -> player.playSound(location, sound, volume, pitch)); } @Override public void playSound(Location location, String s, float v, float v1) { } private void playEffect_(Location location, Effect effect, int data) { // fix name collision playEffect(location, effect, data); } @Override public Spigot spigot() { return spigot; } //@Override public void showParticle(Location loc, Effect particle, float offsetX, float offsetY, float offsetZ, float speed, int amount) { int radius; if (GlowParticle.isLongDistance(particle)) { radius = 48; } else { radius = 16; } showParticle(loc, particle, particle.getId(), 0, offsetX, offsetY, offsetZ, speed, amount, radius); } //@Override public void showParticle(Location loc, Effect particle, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int amount, int radius) { if (loc == null || particle == null) return; double radiusSquared = radius * radius; getRawPlayers().stream().filter(player -> player.getLocation().distanceSquared(loc) <= radiusSquared).forEach(player -> player.spigot().playEffect(loc, particle, id, data, offsetX, offsetY, offsetZ, speed, amount, radius)); } /** * Save the world data using the metadata service. * * @param async Whether to write asynchronously. */ private void writeWorldData(boolean async) { maybeAsync(async, () -> { try { storageProvider.getMetadataService().writeWorldData(); storageProvider.getScoreboardIoService().save(); } catch (IOException e) { server.getLogger().severe("Could not save metadata for world: " + getName()); e.printStackTrace(); } storageProvider.getStructureDataService().writeStructuresData(structures); }); } // Level data write /** * Execute a runnable, optionally asynchronously. * * @param async Whether to run the runnable in an asynchronous task. * @param runnable The runnable to run. */ private void maybeAsync(boolean async, Runnable runnable) { if (async) { server.getScheduler().runTaskAsynchronously(null, runnable); } else { runnable.run(); } } /** * Unloads the world * * @return true if successful */ public boolean unload() { EventFactory.callEvent(new WorldUnloadEvent(this)); try { storageProvider.getChunkIoService().unload(); storageProvider.getScoreboardIoService().unload(); } catch (IOException e) { return false; } return true; } /** * Get the storage provider for the world. * * @return The {@link WorldStorageProvider}. */ public WorldStorageProvider getStorage() { return storageProvider; } /** * Get the world folder. * * @return world folder */ @Override public File getWorldFolder() { return storageProvider.getFolder(); } @Override public String[] getGameRules() { return gameRules.getKeys(); } // Game rules @Override public String getGameRuleValue(String rule) { return gameRules.getString(rule); } @Override public boolean setGameRuleValue(String rule, String value) { if (!gameRules.setValue(rule, value)) { return false; } if (rule.equals("doDaylightCycle")) { // inform clients about the daylight cycle change getRawPlayers().forEach(GlowPlayer::sendTime); } else if (rule.equals("reducedDebugInfo")) { // inform clients about the debug info change EntityStatusMessage message = new EntityStatusMessage(0, gameRules.getBoolean("reducedDebugInfo") ? EntityStatusMessage.ENABLE_REDUCED_DEBUG_INFO : EntityStatusMessage.DISABLE_REDUCED_DEBUG_INFO); for (GlowPlayer player : getRawPlayers()) { player.getSession().send(message); } } return true; } @Override public boolean isGameRule(String rule) { return gameRules.isGameRule(rule); } @Override public WorldBorder getWorldBorder() { return null; } @Override public void spawnParticle(Particle particle, Location location, int i) { } @Override public void spawnParticle(Particle particle, double v, double v1, double v2, int i) { } @Override public <T> void spawnParticle(Particle particle, Location location, int i, T t) { } @Override public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, T t) { } @Override public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2) { } @Override public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5) { } @Override public <T> void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, T t) { } @Override public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, T t) { } @Override public void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3) { } @Override public void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6) { } @Override public <T> void spawnParticle(Particle particle, Location location, int i, double v, double v1, double v2, double v3, T t) { } @Override public <T> void spawnParticle(Particle particle, double v, double v1, double v2, int i, double v3, double v4, double v5, double v6, T t) { } public GameRuleManager getGameRuleMap() { return gameRules; } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { metadata.setMetadata(this, metadataKey, newMetadataValue); } // Metadata @Override public List<MetadataValue> getMetadata(String metadataKey) { return metadata.getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { return metadata.hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { metadata.removeMetadata(this, metadataKey, owningPlugin); } @Override public void sendPluginMessage(Plugin source, String channel, byte[] message) { StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message); for (Player player : getRawPlayers()) { player.sendPluginMessage(source, channel, message); } } // Plugin messages @Override public Set<String> getListeningPluginChannels() { HashSet<String> result = new HashSet<>(); for (Player player : getRawPlayers()) { result.addAll(player.getListeningPluginChannels()); } return result; } private void pulseTickMap() { ItemTable itemTable = ItemTable.instance(); getTickMap().entrySet().stream().filter(entry -> worldAge % entry.getValue().getKey() == 0).forEach(entry -> { GlowBlock block = getBlockAt(entry.getKey()); BlockType notifyType = itemTable.getBlock(block.getTypeId()); if (notifyType != null) { notifyType.receivePulse(block); } if (entry.getValue().getValue()) { cancelPulse(block); } }); } private ConcurrentHashMap<Location, Map.Entry<Long, Boolean>> getTickMap() { return tickMap; } /** * Calling this method will request that the block is ticked on the next iteration * that applies to the specified tick rate. * * @param block The block to tick. * @param tickRate The tick rate to tick the block at. * @param single Whether to tick once. */ public void requestPulse(GlowBlock block, long tickRate, boolean single) { Location target = block.getLocation(); if (tickRate > 0) { tickMap.put(target, new AbstractMap.SimpleEntry<>(tickRate, single)); } else if (tickMap.containsKey(target)) { tickMap.remove(target); } } /** * Calling this method will request that the block is ticked on the next iteration * that applies to the specified tick rate. * * @param block The block to tick. * @param tickRate The tick rate to tick the block at. */ public void requestPulse(GlowBlock block, long tickRate) { Location target = block.getLocation(); if (tickRate > 0) { tickMap.put(target, new AbstractMap.SimpleEntry<>(tickRate, false)); } else if (tickMap.containsKey(target)) { tickMap.remove(target); } } public void cancelPulse(GlowBlock block) { requestPulse(block, 0); } @Override public int hashCode() { return getUID().hashCode(); } @Override public boolean equals(Object obj) { return obj == this; } /** * The metadata store class for worlds. */ private static final class WorldMetadataStore extends MetadataStoreBase<World> implements MetadataStore<World> { @Override protected String disambiguate(World subject, String metadataKey) { return subject.getName() + ":" + metadataKey; } } }
package net.odbogm; import com.orientechnologies.orient.core.metadata.sequence.OSequenceLibrary; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.impls.orient.OrientEdge; import com.tinkerpop.blueprints.impls.orient.OrientElement; import com.tinkerpop.blueprints.impls.orient.OrientVertex; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import net.odbogm.annotations.Indirect; import net.odbogm.cache.ClassCache; import net.odbogm.cache.ClassDef; import net.odbogm.exceptions.CollectionNotSupported; import net.odbogm.proxy.ArrayListEmbeddedProxy; import net.odbogm.proxy.HashMapEmbeddedProxy; import net.odbogm.proxy.ILazyCollectionCalls; import net.odbogm.proxy.ILazyMapCalls; import net.odbogm.proxy.IObjectProxy; import net.odbogm.proxy.ObjectProxyFactory; public class ObjectMapper { private final static Logger LOGGER = Logger.getLogger(ObjectMapper.class.getName()); static { if (LOGGER.getLevel() == null) { LOGGER.setLevel(LogginProperties.ObjectMapper); } } private final ClassCache classCache; public ObjectMapper() { classCache = new ClassCache(); } public ClassDef getClassDef(Object o) { if (o instanceof IObjectProxy) { return classCache.get(((IObjectProxy) o).___getBaseClass()); } else { return classCache.get(o.getClass()); } } public ClassDef getClassDef(Class cls) { return classCache.get(cls); } public Map<String, Object> simpleMap(Object o) { HashMap<String, Object> data = new HashMap<>(); if (Primitives.PRIMITIVE_MAP.containsKey(o.getClass())) { data.put("key", o); } else { ClassDef classmap = classCache.get(o.getClass()); simpleFastMap(o, classmap, data); } return data; } private void simpleFastMap(Object o, ClassDef classmap, HashMap<String, Object> data) { classmap.fields.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); putValue(data, f, o, null); }); classmap.enumFields.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); putValue(data, f, o, v -> ((Enum)v).name()); }); } /** * Fills the sequence fields with the values of the corresponding sequences * from the DB. * * @param o * @param t * @param v If not null, sets also its corresponding property. */ public void fillSequenceFields(Object o, Transaction t, OrientVertex v) { ClassDef classdef = this.classCache.get(o.getClass()); if (!classdef.sequenceFields.isEmpty()) { OSequenceLibrary seqLibrary = t.getCurrentGraphDb().getRawGraph().getMetadata().getSequenceLibrary(); classdef.sequenceFields.entrySet().forEach(e -> { Field f = classdef.fieldsObject.get(e.getKey()); if (this.getFieldValue(o, f) == null) { Long seqVal = seqLibrary.getSequence(e.getValue()).next(); this.setFieldValue(o, f, seqVal); if (v != null) v.setProperty(e.getKey(), seqVal); } }); } } /** * Devuelve un Map con todos los K,V de cada campo del objeto. * * @param o objeto a analizar * @return un objeto con la estructura del objeto analizado. */ public ObjectStruct objectStruct(Object o) { ClassDef classmap; if (o instanceof IObjectProxy) { LOGGER.log(Level.FINEST, "Proxy instance. Seaching the orignal class... ({0})", o.getClass().getSuperclass().getSimpleName()); classmap = classCache.get(o.getClass().getSuperclass()); } else { LOGGER.log(Level.FINEST, "Searching the class... ({0})", o.getClass().getSimpleName()); classmap = classCache.get(o.getClass()); } ObjectStruct oStruct = new ObjectStruct(); this.fastmap(o, classmap, oStruct); return oStruct; } private void fastmap(Object o, ClassDef classmap, ObjectStruct oStruct) { // procesar todos los campos classmap.fields.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); boolean put = putValue(oStruct.fields, f, o, null); if (!put) oStruct.removedProperties.add(entry.getKey()); }); // procesar todos los Enums classmap.enumFields.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); boolean put = putValue(oStruct.fields, f, o, v -> ((Enum)v).name()); if (!put) oStruct.removedProperties.add(entry.getKey()); }); // procesar todas las colecciones de Enums classmap.enumCollectionFields.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); boolean put = putValue(oStruct.fields, f, o, v -> ((Collection)v).stream(). map(e -> ((Enum)e).name()).collect(Collectors.toList())); if (!put) oStruct.removedProperties.add(entry.getKey()); }); // procesar todos los links classmap.links.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); putValue(oStruct.links, f, o, null); }); // procesar todos los linksList classmap.linkLists.entrySet().stream().forEach(entry -> { Field f = classmap.fieldsObject.get(entry.getKey()); putValue(oStruct.linkLists, f, o, null); }); } /** * Saves in the attributes map 'valuesMap' the value that the object 'o' * has in its attribute given by the field 'f', applying the transform if * given. Returns false if the value is null. */ private boolean putValue(Map valuesMap, Field f, Object o, Function transform) { try { Object value = f.get(o); LOGGER.log(Level.FINER, "Field: {0}. Class: {1}. Value: {2}", new Object[]{f.getName(), f.getType().getSimpleName(), value}); if (value != null) { valuesMap.put(f.getName(), transform != null ? transform.apply(value) : value); } return value != null; } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, "Couldn't get attribute value", ex); return true; } } public <T> T hydrate(Class<T> c, OrientVertex v, Transaction t) throws InstantiationException, IllegalAccessException, NoSuchFieldException, CollectionNotSupported { t.initInternalTx(); LOGGER.log(Level.FINER, "class: {0} vertex: {1}", new Object[]{c, v}); Class<?> toHydrate = c; String entityClass = ClassCache.getEntityName(toHydrate); String vertexClass = (v.getType().getName().equals("V") ? entityClass : v.getType().getName()); // validar que el Vertex sea instancia de la clase solicitada // o que la clase solicitada sea su superclass if (!entityClass.equals(vertexClass)) { LOGGER.log(Level.FINER, "Tipos distintos. {0} <> {1}", new Object[]{entityClass, vertexClass}); String javaClass = v.getType().getCustom("javaClass"); if (javaClass != null) { try { javaClass = javaClass.replaceAll("[\'\"]", ""); toHydrate = Class.forName(javaClass); } catch (ClassNotFoundException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, null, ex); } } else { throw new InstantiationException("ERROR de Instanciación! \n" + "El vértice no coincide con la clase que se está intentando instanciar\n" + "y no tiene definido la propiedad javaClass."); } } // crear un proxy sobre el objeto y devolverlo IObjectProxy proxy = (IObjectProxy)ObjectProxyFactory.create(toHydrate, v, t); LOGGER.log(Level.FINER, "**************************************************"); LOGGER.log(Level.FINER, "Hydratando: {0} - Class: {1}", new Object[]{c.getName(), toHydrate}); LOGGER.log(Level.FINER, "**************************************************"); ClassDef classdef = classCache.get(toHydrate); Field f; for (var entry : classdef.fields.entrySet()) { String prop = entry.getKey(); if (!classdef.embeddedFields.containsKey(prop)) { LOGGER.log(Level.FINER, "Buscando campo {0} de tipo {1}...", new String[]{prop, entry.getValue().getSimpleName()}); this.setFieldValue(proxy, prop, v.getProperty(prop)); } } //version field proxy.___uptadeVersion(); // insertar el objeto en el transactionLoopCache t.transactionLoopCache.put(v.getId().toString(), proxy); // process embedded collections hydrateEmbeddedCollections(classdef, proxy, v); // procesar los enum for (Map.Entry<String, Class<?>> entry : classdef.enumFields.entrySet()) { String prop = entry.getKey(); LOGGER.log(Level.FINER, "Buscando campo {0} ....", new String[]{prop}); f = classdef.fieldsObject.get(prop); Object value = v.getProperty(prop); LOGGER.log(Level.FINER, "Enum field: {0} type: {1} value: {2}", new Object[]{f.getName(), f.getType(), value}); setEnumField(proxy, f, value); LOGGER.log(Level.FINER, "hidratado campo: {0}={1}", new Object[]{prop, value}); } // procesar colecciones de enums hydrateEnumCollections(classdef, proxy, v); // hidratar las colecciones // procesar todos los linkslist LOGGER.log(Level.FINER, "preparando las colecciones..."); hydrateLinkCollections(t, classdef, proxy, v, false); // hidratar las colecciones indirectas // procesar todos los indirectLinkslist LOGGER.log(Level.FINER, "hidratar las colecciones indirectas..."); hydrateLinkCollections(t, classdef, proxy, v, true); LOGGER.log(Level.FINER, "******************* FIN HYDRATE *******************"); t.closeInternalTx(); return (T) proxy; } /** * Given a vertex from the base (or edge), hydrate the embedded collections of * the given proxy accordingly to the values of the vertex. * * @param classdef Class definition of the object to hydrate. * @param proxy The proxy. * @param v An OrientDB element (vertex or edge). */ public void hydrateEmbeddedCollections(ClassDef classdef, IObjectProxy proxy, OrientElement v) { Field f; for (Map.Entry<String, Class<?>> entry : classdef.embeddedFields.entrySet()) { String prop = entry.getKey(); Object vertexValue = v.getProperty(prop); f = classdef.fieldsObject.get(prop); if (vertexValue != null) { collectionToEmbedded(proxy, f, vertexValue); } else { /* if the node doesn't have a value, respect the initial value of the attribute * in the class: * null -> null * empty collection -> empty proxy collection */ if (getFieldValue(proxy, f) != null) { collectionToEmbedded(proxy, f); } else { setFieldValue(proxy, prop, null); } } } } /** * Given a vertex from the base (or edge), hydrate the enums collections of the given * proxy accordingly to the values of the vertex. * * @param classdef Class definition of the object to hydrate. * @param proxy The proxy. * @param v An OrientDB element (vertex or edge). */ public void hydrateEnumCollections(ClassDef classdef, IObjectProxy proxy, OrientElement v) { Field f; for (Map.Entry<String, Class<?>> entry : classdef.enumCollectionFields.entrySet()) { String prop = entry.getKey(); List vertexValue = (List)v.getProperty(prop); f = classdef.fieldsObject.get(prop); if (vertexValue != null) { //replace all values by the correspoinding enum: Class<?> listClass = getListType(f); List enumList = new ArrayList(vertexValue.size()); for (int i = 0; i < vertexValue.size(); ++i) { if (vertexValue.get(i) instanceof String) { //only convert to enum if the value in the list is a String String sVal = (String)vertexValue.get(i); enumList.add(Enum.valueOf(listClass.asSubclass(Enum.class), sVal)); } } setFieldValue(proxy, prop, new ArrayListEmbeddedProxy(proxy, enumList)); } else { /* if the node doesn't have a value, respect the initial value of the attribute * in the class: * null -> null * empty list -> empty proxy list */ if (getFieldValue(proxy, f) != null) { setFieldValue(proxy, f, new ArrayListEmbeddedProxy(proxy, new ArrayList())); } else { setFieldValue(proxy, prop, null); } } } } private void hydrateLinkCollections(Transaction t, ClassDef classdef, IObjectProxy proxy, OrientVertex v, boolean indirect) { Map<String, Class<?>> links; Direction relationDirection; if (indirect) { links = classdef.indirectLinkLists; relationDirection = Direction.IN; } else { links = classdef.linkLists; relationDirection = Direction.OUT; } Field fLink; for (Map.Entry<String, Class<?>> entry : links.entrySet()) { try { String field = entry.getKey(); Class<?> fc = entry.getValue(); LOGGER.log(Level.FINER, "Field: {0} Class: {1}", new String[]{field, fc.getName()}); fLink = classdef.fieldsObject.get(field); String graphRelationName; if (indirect) { Indirect in = fLink.getAnnotation(Indirect.class); graphRelationName = in.linkName(); } else { graphRelationName = classdef.entityName + "_" + field; } if ((v.countEdges(relationDirection, graphRelationName) > 0) || (fLink.get(proxy) != null)) { this.collectionToLazy(proxy, field, fc, v, t); } } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, null, ex); } } } public void collectionToLazy(Object o, String field, OrientVertex v, Transaction t) { LOGGER.log(Level.FINER, "convertir colection a Lazy: {0}", field); ClassDef classdef; if (o instanceof IObjectProxy) { classdef = classCache.get(o.getClass().getSuperclass()); } else { classdef = classCache.get(o.getClass()); } Class<?> fc = classdef.linkLists.get(field); collectionToLazy(o, field, fc, v, t); } /** * Dado un Field correspondiente a una lista, devuelve la clase de los * elementos que contiene la lista. */ private Class<?> getListType(Field listField) { ParameterizedType listType = (ParameterizedType) listField.getGenericType(); return (Class<?>) listType.getActualTypeArguments()[0]; } private void collectionToLazy(Object o, String field, Class<?> fc, OrientVertex v, Transaction t) { LOGGER.log(Level.FINER, "***************************************************************"); LOGGER.log(Level.FINER, "convertir colection a Lazy: " + field + " class: " + fc.getName()); LOGGER.log(Level.FINER, "***************************************************************"); try { Class<?> c; if (o instanceof IObjectProxy) { c = o.getClass().getSuperclass(); } else { c = o.getClass(); } ClassDef classdef = classCache.get(c); Field fLink = classdef.fieldsObject.get(field); String graphRelationName = classdef.entityName + "_" + field; Direction direction = Direction.OUT; if (fLink.isAnnotationPresent(Indirect.class)) { // el propuesto por la anotation Indirect in = fLink.getAnnotation(Indirect.class); graphRelationName = in.linkName(); direction = Direction.IN; } Class<?> lazyClass = Primitives.LAZY_COLLECTION.get(fc); LOGGER.log(Level.FINER, "lazyClass: {0}", lazyClass.getName()); Object col = lazyClass.newInstance(); // dependiendo de si la clase hereda de Map o List, inicalizar if (col instanceof List) { Class<?> listClass = getListType(fLink); ((ILazyCollectionCalls) col).init(t, v, (IObjectProxy) o, graphRelationName, listClass, direction); } else if (col instanceof Map) { ParameterizedType listType = (ParameterizedType) fLink.getGenericType(); Class<?> keyClass = (Class<?>) listType.getActualTypeArguments()[0]; Class<?> valClass = (Class<?>) listType.getActualTypeArguments()[1]; ((ILazyMapCalls) col).init(t, v, (IObjectProxy) o, graphRelationName, keyClass, valClass, direction); } else { throw new CollectionNotSupported(); } fLink.set(o, col); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | InstantiationException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, null, ex); } } /** * Convierte todas las colecciones identificadas como embedded en el ClassDef a sus correspondientes proxies * * @param o the object to be analyzed * @param classDef the class struct */ public void collectionsToEmbedded(Object o, ClassDef classDef) { classDef.embeddedFields.entrySet().forEach(entry -> collectionToEmbedded(o, classDef, entry.getKey())); classDef.enumCollectionFields.entrySet().forEach(entry -> collectionToEmbedded(o, classDef, entry.getKey())); } /** * Converts the value of a field into an embedded proxy collection if of correct type. */ private void collectionToEmbedded(Object o, ClassDef classDef, String field) { Field f = classDef.fieldsObject.get(field); try { collectionToEmbedded(o, f, f.get(o)); } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, "Error converting collections to embedded", ex); } } /** * Converts the value of a field into an embedded proxy collection if of correct type. */ private void collectionToEmbedded(Object o, Field f, Object value) { try { LOGGER.log(Level.FINER, "Procesando campo: {0} type: {1}", new String[]{f.getName(), f.getType().getName()}); if (value != null && List.class.isAssignableFrom(f.getType())) { LOGGER.log(Level.FINER, "convirtiendo en ArrayListEmbeddedProxy..."); f.set(o, new ArrayListEmbeddedProxy((IObjectProxy)o, (List)value)); } else if (value != null && Map.class.isAssignableFrom(f.getType())) { LOGGER.log(Level.FINER, "convirtiendo en HashMapEmbeddedProxy"); f.set(o, new HashMapEmbeddedProxy((IObjectProxy)o, (Map)value)); } } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, "Error converting collections to embedded", ex); } } /** * Sets the value of a field into an empty embedded proxy collection. */ private void collectionToEmbedded(Object o, Field f) { try { LOGGER.log(Level.FINER, "Processing field: {0} type: {1}", new String[]{f.getName(), f.getType().getName()}); if (List.class.isAssignableFrom(f.getType())) { LOGGER.log(Level.FINER, "converting into empty ArrayListEmbeddedProxy..."); f.set(o, new ArrayListEmbeddedProxy((IObjectProxy)o, new ArrayList())); } else if (Map.class.isAssignableFrom(f.getType())) { LOGGER.log(Level.FINER, "converting into empty HashMapEmbeddedProxy..."); f.set(o, new HashMapEmbeddedProxy((IObjectProxy)o, new HashMap())); } } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectMapper.class.getName()).log(Level.SEVERE, "Error converting collections to embedded", ex); } } public <T> T hydrate(Class<T> c, OrientEdge e, Transaction t) throws InstantiationException, IllegalAccessException, NoSuchFieldException { T oproxied = ObjectProxyFactory.create(c, e, t); ClassDef classdef = classCache.get(c); Field f; for (String prop : e.getPropertyKeys()) { Object value = e.getProperty(prop); if (value != null) { f = classdef.fieldsObject.get(prop); // obtener la clase a la que pertenece el campo // puede darse el caso que la base cree un atributo sobre los registros (ej: @rid) Class<?> fc = classdef.fields.get(prop); if (fc != null) { setFieldValue(oproxied, f, value); } else { fc = classdef.enumFields.get(prop); if (fc != null) { setEnumField(oproxied, f, value); } } } } return oproxied; } public Object getFieldValue(Object o, Field field) { try { return field.get(o); } catch (IllegalArgumentException | IllegalAccessException ex) { LOGGER.log(Level.SEVERE, "Error getting value for " + field, ex); return null; } } public void setFieldValue(Object o, Field field, Object value) { try { field.set(o, value); } catch (IllegalArgumentException | IllegalAccessException ex) { LOGGER.log(Level.SEVERE, "Error setting value for " + field, ex); } } public void setFieldValue(Object o, String field, Object value) { try { Field f = this.classCache.get(o.getClass()).fieldsObject.get(field); f.set(o, value); } catch (IllegalArgumentException | IllegalAccessException ex) { LOGGER.log(Level.SEVERE, "Error setting value for " + field, ex); } } public void setEnumField(Object o, Field field, Object value) { try { if (value != null && value.toString() != null && !value.toString().isBlank()) { field.set(o, Enum.valueOf(field.getType().asSubclass(Enum.class), value.toString())); } } catch (IllegalArgumentException | IllegalAccessException ex) { LOGGER.log(Level.SEVERE, "Error setting enum value for " + field, ex); } } }
package ninja.joshdavis; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.ConcurrentLinkedQueue; import com.ning.http.client.*; import com.ning.http.client.extra.*; import org.jsoup.*; import org.jsoup.nodes.*; import org.jsoup.select.*; public class Crawler { private AsyncHttpClient client; private ConcurrentLinkedQueue<String> queue; private HashSet<String> seen; private HashSet<Future<Response>> processing; class ThrottledHandler extends AsyncCompletionHandler<Response>{ String url; public ThrottledHandler(String _url) { url = _url; } @Override public Response onCompleted(Response response) throws Exception{ // Do something with the Response String url = response.getUri().toString(); String html = response.getResponseBody(); Document doc = Jsoup.parse(html, url); Elements links = doc.select("a[href]"); for(Element link: links) { String link_url; if((link_url = link.attr("abs:href")) != null) { enqueue_request(link_url); } } System.out.println("Request completed: " + url); return response; } @Override public void onThrowable(Throwable t){ System.out.println("Failed: " + url); System.out.println(t); } } public Crawler(Collection<String> urls) { //Create the client AsyncHttpClientConfig.Builder b = new AsyncHttpClientConfig.Builder().addRequestFilter(new ThrottleRequestFilter(100)); client = new AsyncHttpClient(b.build()); //Init book-keeping data structures queue = new ConcurrentLinkedQueue<String>(); seen = new HashSet<String>(urls.size()); processing = new HashSet<Future<Response>>(urls.size()); //Fill the to-be-scheduled queue with initial inputs for(String url: urls) { enqueue_request(url); } } private void enqueue_request(String url) { if(!seen.contains(url)) { seen.add(url); queue.add(url); } } private void request(String url) { System.out.println("Requesting: "+url); Future<Response> f = this.client.prepareGet(url).execute(new ThrottledHandler(url)); processing.add(f); } private boolean notDone() {//Done when both queue and processing are empty return !(queue.isEmpty() & processing.isEmpty()); } private void schedule_next_request() { String url = queue.poll(); if(url != null) { request(url); } } private void cleanup_finished_tasks() { HashSet<Future<Response>> done = new HashSet<Future<Response>>();//TODO:Initial size? for(Future<Response> f: processing) { if(f.isDone()) done.add(f); } for(Future<Response> f: done) { processing.remove(f); } } public void crawl() { while(notDone()) { //print_status(); schedule_next_request(); cleanup_finished_tasks(); } client.close(); } public void print_status() { System.out.println("In queue: " + queue.size()); System.out.println("In process: " + processing.size()); System.out.println("Have seen: " + seen.size()); } }
package nuclibook.models; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import nuclibook.server.Renderable; import java.util.HashMap; @DatabaseTable(tableName = "cameras") public class Camera implements Renderable { @DatabaseField(generatedId = true) private Integer id; @DatabaseField(columnName = "camera_type_id", canBeNull = false, foreign = true, foreignAutoRefresh = true) private CameraType type; @DatabaseField(canBeNull = false) private String roomNumber; @DatabaseField(defaultValue = "true") private Boolean enabled; public Camera() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public CameraType getType() { return type; } public void setType(CameraType type) { this.type = type; } public String getRoomNumber() { return roomNumber; } public void setRoomNumber(String roomNumber) { this.roomNumber = roomNumber; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } @Override public HashMap<String, String> getHashMap() { return new HashMap<String, String>(){{ put("id", getId().toString()); put("camera-id", getId().toString()); put("camera-type-id", getType().getId().toString()); put("camera-type-label", getType().getLabel()); put("room-number", getRoomNumber()); }}; } }
package org.lantern; import com.google.common.eventbus.Subscribe; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListSet; import org.lastbamboo.common.p2p.P2PConnectionEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class PeerCounter extends TimeSeries1D { private final Logger log = LoggerFactory.getLogger(getClass()); private final Set<String> peers; // this is always the current connected set of peers. private final Set<String> lifetimePeers; // this tracks unique peers seen in total private long lastBucket = -1; public PeerCounter() { this(DEFAULT_BUCKET_SIZE, NO_AGE_LIMIT); } public PeerCounter(long bucketSizeMillis) { this(bucketSizeMillis, NO_AGE_LIMIT); } public PeerCounter(long bucketSizeMillis, long ageLimit) { super(bucketSizeMillis, ageLimit); LanternHub.register(this); peers = new ConcurrentSkipListSet<String>(); lifetimePeers = new ConcurrentSkipListSet<String>(); // measure the current number of peers at regular intervals... final Timer timer = LanternHub.timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { measurePeers(); } }, 0, bucketSizeMillis); } public void reset() { super.reset(); peers.clear(); lifetimePeers.clear(); } protected void measurePeers() { long now = System.currentTimeMillis(); long bucket = bucketForTimestamp(now); if (lastBucket != -1) { if (bucket == lastBucket) { log.warn("Peer counter updated faster than normal..."); return; } if (bucket - lastBucket < 0) { log.warn("...sdrawkcab gninnur si emiT"); return; } if (bucket - lastBucket > 1) { log.warn("Peer counter thread is running more than a bucket slow..."); } } addData(now, peers.size()); resetLifetimeTotal(lifetimePeers.size()); lastBucket = bucket; } @Subscribe protected void onP2PConnectionEvent(final P2PConnectionEvent event) { // could obscure with hash, but not stored now. final String peerId = event.getJid(); if (event.isConnected()) { peers.add(peerId); lifetimePeers.add(peerId); } else { peers.remove(peerId); } } }
package org.lantern; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Class that serves JSON stats over REST. */ public class StatsServer { private final Logger log = LoggerFactory.getLogger(getClass()); private final ExecutorService service = Executors.newCachedThreadPool( new ThreadFactoryBuilder().setDaemon(true).build()); public void serve() { service.execute(new Runnable() { @Override public void run() { try { final ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("127.0.0.1", 7878)); while (true) { final Socket sock = server.accept(); processSocket(sock); } } catch (final IOException e) { log.error("Could not run stats server?", e); } } }); // Some dummy data for now. LanternHub.statsTracker().incrementProxiedRequests(); LanternHub.statsTracker().incrementProxiedRequests(); LanternHub.statsTracker().addBytesProxied(23210, new ChannelAdapter("212.95.136.18")); // Iran LanternHub.statsTracker().addBytesProxied(478291, new ChannelAdapter("78.110.96.7")); // Syria } private void processSocket(final Socket sock) { service.execute(new Runnable() { @Override public void run() { log.info("Got socket!!"); try { final InputStream is = sock.getInputStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String cur = br.readLine(); if (StringUtils.isBlank(cur)) { log.info("Closing blank request socket"); IOUtils.closeQuietly(sock); return; } if (!cur.startsWith("GET /stats")) { log.info("Ignoring request with line: "+cur); IOUtils.closeQuietly(sock); return; } final String requestLine = cur; while (StringUtils.isNotBlank(cur)) { log.info(cur); cur = br.readLine(); } log.info("Read all headers..."); final String json = LanternHub.statsTracker().toJson(); final String wrapped = wrapInCallback(requestLine, json); final String ct; if (json.equals(wrapped)) { ct = "application/json"; } else { ct = "text/javascript"; } OutputStream os = sock.getOutputStream(); final String response = "HTTP/1.1 200 OK\r\n"+ "Content-Type: "+ct+"\r\n"+ "Connection: close\r\n"+ "Content-Length: "+wrapped.length()+"\r\n"+ "\r\n"+ wrapped; os.write(response.getBytes("UTF-8")); } catch (final IOException e) { log.info("Exception serving stats!", e); } finally { IOUtils.closeQuietly(sock); } } }); } protected String wrapInCallback(final String requestLine, final String json) { if (!requestLine.contains("callback=")) { return json; } final String callback; final String cb = StringUtils.substringAfter(requestLine, "callback="); if (StringUtils.isBlank(cb)) { return json; } if (cb.contains("&")) { callback = StringUtils.substringBefore(cb, "&"); } else { callback = cb; } return callback + "("+json+")"; } private static class ChannelAdapter implements Channel { private final InetSocketAddress remoteAddress; private ChannelAdapter(final String address) { this.remoteAddress = new InetSocketAddress(address, 2781); } @Override public int compareTo(Channel o) { // TODO Auto-generated method stub return 0; } @Override public Integer getId() { // TODO Auto-generated method stub return null; } @Override public ChannelFactory getFactory() { // TODO Auto-generated method stub return null; } @Override public Channel getParent() { // TODO Auto-generated method stub return null; } @Override public ChannelConfig getConfig() { // TODO Auto-generated method stub return null; } @Override public ChannelPipeline getPipeline() { // TODO Auto-generated method stub return null; } @Override public boolean isOpen() { // TODO Auto-generated method stub return false; } @Override public boolean isBound() { // TODO Auto-generated method stub return false; } @Override public boolean isConnected() { // TODO Auto-generated method stub return false; } @Override public SocketAddress getLocalAddress() { // TODO Auto-generated method stub return null; } @Override public SocketAddress getRemoteAddress() { return remoteAddress; } @Override public ChannelFuture write(Object message) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture bind(SocketAddress localAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture disconnect() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture unbind() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture close() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture getCloseFuture() { // TODO Auto-generated method stub return null; } @Override public int getInterestOps() { // TODO Auto-generated method stub return 0; } @Override public boolean isReadable() { // TODO Auto-generated method stub return false; } @Override public boolean isWritable() { // TODO Auto-generated method stub return false; } @Override public ChannelFuture setInterestOps(int interestOps) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture setReadable(boolean readable) { // TODO Auto-generated method stub return null; } } }
package org.neuron_di.api; import net.sf.cglib.proxy.CallbackHelper; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.FixedValue; import net.sf.cglib.proxy.NoOp; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import javax.inject.Singleton; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Brain { private static final Class[] NO_INTERFACES = new Class[0]; private final Map<Class<?>, Object> singletons = new ConcurrentHashMap<>(); private final Objenesis objenesis = new ObjenesisStd(); public static Brain build() { return new Brain(); } private Brain() { } /** * Returns an instance of the given type which will resolve its dependencies * lazily. */ public <T> T make(final Class<T> type) { Object instance; if (type.isAnnotationPresent(Neuron.class)) { instance = singletons.get(type); if (null == instance) { final CallbackHelper helper = new CallbackHelper(type, NO_INTERFACES) { @Override protected Object getCallback(final Method method) { if (Modifier.isAbstract(method.getModifiers())) { return (FixedValue) () -> make(method.getReturnType()); } else { return NoOp.INSTANCE; } } }; instance = Enhancer.create(type, NO_INTERFACES, helper, helper.getCallbacks()); if (type.isAnnotationPresent(Singleton.class)) { final Object oldInstance = singletons.putIfAbsent(type, instance); if (null != oldInstance) { instance = oldInstance; } } } } else { instance = objenesis.newInstance(type); } assert null != instance; return type.cast(instance); } /** * Returns an instance of the given type which will resolve it's * non-constant dependencies to mock objects for testing. * The instance will ignore any caching strategy configured for its * {@linkplain Synapse synapses} and use {@link CachingStrategy#THREAD_SAFE} * in order to enable stubbing and verifying the mocked dependencies. */ public <T> T test(Class<T> type) { throw new UnsupportedOperationException(); } }
package sc.iview.vector; import net.imglib2.Localizable; import net.imglib2.RealLocalizable; import net.imglib2.RealPositionable; /** * Interface for 3D vectors. * * @author Kyle Harrington * @author Curtis Rueden */ public interface Vector3 extends RealLocalizable, RealPositionable { // -- Vector3 methods -- float xf(); float yf(); float zf(); default void moveX(float distance) { setX( xf() + distance ); } default void moveY(float distance) { setY( yf() + distance ); } default void moveZ(float distance) { setZ( zf() + distance ); } default void move( float xDist, float yDist, float zDist ) { moveX( xDist ); moveY( yDist ); moveZ( zDist ); } void setX(float position); void setY(float position); void setZ(float position); default void setPosition( float x, float y, float z ) { setX( x ); setY( y ); setZ( z ); } default double xd() { return xf(); } default double yd() { return yf(); } default double zd() { return zf(); } default void moveX(double distance) { setX( xd() + distance ); } default void moveY(double distance) { setY( yd() + distance ); } default void moveZ(double distance) { setZ( zd() + distance ); } default void move( double xDist, double yDist, double zDist ) { moveX( xDist ); moveY( yDist ); moveZ( zDist ); } default void setX(double position) { setX((float) position); } default void setY(double position) { setY((float) position); } default void setZ(double position) { setZ((float) position); } default void setPosition( double x, double y, double z ) { setX( x ); setY( y ); setZ( z ); } // -- RealLocalizable methods -- @Override default void localize( float[] position ) { position[0] = xf(); position[1] = yf(); position[2] = zf(); } @Override default void localize( double[] position ) { position[0] = xd(); position[1] = yd(); position[2] = zd(); } @Override default float getFloatPosition( int d ) { if( d == 0 ) return xf(); if( d == 1 ) return yf(); if( d == 2 ) return zf(); throw new IndexOutOfBoundsException( "" + d ); } @Override default double getDoublePosition( int d ) { if( d == 0 ) return xd(); if( d == 1 ) return yd(); if( d == 2 ) return zd(); throw new IndexOutOfBoundsException( "" + d ); } // -- RealPositionable methods -- @Override default void move( float distance, int d ) { if( d == 0 ) moveX( distance ); else if( d == 1 ) moveY( distance ); else if( d == 2 ) moveZ( distance ); else throw new IndexOutOfBoundsException( "" + d ); } @Override default void move( double distance, int d ) { if( d == 0 ) moveX( distance ); else if( d == 1 ) moveY( distance ); else if( d == 2 ) moveZ( distance ); else throw new IndexOutOfBoundsException( "" + d ); } @Override default void move( RealLocalizable distance ) { moveX( distance.getDoublePosition( 0 ) ); moveY( distance.getDoublePosition( 1 ) ); moveZ( distance.getDoublePosition( 2 ) ); } @Override default void move( float[] distance ) { moveX( distance[0] ); moveY( distance[1] ); moveZ( distance[2] ); } @Override default void move( double[] distance ) { moveX( distance[0] ); moveY( distance[1] ); moveZ( distance[2] ); } @Override default void setPosition( RealLocalizable localizable ) { setX( localizable.getDoublePosition( 0 ) ); setY( localizable.getDoublePosition( 1 ) ); setZ( localizable.getDoublePosition( 2 ) ); } @Override default void setPosition( float[] position ) { setX( position[0] ); setY( position[1] ); setZ( position[2] ); } @Override default void setPosition( double[] position ) { setX( position[0] ); setY( position[1] ); setZ( position[2] ); } @Override default void setPosition( float position, int d ) { if( d == 0 ) setX( position ); else if( d == 1 ) setY( position ); else if( d == 2 ) setZ( position ); else throw new IndexOutOfBoundsException( "" + d ); } @Override default void setPosition( double position, int d ) { if( d == 0 ) setX( position ); else if( d == 1 ) setY( position ); else if( d == 2 ) setZ( position ); else throw new IndexOutOfBoundsException( "" + d ); } // -- Positionable methods -- @Override default void fwd( int d ) { move( 1, d ); } @Override default void bck( int d ) { move( 1, d ); } @Override default void move( int distance, int d ) { move( ( double ) distance, d ); } @Override default void move( long distance, int d ) { move( ( double ) distance, d ); } @Override default void move( Localizable distance ) { moveX( distance.getDoublePosition( 0 ) ); moveY( distance.getDoublePosition( 1 ) ); moveZ( distance.getDoublePosition( 2 ) ); } @Override default void move( int[] distance ) { moveX( (double) distance[0] ); moveY( (double) distance[1] ); moveZ( (double) distance[2] ); } @Override default void move( long[] distance ) { moveX( (double) distance[0] ); moveY( (double) distance[1] ); moveZ( (double) distance[2] ); } @Override default void setPosition( Localizable localizable ) { setX( localizable.getDoublePosition( 0 ) ); setY( localizable.getDoublePosition( 1 ) ); setZ( localizable.getDoublePosition( 2 ) ); } @Override default void setPosition( int[] position ) { setX( (double) position[0] ); setY( (double) position[1] ); setZ( (double) position[2] ); } @Override default void setPosition( long[] position ) { setX( (double) position[0] ); setY( (double) position[1] ); setZ( (double) position[2] ); } @Override default void setPosition( int position, int d ) { setPosition( ( double ) position, d ); } @Override default void setPosition( long position, int d ) { setPosition( ( double ) position, d ); } // -- EuclideanSpace methods -- @Override default int numDimensions() { return 3; } // Extra convenience methods default double getLength() { return Math.sqrt( getDoublePosition(0) * getDoublePosition(0) + getDoublePosition(1) * getDoublePosition(1) + getDoublePosition(2) * getDoublePosition(2) ); } default Vector3 minus(Vector3 p2) { Vector3 result = this.copy(); result.moveX(-p2.getDoublePosition(0)); result.moveY(-p2.getDoublePosition(1)); result.moveZ(-p2.getDoublePosition(2)); return result; } default Vector3 multiply(float s) { Vector3 result = this.copy(); result.setPosition( result.getDoublePosition(0) * s, 0 ); result.setPosition( result.getDoublePosition(1) * s, 1 ); result.setPosition( result.getDoublePosition(2) * s, 2 ); return result; } Vector3 copy(); }
package sotechat.domain; import javax.persistence.*; import org.springframework.data.jpa.domain.AbstractPersistable; /** * Luokka viestien tallentamiseen */ @Entity public class Message extends AbstractPersistable<Long> { /** * aikaleima muodossa DateTime.toString() * */ private String date; /** viestin sisalto */ private String content; /** viestin lahettaja */ private String sender; /** keskustelu, johon viesti liittyy */ @ManyToOne(fetch = FetchType.EAGER) private Conversation conversation; /** keskustelun kanavaid johon viesti liittyy */ private String channelId; /** konstruktori */ public Message() { } /** Konstruktori asettaa parametreina annetut lahettajan, viestin sisallon * ja aikaleiman. * @param sender lahettajan nimi * @param content viestin sisalto * @param date aikaleima */ public Message(String sender, String content, String date){ this.sender = sender; this.content = content; this.date = date; } /** * Palauttaa viestin aikaleiman * @return viestin aikaleima */ public final String getDate() { return this.date; } /** * Asettaa viestin aikaleimaksi parametrina annetun ajan * @param pdate viestin aikaleima */ public final void setDate(final String pdate) { this.date = pdate; } /** * Palauttaa viestin sisallon * @return viestin sisalto */ public final String getContent() { return this.content; } /** * Asettaa viestin sisalloksi parametrina annetun tekstin * @param pContent viestin sisalto */ public final void setContent(final String pContent) { this.content = pContent; } /** * Palauttaa viestin lahettajan * @return viestin lahettaja */ public final String getSender() { return this.sender; } /** * Asettaa viestin lahettajaksi parametrina annetun kayttajanimen * @param psender viestin lahettaja */ public final void setSender(final String psender) { this.sender = psender; } /** * Palauttaa viestin keskustelun * @return viestiin liitetty Conversation olio */ public final Conversation getConversation() { return this.conversation; } /** * Asettaa viestin keskusteluksi parametrina annetun keskustelun * @param pConversation viestiin liittyva keskustelu */ public final void setConversation(final Conversation pConversation) { this.conversation = pConversation; this.channelId = pConversation.getChannelId(); } /** * Palauttaa viestiin liittyvan kanavaid:n * @return keskustelun kanavaid */ public String getChannelId() { return channelId; } /** * Asettaa keskustelun kanavaid:ksi parametrina annetun id:n * @param channelId keskustelun kanavaid */ public void setChannelId(String channelId) { this.channelId = channelId; } }
package tigase.muc; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import tigase.conf.Configurable; import tigase.db.RepositoryFactory; import tigase.db.UserRepository; import tigase.disco.ServiceEntity; import tigase.disco.ServiceIdentity; import tigase.disco.XMPPService; import tigase.muc.exceptions.MUCException; import tigase.muc.modules.DiscoInfoModule; import tigase.muc.modules.DiscoItemsModule; import tigase.muc.modules.GroupchatMessageModule; import tigase.muc.modules.IqStanzaForwarderModule; import tigase.muc.modules.MediatedInvitationModule; import tigase.muc.modules.ModeratorModule; import tigase.muc.modules.PresenceModule; import tigase.muc.modules.PresenceModule.DelayDeliveryThread.DelDeliverySend; import tigase.muc.modules.PrivateMessageModule; import tigase.muc.modules.RoomConfigurationModule; import tigase.muc.modules.SoftwareVersionModule; import tigase.muc.modules.UniqueRoomNameModule; import tigase.muc.modules.XmppPingModule; import tigase.muc.repository.IMucRepository; import tigase.muc.repository.MucDAO; import tigase.muc.repository.inmemory.InMemoryMucRepository; import tigase.server.AbstractMessageReceiver; import tigase.server.DisableDisco; import tigase.server.Packet; import tigase.util.DNSResolver; import tigase.util.TigaseStringprepException; import tigase.xml.Element; import tigase.xmpp.Authorization; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; /** * Class description * * * @version 5.1.0, 2010.11.02 at 01:01:31 MDT * @author Artur Hefczyc <artur.hefczyc@tigase.org> */ public class MUCComponent extends AbstractMessageReceiver implements DelDeliverySend, XMPPService, Configurable, DisableDisco { /** Field description */ public static final String ADMINS_KEY = "admins"; private static final String LOG_DIR_KEY = "room-log-directory"; public static final String MUC_ALLOW_CHAT_STATES_KEY = "muc-allow-chat-states"; public static final String MUC_LOCK_NEW_ROOM_KEY = "muc-lock-new-room"; protected static final String MUC_REPO_CLASS_PROP_KEY = "muc-repo-class"; protected static final String MUC_REPO_URL_PROP_KEY = "muc-repo-url"; private MucConfig config = new MucConfig(); private MucDAO dao; /** Field description */ public String[] HOSTNAMES_PROP_VAL = { "localhost", "hostname" }; protected Logger log = Logger.getLogger(this.getClass().getName()); private GroupchatMessageModule messageModule; private final ModulesManager modulesManager = new ModulesManager(); private IMucRepository mucRepository; private PresenceModule presenceModule; private IChatRoomLogger roomLogger; private ServiceEntity serviceEntity; private UserRepository userRepository; private final tigase.muc.ElementWriter writer; public MUCComponent() { this.writer = new ElementWriter() { @Override public void write(Collection<Packet> elements) { if (elements != null) { for (Packet element : elements) { if (element != null) { write(element); } } } } @Override public void write(Packet packet) { if (log.isLoggable(Level.FINER)) log.finer("Sent: " + packet.getElement()); addOutPacket(packet); } @Override public void writeElement(Collection<Element> elements) { if (elements != null) { for (Element element : elements) { if (element != null) { writeElement(element); } } } } @Override public void writeElement(final Element element) { if (element != null) { try { if (log.isLoggable(Level.FINER)) log.finer("Sent: " + element); addOutPacket(Packet.packetInstance(element)); } catch (TigaseStringprepException e) { } } } }; } public MUCComponent(ElementWriter writer) { this.writer = writer; } /** * Method description * * * @param params * * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> props = super.getDefaults(params); if (params.get(GEN_VIRT_HOSTS) != null) { HOSTNAMES_PROP_VAL = ((String) params.get(GEN_VIRT_HOSTS)).split(","); } else { HOSTNAMES_PROP_VAL = DNSResolver.getDefHostNames(); } String[] hostnames = new String[HOSTNAMES_PROP_VAL.length]; int i = 0; for (String host : HOSTNAMES_PROP_VAL) { hostnames[i++] = getName() + "." + host; } props.put(HOSTNAMES_PROP_KEY, hostnames); // By default use the same repository as all other components: String repo_class = (params.get(GEN_USER_DB) != null) ? (String) params.get(GEN_USER_DB) : DERBY_REPO_CLASS_PROP_VAL; String repo_uri = (params.get(GEN_USER_DB_URI) != null) ? (String) params.get(GEN_USER_DB_URI) : DERBY_REPO_URL_PROP_VAL; props.put(MUC_REPO_CLASS_PROP_KEY, repo_class); props.put(MUC_REPO_URL_PROP_KEY, repo_uri); String[] admins; if (params.get(GEN_ADMINS) != null) { admins = ((String) params.get(GEN_ADMINS)).split(","); } else { admins = new String[] { "admin@" + getDefHostName() }; } props.put(ADMINS_KEY, admins); props.put(LOG_DIR_KEY, new String("./logs/")); props.put(MUC_ALLOW_CHAT_STATES_KEY, Boolean.FALSE); props.put(MUC_LOCK_NEW_ROOM_KEY, Boolean.TRUE); return props; } /** * Method description * * * @return */ @Override public List<Element> getDiscoFeatures() { return null; } /** * Method description * * * @param node * @param jid * * @return */ @Override public Element getDiscoInfo(String node, JID jid) { return null; } /** * Method description * * * @param node * @param jid * * @return */ @Override public List<Element> getDiscoItems(String node, JID jid) { if (node == null) { Element result = serviceEntity.getDiscoItem(null, getName() + "." + jid.toString()); return Arrays.asList(result); } else { return null; } } /** * Method description * * * @return */ public Set<String> getFeaturesFromModule() { HashSet<String> result = new HashSet<String>(); result.add("http://jabber.org/protocol/muc"); result.addAll(this.modulesManager.getFeatures()); return result; } protected void init() { this.modulesManager.register(new PrivateMessageModule(this.config, writer, this.mucRepository)); messageModule = this.modulesManager.register(new GroupchatMessageModule(this.config, writer, this.mucRepository, this.roomLogger)); presenceModule = this.modulesManager.register(new PresenceModule(this.config, writer, this.mucRepository, this.roomLogger, this)); this.modulesManager.register(new RoomConfigurationModule(this.config, writer, this.mucRepository, messageModule)); this.modulesManager.register(new ModeratorModule(this.config, writer, this.mucRepository)); this.modulesManager.register(new SoftwareVersionModule(writer)); this.modulesManager.register(new XmppPingModule(writer)); this.modulesManager.register(new DiscoItemsModule(this.config, writer, this.mucRepository)); this.modulesManager.register(new DiscoInfoModule(this.config, writer, this.mucRepository, this)); this.modulesManager.register(new MediatedInvitationModule(this.config, writer, this.mucRepository)); this.modulesManager.register(new UniqueRoomNameModule(this.config, writer, this.mucRepository)); this.modulesManager.register(new IqStanzaForwarderModule(this.config, writer, this.mucRepository)); } /** * Method description * * * @param packet */ @Override public void processPacket(Packet packet) { processStanzaPacket(packet); } protected void processStanzaPacket(final Packet packet) { try { boolean handled = this.modulesManager.process(packet, writer); if (!handled) { final String t = packet.getAttribute("type"); final StanzaType type = t == null ? null : StanzaType.valueof(t); if (type != StanzaType.error) { throw new MUCException(Authorization.FEATURE_NOT_IMPLEMENTED); } else { if (log.isLoggable(Level.FINER)) { log.finer(packet.getElemName() + " stanza with type='error' ignored"); } } } } catch (MUCException e) { try { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Exception thrown for " + packet.toString(), e); } else if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "PubSubException on stanza id=" + packet.getAttribute("id") + " " + e.getMessage()); } Packet result = e.makeElement(packet, true); Element el = result.getElement(); el.setAttribute("from", BareJID.bareJIDInstance(el.getAttribute("from")).toString()); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Sending back: " + result.toString()); } writer.write(result); } catch (Exception e1) { log.log(Level.WARNING, "Problem during generate error response", e1); } } } /** * Method description * * * @param packet */ @Override public void sendDelayedPacket(Packet packet) { addOutPacket(packet); } /** * @param config2 */ public void setConfig(MucConfig config2) { this.config = config2; } /** * Method description * * * @param mucRepository */ public void setMucRepository(IMucRepository mucRepository) { this.mucRepository = mucRepository; } /** * Method description * * * @param props */ @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); if (props.size() == 1) { // If props.size() == 1, it means this is a single property update // and this component does not support single property change for the rest // of it's settings return; } // String[] hostnames = (String[]) props.get(HOSTNAMES_PROP_KEY); // if (hostnames == null || hostnames.length == 0) { // log.warning("Hostnames definition is empty, setting 'localhost'"); // hostnames = new String[] { getName() + ".localhost" }; // clearRoutings(); // for (String host : hostnames) { // addRouting(host); serviceEntity = new ServiceEntity(getName(), null, "Multi User Chat"); serviceEntity.addIdentities(new ServiceIdentity("conference", "text", "Multi User Chat")); serviceEntity.addFeatures("http://jabber.org/protocol/muc"); this.config.setServiceName(BareJID.bareJIDInstanceNS("multi-user-chat")); this.config.setLogDirectory((String) props.get(LOG_DIR_KEY)); if (userRepository == null) { userRepository = (UserRepository) props.get(SHARED_USER_REPO_PROP_KEY); try { if (userRepository == null) { String cls_name = (String) props.get(MUC_REPO_CLASS_PROP_KEY); String res_uri = (String) props.get(MUC_REPO_URL_PROP_KEY); this.userRepository = RepositoryFactory.getUserRepository(cls_name, res_uri, null); userRepository.initRepository(res_uri, null); } dao = new MucDAO(this.config, this.userRepository); mucRepository = new InMemoryMucRepository(this.config, dao); } catch (Exception e) { log.severe("Can't initialize MUC repository: " + e); e.printStackTrace(); // System.exit(1); } this.roomLogger = new RoomChatLogger(this.config); init(); } this.messageModule.setChatStateAllowed((Boolean) props.get(MUC_ALLOW_CHAT_STATES_KEY)); this.presenceModule.setLockNewRoom((Boolean) props.get(MUC_LOCK_NEW_ROOM_KEY)); log.info("Tigase MUC Component ver. " + MucVersion.getVersion() + " started."); } } // ~ Formatted in Sun Code Convention
package model.statistics; import utilities.structuredmap.StructuredMap; public class EntityStatistics extends Statistics { private int livesLeft; private int experience; private int movement; private int currentHealth; private int currentMana; private int money; public EntityStatistics() { super(); setLivesLeft(3); setExperience(0); setMovement(0); setCurrentHealth(getMaximumHealth()); setCurrentMana(getMaximumMana()); setMoney(30); } public EntityStatistics(StructuredMap map) { super(map); setLivesLeft(map.getInteger("livesLeft")); setExperience(map.getInteger("experience")); setMovement(map.getInteger("movement")); setCurrentHealth(map.getInteger("currentHealth")); setCurrentMana(map.getInteger("currentMana")); setMoney(map.getInteger("money")); } public EntityStatistics(int strength, int agility, int intellect, int hardiness, int livesLeft, int experience, int movement, int currentHealth, int currentMana, int money) { super(strength, agility, intellect, hardiness); setLivesLeft(livesLeft); setExperience(experience); setMovement(movement); setCurrentHealth(currentHealth); setCurrentMana(currentMana); setMoney(money); } public int getOffensiveRating() { return (getStrength() + getAgility()) / 2; } public int getDefensiveRating() { return (getHardiness() + getAgility()) / 2; } public int getArmorRating() { return (getHardiness() + getCurrentHealth()) / 2; } public EntityStatistics clone() { EntityStatistics cloned = new EntityStatistics(); cloned.setStrength(this.getStrength()); cloned.setAgility(this.getAgility()); cloned.setIntellect(this.getIntellect()); cloned.setHardiness(this.getHardiness()); cloned.setLivesLeft(this.getLivesLeft()); cloned.setExperience(this.getExperience()); cloned.setMovement(this.getMovement()); cloned.setCurrentHealth(this.getCurrentHealth()); cloned.setCurrentMana(this.getCurrentMana()); return cloned; } public int getLevel() { return (experience / 100) + 1; } public int getLivesLeft() { return livesLeft; } public void setLivesLeft(int livesLeft) { this.livesLeft = livesLeft; livesCheck(); } public void decrementLives(){ --this.livesLeft; livesCheck(); } private void livesCheck(){ if(this.getLivesLeft() <= 0){ System.out.println("OUT OF LIVES, PERMA DEAD, PROB SHOULD DO SOMETHING"); } } public int getExperience() { return experience; } public void setExperience(int experience) { this.experience = experience; } public int getMovement() { return movement; } public void setMovement(int movement) { this.movement = movement; } public int getCurrentHealth() { return currentHealth; } public void setCurrentHealth(int currentHealth) { this.currentHealth = currentHealth; this.healthCheck(); } private void healthCheck(){ if(this.currentHealth < 0){ this.currentHealth = getMaximumHealth(); this.decrementLives(); System.out.println("You haved Died!"); } if(this.currentHealth > this.getMaximumHealth()){ this.currentHealth = this.getMaximumHealth(); } } public int getMaximumHealth() { return getStrength() * 100; } public int getCurrentMana() { return currentMana; } public void setMoney(int money) { this.money = money; } public int getMoney() { return money; } private void setCurrentMana(int currentMana) { this.currentMana = currentMana; this.manaCheck(); } public void addCurrentMana(int change) { this.currentMana += change; this.manaCheck(); } private void manaCheck(){ if(this.currentMana < 0){ this.currentMana = 0; } if(this.currentMana > this.getMaximumMana()){ this.currentMana = this.getMaximumMana(); } } public int getMaximumMana() { return getIntellect() * 100; } public void addExperience(int experience) { this.experience += experience; } public void addHealth(int health) { this.currentHealth += health; } public void addMovement(int movement) { this.movement += movement; } public void addLives(int lives) { this.livesLeft += lives; } public void addMoney(int money) { this.money += money; } @Override public String toString() { String contents = super.toString() + "Lives Left: " + livesLeft + "\n" + "Experience: " + experience + "\n" + "Movement: " + movement + "\n" + "Current Health: " + currentHealth + "\n" + "Current Mana: " + currentMana + "\n" + "Level: " + getLevel() + "\nMoney: " + getMoney() + "\nArmor Rank:" + getArmorRating() + "\nOffensive Rating: " + getOffensiveRating() + "\nDefensive Rating: " + getDefensiveRating(); return contents; } @Override public StructuredMap getStructuredMap() { StructuredMap map = super.getStructuredMap(); map.put("livesLeft", getLivesLeft()); map.put("experience", getExperience()); map.put("movement", getMovement()); map.put("currentHealth", getCurrentHealth()); map.put("currentMana", getCurrentMana()); map.put("money", getMoney()); return map; } }
package net.coobird.paint.driver; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.Point; import java.awt.Rectangle; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.lang.reflect.InvocationTargetException; import javax.swing.DefaultListModel; import javax.swing.JCheckBoxMenuItem; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import net.coobird.paint.BlendingMode; import net.coobird.paint.application.ApplicationUtils; import net.coobird.paint.application.BrushListCellRenderer; import net.coobird.paint.application.ImageLayerListCellRenderer; import net.coobird.paint.brush.Brush; import net.coobird.paint.brush.BrushController; import net.coobird.paint.brush.RandomSplashBrush; import net.coobird.paint.brush.RegularCircularBrush; import net.coobird.paint.brush.RegularEllipticalBrush; import net.coobird.paint.brush.RegularEllipticalEraser; import net.coobird.paint.brush.SolidCircularBrush; import net.coobird.paint.brush.StagedBrush; import net.coobird.paint.filter.ImageFilter; import net.coobird.paint.filter.ImageFilterThreadingWrapper; import net.coobird.paint.filter.MatrixImageFilter; import net.coobird.paint.filter.RepeatableMatrixFilter; import net.coobird.paint.filter.ResizeFilter; import net.coobird.paint.image.Canvas; import net.coobird.paint.image.ClippableImageRenderer; import net.coobird.paint.image.ImageLayer; import net.coobird.paint.image.ImageLayerUtils; import net.coobird.paint.image.PartialImageRenderer; import net.coobird.paint.io.FormatManager; public class DemoApp2 { class ActionMenuItem extends JMenuItem implements ActionListener { public ActionMenuItem(String s) { addActionListener(this); setText(s); } public void actionPerformed(ActionEvent e) {}; } private void makeGUI() { final JFrame f = new JFrame("Paint Dot Jar Demonstration 2"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //f.getContentPane().setLayout(new BorderLayout()); ApplicationUtils.setMainComponent(f); JPanel listPanels = new JPanel(new GridLayout(0, 1)); final JList brushList = new JList(); brushList.setCellRenderer(new BrushListCellRenderer()); final DefaultListModel brushListModel = new DefaultListModel(); brushList.setModel(brushListModel); brushListModel.addElement(new RegularCircularBrush(null, 80, new Color(0,0,255,32))); brushListModel.addElement(new SolidCircularBrush(null, 80, Color.red)); brushListModel.addElement(new SolidCircularBrush(null, 40, Color.orange)); brushListModel.addElement(new SolidCircularBrush(null, 120, Color.white)); brushListModel.addElement(new RegularCircularBrush("Small black brush", 40, new Color(0,0,0,32))); brushListModel.addElement(new RegularCircularBrush("Thin black brush", 80, new Color(0,0,0,4))); brushListModel.addElement(new RegularCircularBrush("Emerald green 40 px brush", 40, new Color(0,255,96,32))); brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.67, 0.3, new Color(0,0,128,4))); brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.67, 0.5, new Color(0,0,128,4))); brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.8, 0.8, new Color(0,0,128,4))); brushListModel.addElement(new RegularEllipticalBrush(null, 120, Math.PI * 0.4, 0.8, new Color(0,0,0,16))); brushListModel.addElement(new RegularEllipticalBrush(null, 240, Math.PI * 0.4, 0.8, new Color(255,0,0,16))); brushListModel.addElement(new RegularEllipticalBrush(null, 240, Math.PI * 0.2, 0.6, new Color(255,0,0,4))); brushListModel.addElement(new RegularEllipticalBrush(null, 40, Math.PI * 0.9, 0.2, new Color(0,255,128,4))); brushListModel.addElement(new RegularEllipticalBrush(null, 60, Math.PI * 0.5, 0.4, new Color(0,0,128,16))); brushListModel.addElement(new RegularEllipticalEraser(null, 40, 0, 1, 1f)); brushListModel.addElement(new RegularEllipticalEraser(null, 80, 0, 1, 1f)); brushListModel.addElement(new RegularEllipticalEraser(null, 80, Math.PI * 0.25, 0.5, 0.5f)); brushListModel.addElement(new SolidCircularBrush(null, 4)); brushListModel.addElement(new RegularCircularBrush(null, 4, Color.black)); brushListModel.addElement(new RegularEllipticalEraser(null, 4, 0, 1, 1f)); brushListModel.addElement(new StagedBrush(null, 10, Color.black)); brushListModel.addElement(new RandomSplashBrush()); final JPopupMenu brushPopupMenu = new JPopupMenu(); brushPopupMenu.add(new ActionMenuItem("Change Color...") { public void actionPerformed(ActionEvent e) { Brush b = (Brush)brushList.getSelectedValue(); if (b == null) { return; } Color c = JColorChooser.showDialog(f, "Choose Color...", b.getColor()); if (c == null) { return; } b.setColor(c); brushList.repaint(); } }); brushPopupMenu.add(new ActionMenuItem("Change Size...") { public void actionPerformed(ActionEvent e) { Brush b = (Brush)brushList.getSelectedValue(); String s = JOptionPane.showInputDialog(f, "Size:"); b.setSize(Integer.parseInt(s)); brushList.repaint(); } }); brushPopupMenu.add(new ActionMenuItem("Properties...") { public void actionPerformed(ActionEvent e) { Brush b = (Brush)brushList.getSelectedValue(); JPanel p = new JPanel(new BorderLayout()); JSlider brushSize = new JSlider(1, 200, b.getSize()); JSlider alpha = new JSlider(0, 100, Math.round(b.getAlpha() * 100)); JColorChooser color = new JColorChooser(b.getColor()); JPanel ip = new JPanel(new GridLayout(0,1)); ip.add(new JLabel("Brush size:")); ip.add(brushSize); ip.add(new JLabel("Alpha:")); ip.add(alpha); p.add(ip, BorderLayout.CENTER); p.add(color, BorderLayout.SOUTH); p.validate(); int option = JOptionPane.showConfirmDialog(f, p, "Properties", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.CANCEL_OPTION) { return; } b.setSize(brushSize.getValue()); b.setAlpha(((float)alpha.getValue()/100f)); b.setColor(color.getColor()); brushList.repaint(); } }); brushList.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { brushPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { brushPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); final JScrollPane brushListSp = new JScrollPane(brushList); listPanels.add(brushListSp); final BrushController bc = new BrushController(); final JList ilList = new JList(); ilList.setCellRenderer(new ImageLayerListCellRenderer()); final DefaultListModel ilListModel = new DefaultListModel(); ilList.setModel(ilListModel); final int SIZE = 800; final CanvasHolder ch = new CanvasHolder(); Canvas c = new Canvas(SIZE, SIZE); c.addLayer(); c.addLayer(); c.addLayer(); ch.setCanvas(c); for (ImageLayer il : c.getLayers()) { ilListModel.addElement(il); } final JScrollPane ilListSp = new JScrollPane(ilList); listPanels.add(ilListSp); // final ImageRenderer renderer = ImageRendererFactory.getInstance(); final PartialImageRenderer renderer = new ClippableImageRenderer(); // final ProgressiveImageRenderer renderer = new ProgressiveImageRenderer(); final JPanel p = new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); Rectangle r = getVisibleRect(); // g.drawImage(renderer.render(ch.getCanvas()), 0, 0, null); int width = r.width; int height = r.height; double zoom = ch.getCanvas().getZoom(); g.drawImage( renderer.render( ch.getCanvas(), (int)(r.x / zoom), (int)(r.y / zoom), (int)(width / zoom), (int)(height / zoom) ), r.x, r.y, null ); } /* (non-Javadoc) * @see javax.swing.JComponent#getPreferredSize() */ @Override public Dimension getPreferredSize() { int width = (int)Math.round(ch.getCanvas().getWidth() * ch.getCanvas().getZoom()); int height = (int)Math.round(ch.getCanvas().getHeight() * ch.getCanvas().getZoom()); return new Dimension(width, height); } }; class DrawEventHandler extends MouseAdapter implements BrushController.BrushDrawListener { // MouseAdapter ma = new MouseAdapter() // long lastTime = System.currentTimeMillis(); public void mouseDragged(MouseEvent e) { ImageLayer il = (ImageLayer)ilList.getSelectedValue(); Brush b = (Brush)brushList.getSelectedValue(); if (il == null || b == null) { return; } int offsetX = il.getX(); int offsetY = il.getY(); double zoom = ch.getCanvas().getZoom(); int sx = (int)Math.round((e.getX() - offsetX) / zoom); int sy = (int)Math.round((e.getY() - offsetY) / zoom); bc.drawBrush( il, b, sx, sy ); SwingUtilities.invokeLater(new Runnable() { public void run() { p.repaint(); } }); } public void mouseReleased(MouseEvent e) { if (ilList.getSelectedValue() == null) { return; } ((ImageLayer)ilList.getSelectedValue()).update(); ilList.repaint(); bc.releaseBrush(); p.repaint(); } public void mousePressed(MouseEvent e) { ImageLayer il = (ImageLayer)ilList.getSelectedValue(); Brush b = (Brush)brushList.getSelectedValue(); if (il == null || b == null) { return; } int offsetX = il.getX(); int offsetY = il.getY(); double zoom = ch.getCanvas().getZoom(); int sx = (int)Math.round((e.getX() - offsetX) / zoom); int sy = (int)Math.round((e.getY() - offsetY) / zoom); bc.drawBrush( il, b, sx, sy ); } @Override public void doneDrawing() { SwingUtilities.invokeLater(new Runnable() { public void run() { p.repaint(); } }); } }; DrawEventHandler ma = new DrawEventHandler(); bc.listener = ma; p.addMouseListener(ma); p.addMouseMotionListener(ma); ilList.setDropTarget(new DropTarget() { /* (non-Javadoc) * @see java.awt.dnd.DropTarget#drop(java.awt.dnd.DropTargetDropEvent) */ @Override public synchronized void drop(DropTargetDropEvent e) { super.drop(e); Point pt = e.getLocation(); int fromIndex = ilList.getSelectedIndex(); int toIndex = ilList.locationToIndex(pt); ch.getCanvas().moveLayer(fromIndex, toIndex); ilListModel.removeAllElements(); for (ImageLayer il : ch.getCanvas().getLayers()) { ilListModel.addElement(il); } p.repaint(); } }); ilList.setDragEnabled(true); final JPopupMenu ilPopupMenu = new JPopupMenu(); ilPopupMenu.add(new ActionMenuItem("Change Name...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Name:"); ((ImageLayer)ilList.getSelectedValue()).setCaption(s); p.repaint(); } }); ilPopupMenu.add(new ActionMenuItem("Change Alpha...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Alpha:"); ((ImageLayer)ilList.getSelectedValue()).setAlpha(Float.parseFloat(s)); p.repaint(); } }); ilPopupMenu.add(new ActionMenuItem("Change Location...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Location (x,y):"); String[] t = s.split(","); int x = Integer.parseInt(t[0]); int y = Integer.parseInt(t[1]); ((ImageLayer)ilList.getSelectedValue()).setLocation(x, y); p.repaint(); } }); ilPopupMenu.add(new ActionMenuItem("Change Mode...") { public void actionPerformed(ActionEvent e) { ImageLayer il = (ImageLayer)ilList.getSelectedValue(); JComboBox cb = new JComboBox(BlendingMode.Layer.values()); cb.setSelectedItem(il.getMode()); JOptionPane.showMessageDialog(f, cb); il.setMode((BlendingMode.Layer)cb.getSelectedItem()); p.repaint(); } }); ilPopupMenu.addSeparator(); ilPopupMenu.add(new ActionMenuItem("New Layer") { public void actionPerformed(ActionEvent e) { ImageLayer il = new ImageLayer( ch.getCanvas().getWidth(), ch.getCanvas().getHeight() ); il.setCaption(ch.getCanvas().getNextLayerName()); ch.getCanvas().addLayer(il); updateGUI(ilListModel, ch, p); } }); ilPopupMenu.add(new ActionMenuItem("Delete Layer") { public void actionPerformed(ActionEvent e) { ImageLayer il = (ImageLayer)ilList.getSelectedValue(); ch.getCanvas().removeLayer(il); updateGUI(ilListModel, ch, p); } }); ilPopupMenu.add(new ActionMenuItem("Merge Layer") { public void actionPerformed(ActionEvent e) { int index = ilList.getSelectedIndex(); if (index >= ilListModel.size() - 1) { return; } ImageLayer topIl = (ImageLayer)ilListModel.get(index); ImageLayer bottomIl = (ImageLayer)ilListModel.get(index + 1); ch.getCanvas().removeLayer(topIl); ch.getCanvas().removeLayer(bottomIl); ch.getCanvas().addLayer(ImageLayerUtils.mergeLayers(topIl, bottomIl), index); updateGUI(ilListModel, ch, p); } }); ilList.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { ilPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { ilPopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); final JMenuBar menubar = new JMenuBar(); final JMenu fileMenu = new JMenu("File"); final JMenu brushMenu = new JMenu("Brush"); final JMenu layerMenu = new JMenu("Layer"); final JMenu filterMenu = new JMenu("Filter"); fileMenu.add(new ActionMenuItem("New...") { public void actionPerformed(ActionEvent e) { System.out.println("new"); String s = JOptionPane.showInputDialog(f, "Enter dimensions in (w,h):"); if (s == null) { return; } int width = SIZE; int height = SIZE; String[] t = s.split(","); try { width = Integer.parseInt(t[0]); height = Integer.parseInt(t[1]); } catch (Exception ex) { JOptionPane.showMessageDialog(f, "Invalid dimensions.\n" + ex); } Canvas c = new Canvas(width, height); c.addLayer(new ImageLayer(width, height)); ch.setCanvas(c); updateGUI(ilListModel, ch, p); } }); fileMenu.addSeparator(); fileMenu.add(new ActionMenuItem("Open...") { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); for (FileFilter filter : FormatManager.getInputFileFilters()) { fc.addChoosableFileFilter(filter); } int option = fc.showOpenDialog(f); if (option != JFileChooser.APPROVE_OPTION) return; File f = fc.getSelectedFile(); ch.setCanvas(FormatManager.getImageInput(f).read(f)); updateGUI(ilListModel, ch, p); } }); fileMenu.add(new ActionMenuItem("Save As...") { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); for (FileFilter filter : FormatManager.getOutputFileFilters()) { fc.addChoosableFileFilter(filter); } fc.setFileFilter(fc.getAcceptAllFileFilter()); int option = fc.showSaveDialog(f); if (option != JFileChooser.APPROVE_OPTION) { return; } File outFile = fc.getSelectedFile(); FormatManager.getImageOutput(outFile).write(ch.getCanvas(), outFile); } }); fileMenu.addSeparator(); fileMenu.add(new ActionMenuItem("Import Layer...") { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); for (FileFilter filter : FormatManager.getInputFileFilters()) { fc.addChoosableFileFilter(filter); } int option = fc.showOpenDialog(f); if (option != JFileChooser.APPROVE_OPTION) return; File f = fc.getSelectedFile(); Canvas c = FormatManager.getImageInput(f).read(f); for (ImageLayer layer : c.getLayers()) { ch.getCanvas().addLayer(layer); } updateGUI(ilListModel, ch, p); } }); fileMenu.addSeparator(); fileMenu.add(new ActionMenuItem("Exit") { public void actionPerformed(ActionEvent arg0) { f.setVisible(false); } }); final JCheckBoxMenuItem bcMenu = new JCheckBoxMenuItem("Rotatable Brush"); bcMenu.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { System.out.println("rotatable toggle"); bc.setMovable(!bc.getMovable()); bcMenu.setSelected(bc.getMovable()); } }); brushMenu.add(bcMenu); layerMenu.add(new ActionMenuItem("New Layer") { public void actionPerformed(ActionEvent e) { ch.getCanvas().addLayer(new ImageLayer(ch.getCanvas().getWidth(), ch.getCanvas().getHeight())); updateGUI(ilListModel, ch, p); } }); layerMenu.add(new ActionMenuItem("Delete Layer") { public void actionPerformed(ActionEvent e) { if (ilList.getSelectedIndex() == -1) { return; } ImageLayer il = (ImageLayer)ilList.getSelectedValue(); ch.getCanvas().removeLayer(il); updateGUI(ilListModel, ch, p); } }); layerMenu.add(new ActionMenuItem("Merge Layer") { public void actionPerformed(ActionEvent e) { if (ilList.getSelectedIndex() == -1) { return; } int index = ilList.getSelectedIndex(); if (index >= ilListModel.size() - 1) { return; } ImageLayer topIl = (ImageLayer)ilListModel.get(index); ImageLayer bottomIl = (ImageLayer)ilListModel.get(index + 1); ch.getCanvas().removeLayer(topIl); ch.getCanvas().removeLayer(bottomIl); ch.getCanvas().addLayer(ImageLayerUtils.mergeLayers(topIl, bottomIl), index); updateGUI(ilListModel, ch, p); } }); layerMenu.addSeparator(); layerMenu.add(new ActionMenuItem("Size Canvas to Largest Layer") { public void actionPerformed(ActionEvent e) { ch.getCanvas().pack(); ilList.repaint(); p.repaint(); } }); layerMenu.add(new ActionMenuItem("Grow Layer to Canvas") { public void actionPerformed(ActionEvent e) { } }); layerMenu.add(new ActionMenuItem("Resize Canvas...") { public void actionPerformed(ActionEvent e) { } }); class FilterWithProgressBar { final ImageFilter filter; final JProgressBar pb; final JDialog d; public FilterWithProgressBar(final ImageFilter filter) { pb = new JProgressBar(); d = new JDialog(f); JPanel panel = new JPanel(new BorderLayout()); pb.setValue(0); pb.setStringPainted(true); panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH); panel.add(pb, BorderLayout.CENTER); d.getContentPane().add(panel); d.pack(); d.setVisible(true); this.filter = filter; } public void run() { new Thread(new Runnable() { public void run() { long st = System.currentTimeMillis(); final int inc = 100 / ch.getCanvas().getLayers().size(); for (ImageLayer il : ch.getCanvas().getLayers()) { il.setImage(filter.processImage(il.getImage())); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { pb.setValue(pb.getValue() + inc); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long tp = System.currentTimeMillis() - st; System.out.println("complete in: " + tp); pb.setValue(100); d.dispose(); p.repaint(); ilList.repaint(); } }).start(); } } filterMenu.add(new ActionMenuItem("Blur") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new MatrixImageFilter(3, 3, new float[]{ 0.0f, 0.1f, 0.0f, 0.1f, 0.6f, 0.1f, 0.0f, 0.1f, 0.0f }); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Blur More") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new RepeatableMatrixFilter( "Blur More", 3, 3, 10, new float[]{ 0.0f, 0.1f, 0.0f, 0.1f, 0.6f, 0.1f, 0.0f, 0.1f, 0.0f }); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Blur More Concurrent") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new ImageFilterThreadingWrapper( new RepeatableMatrixFilter( 3, 3, 10, new float[] { 0.0f, 0.1f, 0.0f, 0.1f, 0.6f, 0.1f, 0.0f, 0.1f, 0.0f } ) ); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Blur More Concurrent 7x7") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new ImageFilterThreadingWrapper( new RepeatableMatrixFilter( 7, 7, 1, new float[] { 0.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 0.05f, 0.05f, 0.1f, 0.2f, 0.1f, 0.05f, 0.05f, 0.0f, 0.0f, 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.0f, 0.0f } ), 10 ); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("No Effect") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new MatrixImageFilter( "No Effect", 3, 3, new float[]{ 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Saturate") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new MatrixImageFilter(3, 3, new float[]{ 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f }); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Blur + Lighten") { public void actionPerformed(ActionEvent e) { ImageFilter filter = new MatrixImageFilter(5, 5, new float[]{ 0.0f, 0.0f, 0.25f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.25f, 0.0f, 1.0f, 0.0f, 0.25f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.25f, 0.0f, 0.0f }); new FilterWithProgressBar(filter).run(); } }); filterMenu.add(new ActionMenuItem("Resize...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Resize scale:"); final double scale = Double.parseDouble(s); final JProgressBar pb = new JProgressBar(); final JDialog d = new JDialog(f); JPanel panel = new JPanel(new BorderLayout()); pb.setValue(0); pb.setStringPainted(true); panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH); panel.add(pb, BorderLayout.CENTER); d.getContentPane().add(panel); d.pack(); d.setVisible(true); new Thread(new Runnable() { public void run() { long st = System.currentTimeMillis(); ImageFilter filter = new ResizeFilter("Resize", scale); for (ImageLayer il : ch.getCanvas().getLayers()) { il.setImage(filter.processImage(il.getImage())); } final int inc = 100 / ch.getCanvas().getLayers().size(); for (ImageLayer il : ch.getCanvas().getLayers()) { il.setImage(filter.processImage(il.getImage())); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { pb.setValue(pb.getValue() + inc); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long tp = System.currentTimeMillis() - st; System.out.println("complete in: " + tp); pb.setValue(100); d.dispose(); Rectangle r = new Rectangle(); for (ImageLayer il : ch.getCanvas().getLayers()) { r.add(new Rectangle( il.getX(), il.getY(), il.getWidth(), il.getHeight() )); } ch.getCanvas().setSize(r.width, r.height); p.repaint(); ilList.repaint(); p.revalidate(); filter = null; } }).start(); } }); filterMenu.add(new ActionMenuItem("Resize Concurrent...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Resize scale:"); final double scale = Double.parseDouble(s); final JProgressBar pb = new JProgressBar(); final JDialog d = new JDialog(f); JPanel panel = new JPanel(new BorderLayout()); pb.setValue(0); pb.setStringPainted(true); panel.add(new JLabel("Processing filter..."), BorderLayout.NORTH); panel.add(pb, BorderLayout.CENTER); d.getContentPane().add(panel); d.pack(); d.setVisible(true); new Thread(new Runnable() { public void run() { long st = System.currentTimeMillis(); ImageFilter filter = new ImageFilterThreadingWrapper(new ResizeFilter("Resize Concurrent", scale)); for (ImageLayer il : ch.getCanvas().getLayers()) { il.setImage(filter.processImage(il.getImage())); } final int inc = 100 / ch.getCanvas().getLayers().size(); for (ImageLayer il : ch.getCanvas().getLayers()) { il.setImage(filter.processImage(il.getImage())); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { pb.setValue(pb.getValue() + inc); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long tp = System.currentTimeMillis() - st; System.out.println("complete in: " + tp); pb.setValue(100); d.dispose(); Rectangle r = new Rectangle(); for (ImageLayer il : ch.getCanvas().getLayers()) { r.add(new Rectangle( il.getX(), il.getY(), il.getWidth(), il.getHeight() )); } ch.getCanvas().setSize(r.width, r.height); p.repaint(); ilList.repaint(); p.revalidate(); filter = null; } }).start(); } }); layerMenu.addSeparator(); layerMenu.add(new ActionMenuItem("Throw Exception") { public void actionPerformed(ActionEvent e) { try { class CatchMeIfYouCanException extends Exception { private CatchMeIfYouCanException(String s) { super(s); } } throw new CatchMeIfYouCanException("Ha! Catch me if you can!"); } catch (Exception ex) { ApplicationUtils.showExceptionMessage(ex); } } }); layerMenu.addSeparator(); final JScrollPane sp = new JScrollPane(p); sp.getViewport().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { sp.repaint(); } }); layerMenu.add(new ActionMenuItem("Zoom...") { public void actionPerformed(ActionEvent e) { String s = JOptionPane.showInputDialog(f, "Zoom:"); ch.getCanvas().setZoom(Double.parseDouble(s)); p.revalidate(); p.repaint(); } }); JMenu helpMenu = new JMenu("Help"); helpMenu.add(new ActionMenuItem("About...") { public void actionPerformed(ActionEvent e) { String msg = "Coobird's Paint dot Jar Demonstration 2"; JOptionPane.showMessageDialog(f, msg, "About Paint dot Jar", JOptionPane.INFORMATION_MESSAGE); } }); menubar.add(fileMenu); menubar.add(brushMenu); menubar.add(layerMenu); menubar.add(filterMenu); menubar.add(helpMenu); f.setJMenuBar(menubar); bcMenu.setSelected(bc.getMovable()); f.setSize(640, 480); f.setLocation(1, 1); JSplitPane splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, sp, listPanels ); f.getContentPane().add(splitPane); f.validate(); f.setVisible(true); splitPane.setDividerLocation(0.7); } private void updateGUI(final DefaultListModel ilListModel, final CanvasHolder ch, final JPanel p) { SwingUtilities.invokeLater(new Runnable() { public void run() { ilListModel.removeAllElements(); for (ImageLayer il : ch.getCanvas().getLayers()) { ilListModel.addElement(il); } p.repaint(); p.revalidate(); } }); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { new DemoApp2().makeGUI(); } }); } private static class CanvasHolder { Canvas c; public Canvas getCanvas() { return c; } public void setCanvas(Canvas c) { this.c = c; } } }
package net.sf.jaer.aemonitor; import java.util.Collection; import net.sf.jaer.aemonitor.EventRaw.EventType; import net.sf.jaer.eventio.AEFileInputStream; /** * A structure containing a packer of AEs: addresses, timestamps. The AE packet * efficiently packages a set of events: rather than using an object per event, * it packs a lot of events into an object that references arrays of primitives. * These arrays can be newly allocated or statically allocated to the capacity * of the maximum buffer that is transferred from a device. Callers must use * {@link #getNumEvents} to find out the capacity of the packet in the case that * the arrays contain less events than their capacity, which is usually the case * when the packet is reused in a device acquisition. * <p> * These AEPacketRaw are used only for device events (raw events). For processed * events, see the net.sf.jaer.event package. * * @author tobi */ public class AEPacketRaw extends AEPacket { /** * The index of the start of the last packet captured from a device, used * for processing data on acquisition. The hardware interface class is * responsible for setting this value. After a capture of data, * lastCaptureLength points to the start of this capture. A real time * processor need not process the entire buffer but only starting from this * lastCaptureIndex. */ public int lastCaptureIndex = 0; /** * The number of events last captured. The hardware interface class is * responsible for setting this value. */ public int lastCaptureLength = 0; /** * The raw AER addresses */ public int[] addresses; /** * Signals that an overrun occurred on this packet */ public boolean overrunOccuredFlag = false; /** * An event, for internal use. */ private EventRaw event = new EventRaw(); /** * The last modification time from System.nanoTime(). Not all hardware * interfaces set this value. */ public long systemModificationTimeNs; /** * Creates a new instance of AEPacketRaw with 0 capacity. */ public AEPacketRaw() { } /** * Creates a new instance of AEPacketRaw from addresses and timestamps * * @param addresses * @param timestamps */ public AEPacketRaw(int[] addresses, int[] timestamps) { if ((addresses == null) || (timestamps == null)) { return; } setAddresses(addresses); setTimestamps(timestamps); if (addresses.length != timestamps.length) { throw new RuntimeException("addresses.length=" + addresses.length + "!=timestamps.length=" + timestamps.length); } capacity = addresses.length; numEvents = addresses.length; } /** * Creates a new instance of AEPacketRaw from addresses and timestamps and * EventTypes * * @param addresses * @param timestamps * @param etypes */ public AEPacketRaw(int[] addresses, int[] timestamps, EventType[] etypes) { if ((addresses == null) || (timestamps == null)) { return; } setAddresses(addresses); setTimestamps(timestamps); setEventtypes(etypes); if (addresses.length != timestamps.length) { throw new RuntimeException("addresses.length=" + addresses.length + "!=timestamps.length=" + timestamps.length); } capacity = addresses.length; numEvents = addresses.length; } /** * Creates a new instance of AEPacketRaw with an initial capacity and empty * event arrays. * * @param size capacity in events */ public AEPacketRaw(int size) { if (size > MAX_PACKET_SIZE_EVENTS) { log.warning("allocating arrays of size " + size + " which is larger than MAX_PACKET_SIZE_EVENTS=" + MAX_PACKET_SIZE_EVENTS + " in size"); } else { log.info("allocating size=" + size + " arrays of events"); } allocateArrays(size); } /** * Constructs a new AEPacketRaw by concatenating two packets. The contents * of the source packets are copied to this packet's memory arrays. * * The timestamps will be probably not be ordered monotonically after this * concatenation! And unless the sources are identified by unique addresses, * the sources of the events will be lost. * * @param one * @param two */ public AEPacketRaw(AEPacketRaw one, AEPacketRaw two) { this(one.getNumEvents() + two.getNumEvents()); System.arraycopy(one.getAddresses(), 0, getAddresses(), 0, one.getNumEvents()); System.arraycopy(two.getAddresses(), 0, getAddresses(), one.getNumEvents(), two.getNumEvents()); System.arraycopy(one.getTimestamps(), 0, getTimestamps(), 0, one.getNumEvents()); System.arraycopy(two.getTimestamps(), 0, getTimestamps(), one.getNumEvents(), two.getNumEvents()); numEvents = addresses.length; capacity = numEvents; } /** * Constructs a new AEPacketRaw by concatenating a list of event packets. * The contents of the source packets are copied to this packet's memory * arrays according to the iterator of the Collection. * * The timestamps will be probably not be ordered monotonically after this * concatenation! And unless the sources are identified by unique addresses, * the sources of the events will be lost. * * @param collection to copy from. */ public AEPacketRaw(Collection<AEPacketRaw> collection) { int n = 0; for (AEPacketRaw packet : collection) { n += packet.getNumEvents(); } allocateArrays(n); //setNumEvents(n); int counter = 0; for (AEPacketRaw packet : collection) { try { int ne = packet.getNumEvents(); System.arraycopy(packet.getAddresses(), 0, getAddresses(), counter, ne); System.arraycopy(packet.getTimestamps(), 0, getTimestamps(), counter, ne); counter += ne; } catch (ArrayIndexOutOfBoundsException e) { log.warning("caught " + e.toString() + "when constructing new RawPacket from Collection."); continue; } } setNumEvents(counter); } private void allocateArrays(int size) { addresses = new int[size]; //new E[size]; timestamps = new int[size]; eventtypes = new EventType[size]; pixelDataArray = new int[size]; this.capacity = size; numEvents = 0; } public int[] getAddresses() { return this.addresses; } public void setAddresses(final int[] addresses) { this.addresses = addresses; if (addresses == null) { numEvents = 0; } else { numEvents = addresses.length; } } /** * Uses local EventRaw to return packaged event. (Does not create a new * object instance.) */ final public EventRaw getEvent(int k) { event.timestamp = timestamps[k]; event.address = addresses[k]; event.eventtype = eventtypes[k]; event.pixelData = pixelDataArray[k]; return event; } /** * Ensure the capacity given. Overrides AEPacket's ensureCapacity to * increase the size of the addresses array. If present capacity is less * than capacity, then arrays are newly allocated and old contents are * copied. * * @param c the desired capacity */ @Override final public void ensureCapacity(final int c) { super.ensureCapacity(c); if (addresses == null) { addresses = new int[c]; this.capacity = c; } else if (addresses.length < c) { int newcap = (int) ENLARGE_CAPACITY_FACTOR * c; int[] newaddresses = new int[newcap]; // TODO can use all of heap and OutOfMemoryError here if we keep adding events System.arraycopy(addresses, 0, newaddresses, 0, addresses.length); addresses = newaddresses; this.capacity = newcap; } } /** * Appends event, enlarging packet if necessary. Not thread safe. * * @param e an Event to add to the ones already present. Capacity is * enlarged if necessary. */ @Override final public void addEvent(EventRaw e) { if (e == null) { log.warning("tried to add null event, not adding it"); } super.addEvent(e); // will increment numEvents // int n=getCapacity(); // make sure our address array is big enough this.ensureCapacity(capacity); // enlarge the address array if necessary addresses[numEvents - 1] = e.address; // store the address at the end of the array // numEvents++; // we already incremented the number of events in the super call } /** * Allocates a new AEPacketRaw and copies the events from this packet into * the new one, returning it. The size of the new packet that is returned is * exactly the number of events stored in the this packet. This method can * be used to more efficiently use matlab memory, which handles java garbage * collection poorly. * * @return a new packet sized to the src packet number of events */ public AEPacketRaw getPrunedCopy() { int n = getNumEvents(); AEPacketRaw dest = new AEPacketRaw(n); int[] srcTs = getTimestamps(); int[] srcAddr = getAddresses(); int[] destTs = dest.getTimestamps(); int[] destAddr = dest.getAddresses(); System.arraycopy(srcTs, 0, destTs, 0, n); System.arraycopy(srcAddr, 0, destAddr, 0, n); dest.setNumEvents(n); return dest; } @Override public String toString() { if (getNumEvents() == 0) { return super.toString(); } else { return super.toString() + (numEvents > 0 ? String.format(" tstart=%,d tend=%,d dt=%,d", timestamps[0], timestamps[numEvents - 1], (timestamps[numEvents - 1] - timestamps[0])) : " empty"); } } private void checkTimeOrder(AEPacketRaw first, AEPacketRaw second) throws IllegalArgumentException { if (first == null || second == null) { return; } if (first.isEmpty() || second.isEmpty()) { return; } if (first.getFirstTimestamp() > second.getFirstTimestamp()) { throw new IllegalArgumentException(String.format("first packet %s starts later than start of second packet %s", first.toString(), second.toString())); } if (first.getLastTimestamp() > second.getFirstTimestamp()) { throw new IllegalArgumentException(String.format("first packet %s ends later than start of second packet %s", first.toString(), second.toString())); } } /** * Appends another AEPacketRaw to this one. The packets must be in strict * time order so that first and last timestamp make sense. * * @param source * @return the appended packet * @see #prepend(net.sf.jaer.aemonitor.AEPacketRaw) */ public AEPacketRaw append(AEPacketRaw source) { if (source == null || source.getNumEvents() == 0) { return this; } // checkTimeOrder(this, source); ensureCapacity(getNumEvents() + source.getNumEvents()); System.arraycopy(source.getAddresses(), 0, addresses, numEvents, source.getNumEvents()); System.arraycopy(source.getTimestamps(), 0, timestamps, numEvents, source.getNumEvents()); setNumEvents(getNumEvents() + source.getNumEvents()); return this; } /** * Prepends another AEPacketRaw *before* this one. The packets must be in * strict time order so that first and last timestamp make sense. * * @param source * @return the appended packet * @since 12.1.21 - to support RosbagFileInputStream backwards mode * @see #append(net.sf.jaer.aemonitor.AEPacketRaw) */ public AEPacketRaw prepend(AEPacketRaw source) { if (source == null || source.getNumEvents() == 0) { return this; } checkTimeOrder(source, this); ensureCapacity(getNumEvents() + source.getNumEvents()); // makes arrays large enough // copy current packet to the new positions to the right System.arraycopy(addresses, 0, addresses, source.getNumEvents(), numEvents); System.arraycopy(timestamps, 0, timestamps, source.getNumEvents(), numEvents); // copy source to start of address and timestamp arrays System.arraycopy(source.getAddresses(), 0, addresses, 0, source.getNumEvents()); System.arraycopy(source.getTimestamps(), 0, timestamps, 0, source.getNumEvents()); setNumEvents(getNumEvents() + source.getNumEvents()); AEPacketRaw.timestampCheck(this); return this; } /** * Static method to copy from one AEPacketRaw to another. Assumes events * before <i>destPos</i> make sense. * * @param src source packet * @param srcPos the starting index in src * @param dest destination packet * @param destPos the starting index in destination * @param length the number of events to copy from src */ public static void copy(AEPacketRaw src, int srcPos, AEPacketRaw dest, int destPos, int length) { // num events in dest =destPos+length if (src == null || dest == null) { throw new NullPointerException("null src or dest"); } dest.ensureCapacity(destPos + length); System.arraycopy(src.getAddresses(), srcPos, dest.getAddresses(), destPos, length); System.arraycopy(src.getTimestamps(), srcPos, dest.getTimestamps(), destPos, length); dest.setNumEvents(destPos + length); timestampCheck(dest); } private static void timestampCheck(AEPacketRaw dest) { if (!dest.isEmpty() && dest.getFirstTimestamp() > dest.getLastTimestamp()) { throw new RuntimeException(String.format("First timestamp later than last timestamp for %s", dest)); } } }
package org.beanmaker; import java.util.List; import java.util.Set; import org.jcodegen.java.AnonymousClassCreation; import org.jcodegen.java.Assignment; import org.jcodegen.java.Comparison; import org.jcodegen.java.Condition; import org.jcodegen.java.ConstructorDeclaration; import org.jcodegen.java.ElseBlock; import org.jcodegen.java.ElseIfBlock; import org.jcodegen.java.ExceptionThrow; import org.jcodegen.java.ForLoop; import org.jcodegen.java.FunctionArgument; import org.jcodegen.java.FunctionCall; import org.jcodegen.java.FunctionDeclaration; import org.jcodegen.java.GenericType; import org.jcodegen.java.IfBlock; import org.jcodegen.java.JavaClass; import org.jcodegen.java.JavaCodeBlock; import org.jcodegen.java.LineOfCode; import org.jcodegen.java.ObjectCreation; import org.jcodegen.java.OperatorExpression; import org.jcodegen.java.ReturnStatement; import org.jcodegen.java.VarDeclaration; import org.jcodegen.java.Visibility; import org.jcodegen.java.WhileBlock; import org.dbbeans.util.Strings; import static org.beanmaker.SourceFiles.chopId; import static org.dbbeans.util.Strings.*; public class BaseClassSourceFile extends BeanCodeWithDBInfo { private final Set<String> types; private final String internalsVar; private final String parametersVar; public BaseClassSourceFile(final String beanName, final String packageName, final Columns columns, final String tableName) { super(beanName, packageName, "Base", columns, tableName); internalsVar = beanVarName + "Internals"; parametersVar = Strings.uncamelize(beanName).toUpperCase() + "_PARAMETERS"; types = columns.getJavaTypes(); createSourceCode(); } private void addImports() { importsManager.addImport("java.sql.PreparedStatement"); importsManager.addImport("java.sql.ResultSet"); importsManager.addImport("java.sql.SQLException"); importsManager.addImport("java.util.ArrayList"); importsManager.addImport("java.util.List"); importsManager.addImport("java.util.Locale"); importsManager.addImport("org.beanmaker.util.BeanInternals"); importsManager.addImport("org.beanmaker.util.DbBeanInterface"); importsManager.addImport("org.beanmaker.util.DBQueries"); importsManager.addImport("org.beanmaker.util.ErrorMessage"); importsManager.addImport("org.beanmaker.util.IdNamePair"); importsManager.addImport("org.dbbeans.sql.DBQueryRetrieveData"); importsManager.addImport("org.dbbeans.sql.DBQuerySetup"); importsManager.addImport("org.dbbeans.sql.DBQuerySetupProcess"); importsManager.addImport("org.dbbeans.sql.DBTransaction"); importsManager.addImport("org.dbbeans.util.Strings"); if (columns.containsNumericalData()) importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); if (types.contains("Date")) { importsManager.addImport("java.sql.Date"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); } if (types.contains("Time")) { importsManager.addImport("java.sql.Time"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputTimeFormat"); } if (types.contains("Timestamp")) { importsManager.addImport("java.sql.Timestamp"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); importsManager.addImport("org.dbbeans.util.SimpleInputTimestampFormat"); } if (types.contains("Money")) { importsManager.addImport("org.dbbeans.util.Money"); importsManager.addImport("org.dbbeans.util.MoneyFormat"); } if (columns.hasLastUpdate()) importsManager.addImport("org.dbbeans.util.Dates"); } private void addClassModifiers() { javaClass.markAsAbstract().extendsClass("DbBean").implementsInterface("DbBeanInterface"); } private void addProperties() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final VarDeclaration declaration; if (type.equals("String")) declaration = new VarDeclaration("String", field, EMPTY_STRING); else if (type.equals("Money")) declaration = new VarDeclaration("Money", field, new ObjectCreation("Money") .addArgument("0") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))); else declaration = new VarDeclaration(type, field); addProperty(declaration); if (type.equals("Money")) addProperty(new VarDeclaration("String", field + "Str", new FunctionCall("toString", field))); if (JAVA_TEMPORAL_TYPES.contains(type) || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) addProperty(new VarDeclaration("String", field + "Str", EMPTY_STRING)); } if (columns.hasLastUpdate()) addProperty("boolean", "updateOK"); if (columns.hasOneToManyRelationships()) { boolean first = true; for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { if (first) { newLine(); first = false; } addProperty(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName())); } } newLine(); javaClass.addContent(new VarDeclaration("String", "DATABASE_TABLE_NAME", quickQuote(tableName)).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); javaClass.addContent(new VarDeclaration("String", "DATABASE_FIELD_LIST", quickQuote(getStaticFieldList())).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); newLine(); javaClass.addContent( new VarDeclaration("BeanInternals", internalsVar, new ObjectCreation("BeanInternals").addArgument(quickQuote(bundleName))).markAsFinal().visibility(Visibility.PROTECTED) ); final String parametersClass = beanName + "Parameters"; javaClass.addContent( new VarDeclaration(parametersClass, parametersVar, new ObjectCreation(parametersClass)).markAsFinal().markAsStatic().visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); if (columns.hasExtraFields()) { for (ExtraField extraField: columns.getExtraFields()) { javaClass.addContent(new LineOfCode(extraField.toString())); if (extraField.requiresImport()) importsManager.addImport(extraField.getRequiredImport()); if (extraField.requiresSecondaryImport()) importsManager.addImport(extraField.getSecondaryRequiredImport()); if (extraField.requiresTernaryImport()) importsManager.addImport(extraField.getTernaryRequiredImport()); } newLine(); } } private String getStaticFieldList() { final StringBuilder list = new StringBuilder(); for (Column column: columns.getList()) list.append(tableName).append(".").append(column.getSqlName()).append(", "); list.delete(list.length() - 2, list.length()); return list.toString(); } private void addConstructors() { javaClass.addContent(getBaseConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getIdArgumentConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getCopyConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getFieldConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getResultSetConstructor()).addContent(EMPTY_LINE); } private ConstructorDeclaration getBaseConstructor() { return javaClass.createConstructor(); } private ConstructorDeclaration getIdArgumentConstructor() { return getBaseConstructor().addArgument(new FunctionArgument("long", "id")).addContent("setId(id);"); } private ConstructorDeclaration getCopyConstructor() { final ConstructorDeclaration copyConstructor = getBaseConstructor(); copyConstructor.addArgument(new FunctionArgument(beanName + "Base", "model")).addContent(new Assignment("id", "0")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (field.equals("itemOrder")) copyConstructor.addContent(new Assignment("itemOrder", "0")); else if (field.startsWith("id") || type.equals("boolean") || type.equals("String")) copyConstructor.addContent(new Assignment(field, "model." + field)); else copyConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument("model." + field).byItself()); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); copyConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": model." + javaName).addContent( new FunctionCall("add", javaName).byItself().addArgument( new ObjectCreation(beanClass).addArgument(new FunctionCall("getId", beanObject)) ) ) ); } return copyConstructor; } private ConstructorDeclaration getFieldConstructor() { final ConstructorDeclaration fieldConstructor = getBaseConstructor().visibility(Visibility.PROTECTED); for (Column column: columns.getList()) fieldConstructor.addArgument(new FunctionArgument(column.getJavaType(), column.getJavaName())); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (field.startsWith("id") || field.equals("itemOrder") || type.equals("boolean") || type.equals("String")) fieldConstructor.addContent(new Assignment("this." + field, field)); else fieldConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument(field).byItself()); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); fieldConstructor.addArgument(new FunctionArgument(new GenericType("List", beanClass).toString(), javaName)); fieldConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": " + javaName).addContent( new FunctionCall("add", "this." + javaName).byItself().addArgument(beanObject) ) ); } return fieldConstructor; } private ConstructorDeclaration getResultSetConstructor() { final ConstructorDeclaration rsConstructor = getBaseConstructor().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("ResultSet", "rs")).addException("SQLException"); for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) rsConstructor.addArgument(new FunctionArgument(new GenericType("List", relationship.getBeanClass()).toString(), relationship.getJavaName())); final FunctionCall thisCall = new FunctionCall("this").byItself(); int index = 0; for (Column column: columns.getList()) { if (column.getJavaType().equals("Money")) thisCall.addArgument(new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(++index)))); else thisCall.addArgument(new FunctionCall("get" + capitalize(column.getJavaType()), "rs").addArgument(Integer.toString(++index))); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) thisCall.addArgument(relationship.getJavaName()); return rsConstructor.addContent(thisCall); } private void addSetIdFunction() { final List<OneToManyRelationship> relationships = columns.getOneToManyRelationships(); final FunctionDeclaration function = new FunctionDeclaration("setId") .addArgument(new FunctionArgument("long", "id")); // function inner class for database row retrieval final JavaClass databaseInnerClass = new JavaClass("DataFromDBQuery").visibility(Visibility.NONE) .implementsInterface("DBQuerySetupProcess"); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (type.equals("int") || type.equals("long")) databaseInnerClass.addContent(new VarDeclaration(type, field, "0")); else if (type.equals("String") || JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money")) databaseInnerClass.addContent(new VarDeclaration(type, field, "null")); else if (type.equals("boolean")) databaseInnerClass.addContent(new VarDeclaration(type, field, "false")); else throw new IllegalStateException("Java type not allowed: " + type); } } databaseInnerClass.addContent(new VarDeclaration("boolean", "idOK", "false")) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRS = getInnerClassProcessRSFunctionStart(); final IfBlock ifRsNext = new IfBlock(new Condition("rs.next()")); int index = 0; for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { ++index; if (type.equals("Money")) ifRsNext.addContent(new Assignment(field, new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(index))) .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar)))); else { final String getterName = "get" + capitalize(type); ifRsNext.addContent(new Assignment(field, new FunctionCall(getterName, "rs") .addArgument(Integer.toString(index)))); } } } ifRsNext.addContent(new Assignment("idOK", "true")); processRS.addContent(ifRsNext); databaseInnerClass.addContent(processRS); function.addContent(databaseInnerClass).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final JavaClass extraDBInnerClass = new JavaClass("DataFromDBQuery" + capitalize(relationship.getJavaName())) .visibility(Visibility.NONE).implementsInterface("DBQuerySetupProcess") .addContent(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName()).markAsFinal()) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRSExtra = getInnerClassProcessRSFunctionStart() .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", relationship.getJavaName()) .byItself() .addArgument(new ObjectCreation(relationship.getBeanClass()) .addArgument("rs.getLong(1)")))); extraDBInnerClass.addContent(processRSExtra); function.addContent(extraDBInnerClass).addContent(EMPTY_LINE); } } // check for bad ID function.addContent(new IfBlock(new Condition("id <= 0")).addContent("throw new IllegalArgumentException(\"id = \" + id + \" <= 0\");")) .addContent(EMPTY_LINE); // instantiate DBQuery inner class & use it to retrieve data function.addContent( new VarDeclaration("DataFromDBQuery", "dataFromDBQuery", new ObjectCreation("DataFromDBQuery")).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQuery())) .addArgument("dataFromDBQuery") ).addContent(EMPTY_LINE); // check if data was returned function.addContent( new IfBlock(new Condition("!dataFromDBQuery.idOK")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"id = \" + id + \" does not exist\"") ) ).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final String cappedJavaName = capitalize(relationship.getJavaName()); function.addContent( new VarDeclaration("DataFromDBQuery" + cappedJavaName, "dataFromDBQuery" + cappedJavaName, new ObjectCreation("DataFromDBQuery" + cappedJavaName)).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQueryOneToManyRelationship(relationship.getTable(), relationship.getIdSqlName()))) .addArgument("dataFromDBQuery" + cappedJavaName) ).addContent(EMPTY_LINE); } } // extra DB actions function.addContent("initExtraDbActions(id);").addContent(EMPTY_LINE); // fields assignment function.addContent(new Assignment("this.id", "id")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { function.addContent(new Assignment("this." + field, "dataFromDBQuery." + field)); if (JAVA_TEMPORAL_TYPES.contains(type)) function.addContent( new Assignment(field +"Str", new FunctionCall("convert" + type + "ToString").addArgument(field)) ); if ((type.equals("int") || type.equals("long")) && !field.equals("itemOrder") && !field.startsWith("id")) function.addContent( new Assignment(field +"Str", new FunctionCall("valueOf", "String").addArgument(field)) ); if (type.equals("Money")) function.addContent( new Assignment(field +"Str", new FunctionCall("toString", field)) ); } } for (OneToManyRelationship relationship: relationships) if (!relationship.isListOnly()) function.addContent( new Assignment("this." + relationship.getJavaName(), "dataFromDBQuery" + capitalize(relationship.getJavaName()) + "." + relationship.getJavaName()) ); function.addContent(EMPTY_LINE).addContent("postInitActions();"); javaClass.addContent(function).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("initExtraDbActions") .visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "id")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postInitActions") .visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("resetId") .addContent("id = 0;") ).addContent(EMPTY_LINE); } private FunctionDeclaration getInnerClassSetupPSWithIdFunction() { return new FunctionDeclaration("setupPreparedStatement") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent("stat.setLong(1, id);"); } private FunctionDeclaration getInnerClassProcessRSFunctionStart() { return new FunctionDeclaration("processResultSet") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("ResultSet", "rs")); } private void addEquals() { javaClass.addContent( new FunctionDeclaration("equals", "boolean").addArgument(new FunctionArgument("Object", "object")).annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition("object instanceof " + beanName)).addContent( new ReturnStatement("((" + beanName + ") object).getId() == id") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("hashCode", "int").annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("-1") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("31 * ((int) (id ^ (id >>> 32))) + 17") ) ).addContent(EMPTY_LINE); } private void addToString() { final String returnExpression = "\"[" + beanName + " - " + tableName + " javaClass.addContent( new FunctionDeclaration("toString", "String").annotate("@Override").addContent( new ReturnStatement(returnExpression) ) ).addContent(EMPTY_LINE); } private void addSetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id") && !field.equals("lastUpdate") && !field.equals("modifiedBy") && !field.equals("itemOrder")) { final FunctionDeclaration setter = new FunctionDeclaration("set" + capitalize(field)) .addArgument(new FunctionArgument(type, field)); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new Assignment("this." + field, "null") ).elseClause(new ElseBlock().addContent( new Assignment("this." + field, new ObjectCreation(type) .addArgument(new FunctionCall("getTime", field))) )) ); else setter.addContent( new Assignment("this." + field, field) ); if (type.equals("int") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Integer").addArgument(field)) ); if (type.equals("long") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Long").addArgument(field)) ); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new Assignment(field + "Str", new FunctionCall("convert" + capitalize(type) + "ToString").addArgument(field)) ); if (type.equals("Money")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", field)) ); javaClass.addContent(setter).addContent(EMPTY_LINE); if (column.couldHaveAssociatedBean() && column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final String associatedBeanObject = uncapitalize(chopId(field)); final FunctionDeclaration fromObjectSetter = new FunctionDeclaration("set" + capitalize(associatedBeanObject)) .addArgument(new FunctionArgument(associatedBeanClass, associatedBeanObject)) .addContent(new IfBlock(new Condition(new Comparison(new FunctionCall("getId", associatedBeanObject), "0"))) .addContent(new ExceptionThrow("IllegalArgumentException") .addArgument(quickQuote("Cannot accept uninitialized " + associatedBeanClass + " bean (id = 0) as argument.")))) .addContent(EMPTY_LINE) .addContent(new Assignment(field, new FunctionCall("getId", associatedBeanObject))); javaClass.addContent(fromObjectSetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id"))) { final FunctionDeclaration strSetter = new FunctionDeclaration("set" + capitalize(field) + "Str") .addArgument(new FunctionArgument("String", field + "Str")) .addContent(new Assignment("this." + field + "Str", field + "Str")); javaClass.addContent(strSetter).addContent(EMPTY_LINE); } } } } private void addGetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String prefix; if (type.equals("boolean")) prefix = "is"; else prefix = "get"; final FunctionDeclaration getter = new FunctionDeclaration(prefix + capitalize(field), type); if (JAVA_TEMPORAL_TYPES.contains(type)) getter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent(new ReturnStatement("null")) ).addContent( EMPTY_LINE ).addContent( new ReturnStatement(new ObjectCreation(type).addArgument(new FunctionCall("getTime", field))) ); else getter.addContent( new ReturnStatement(field) ); javaClass.addContent(getter).addContent(EMPTY_LINE); if (column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final FunctionDeclaration associatedBeanGetter = new FunctionDeclaration("get" + chopId(field), associatedBeanClass) .addContent(new ReturnStatement(new ObjectCreation(associatedBeanClass).addArgument(field))); javaClass.addContent(associatedBeanGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) { final FunctionDeclaration strGetter = new FunctionDeclaration("get" + capitalize(field) + "Str", "String") .addContent(new ReturnStatement(field + "Str")); javaClass.addContent(strGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type)) { final String capField = capitalize(field); final FunctionDeclaration formattedGetter = new FunctionDeclaration("get" + capField + "Formatted", "String") .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Empty"))) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Required"))) .addContent(getCannotDisplayBadDataException())) .addContent(new ReturnStatement(EMPTY_STRING))) .addContent(EMPTY_LINE) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "OK"), true)).addContent(getCannotDisplayBadDataException())) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("format" + type).addArgument(new FunctionCall("convertStringTo" + type).addArgument(field + "Str")))); javaClass.addContent(formattedGetter).addContent(EMPTY_LINE); } if (type.equals("boolean")) { final FunctionDeclaration booleanValGetter = new FunctionDeclaration("get" + capitalize(field) + "Val", "String") .addContent(new IfBlock(new Condition(field)) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("true_value"))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("false_value")))); javaClass.addContent(booleanValGetter).addContent(EMPTY_LINE); } } } private void addLabelGetters() { for (Column column: columns.getList()) { final String field = column.getJavaName(); if (!column.isSpecial()) javaClass.addContent( new FunctionDeclaration("get" + capitalize(field) + "Label", "String").addContent( new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } private ExceptionThrow getCannotDisplayBadDataException() { return new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot display bad data")); } private void addRequiredIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "Required", column.isRequired(), false); } private void addUniqueIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "ToBeUnique", column.isUnique(), false); } private void addOneToManyRelationshipManagement() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { final String beanClass = relationship.getBeanClass(); final String itemName = uncapitalize(beanClass); final String listName = relationship.getJavaName(); if (relationship.isListOnly()) { importsManager.addImport("org.dbbeans.sql.DBQuerySetupRetrieveData"); final FunctionDeclaration preparedStatementSetup = new FunctionDeclaration("setupPreparedStatement") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent(new FunctionCall("setLong", "stat") .addArgument("1") .addArgument("id") .byItself()); final FunctionCall dbAccessFunction = new FunctionCall("processQuery", "dbAccess").byItself(); final FunctionDeclaration listGetter = new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(VarDeclaration.createListDeclaration(beanClass, listName).markAsFinal()) .addContent(EMPTY_LINE) .addContent(dbAccessFunction .addArgument(new OperatorExpression(quickQuote("SELECT ") + " + " + beanClass + ".DATABASE_FIELD_LIST + " + quickQuote(" FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=? ORDER BY "), new FunctionCall("getOrderByFields", beanClass + "." + Strings.uncamelize(beanClass).toUpperCase() + "_PARAMETERS"), OperatorExpression.Operator.ADD)) .addArgument(new AnonymousClassCreation("DBQuerySetupProcess").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(EMPTY_LINE) .addContent(new FunctionDeclaration("processResultSet") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", listName).byItself() .addArgument(new ObjectCreation(beanClass) .addArgument("rs"))))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(listName)); javaClass.addContent(listGetter).addContent(EMPTY_LINE); final FunctionCall dbAccessForCountFunction = new FunctionCall("processQuery", "dbAccess"); final FunctionDeclaration countGetter = new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement( dbAccessForCountFunction .addArgument(quickQuote("SELECT COUNT(id) FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=?")) .addArgument(new AnonymousClassCreation("DBQuerySetupRetrieveData<Long>").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(new FunctionDeclaration("processResultSet", "Long") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new FunctionCall("next", "rs").byItself()) .addContent(new ReturnStatement(new FunctionCall("getLong", "rs").addArgument("1"))))) )); javaClass.addContent(countGetter).addContent(EMPTY_LINE); } else { importsManager.addImport("java.util.Collections"); javaClass.addContent( new FunctionDeclaration("add" + beanClass) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(new FunctionCall("add", listName).byItself() .addArgument(itemName)) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + beanClass, beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("get", listName).addArgument("index"))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("insert" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("add", listName).addArgument("index").addArgument(itemName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("delete" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("remove", listName).addArgument("index").byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("clear" + capitalize(listName)) .addContent(new FunctionCall("clear", listName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(new ReturnStatement(new FunctionCall("unmodifiableList", "Collections").addArgument(listName))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement(new FunctionCall("size", listName))) ).addContent(EMPTY_LINE); } } } private IfBlock getOneToManyRelationshipIndexOutOfBoundTest(final String listName) { return new IfBlock(new Condition(new Comparison("index", "0", Comparison.Comparator.LESS_THAN)) .orCondition(new Condition(new Comparison("index", new FunctionCall("size", listName), Comparison.Comparator.GT_EQUAL)))) .addContent(new ExceptionThrow("IndexOutOfBoundsException") .addArgument(getOneToManyRelationshipIndexOutOfBoundExceptionText(listName))); } private String getOneToManyRelationshipIndexOutOfBoundExceptionText(final String listName) { return "\"Bounds : 0-\" + " + listName + ".size() + \", index : \" + index"; } private void addItemOrderManagement() { if (!columns.hasItemOrder()) return; final Column itemOrderField = columns.getItemOrderField(); javaClass.addContent( new FunctionDeclaration("isFirstItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new ReturnStatement("itemOrder == 1") ) ).addContent(EMPTY_LINE); final FunctionDeclaration isLastItemOrderFunction = new FunctionDeclaration("isLastItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE); if (!itemOrderField.isUnique()) isLastItemOrderFunction.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, true))) ).addContent(EMPTY_LINE) ); isLastItemOrderFunction.addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, false))) ); javaClass.addContent(isLastItemOrderFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveUp").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isFirstItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot move Item Order above position 1 which it currently occupies")) ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveUp", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveDown").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"Cannot move Item Order below max position: \" + itemOrder") ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveDown", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder++;") ) ).addContent(EMPTY_LINE); if (itemOrderField.isUnique()) { javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } else { final String associatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); final String associatedFieldJavaFunction = "get" + camelize(itemOrderField.getItemOrderAssociatedField()); javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addArgument(new FunctionArgument("long...", "parameters")).addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound", "parameters").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQueryWithNullSecondaryField", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) ).addElseIfClause(new ElseIfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQueryWithNullSecondaryField", parametersVar)) .addArgument(beanVarName) )).elseClause(new ElseBlock().addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "queryDest")) .addArgument(new FunctionArgument("long", "destLowerBound")) .addArgument(new FunctionArgument("String", "queryOrig")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound", associatedFieldJavaName) )) ).addContent( new IfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder", associatedFieldJavaName) )) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderReassociateWith").addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Bean must be saved in DB before reassociation.") ) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, associatedFieldJavaName))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Association already exists.") ) ).addContent(EMPTY_LINE).addContent( new FunctionCall("itemOrderMove").addArgument(associatedFieldJavaName).byItself() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart().addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new VarDeclaration("long", "newItemOrder") ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)) .addArgument(associatedFieldJavaName), "1", OperatorExpression.Operator.ADD)) )) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, "0"))).addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", parametersVar)) .addArgument("transaction").addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQuery", parametersVar)) .addArgument("transaction").addArgument("itemOrder") .addArgument("this." + associatedFieldJavaName) )) ).addContent( new Assignment("this." + associatedFieldJavaName, associatedFieldJavaName) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } javaClass.addContent( new FunctionDeclaration("itemOrderMoveCompleteTransaction").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addContent(new Assignment("itemOrder", "newItemOrder")) .addContent(new FunctionCall("updateRecord").addArgument("transaction").byItself()) .addContent(new FunctionCall("commit", "transaction").byItself()) ).addContent(EMPTY_LINE); } private FunctionDeclaration getItemOrderMoveDeclarationStart() { return new FunctionDeclaration("itemOrderMove").visibility(Visibility.PROTECTED); } private FunctionDeclaration getBaseItemOrderMoveFunction() { return getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "query")) .addArgument(new FunctionArgument("long", "lowerBound")) .addArgument(new FunctionArgument("long", "upperBound")) .addContent(new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()); } private FunctionCall getItemOrderMoveCall() { return new FunctionCall("itemOrderMove").byItself().addArgument("newItemOrder"); } private FunctionCall getDBQueriesUpdateItemOrdersAboveCall() { return new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself(); } private FunctionCall getItemOrderCompleteTransactionFunctionCall() { return new FunctionCall("itemOrderMoveCompleteTransaction").addArguments("newItemOrder", "transaction").byItself(); } private FunctionCall getMaxItemOrderFunctionCall(final Column itemOrderField, final boolean withTransaction, final boolean nullSecondaryVariant) { final FunctionCall functionCall = new FunctionCall("getMaxItemOrder", "DBQueries"); if (withTransaction) functionCall.addArgument("transaction"); else functionCall.addArgument("db"); if (nullSecondaryVariant) functionCall.addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)); else { functionCall.addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)); if (!itemOrderField.isUnique()) functionCall.addArgument(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()))); } return functionCall; } private JavaCodeBlock getItemOrderFunctionCalls(final String functionName, final Column itemOrderField) { final FunctionCall itemOrderFunctionCall = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQuery"); if (itemOrderField.isUnique()) return itemOrderFunctionCall; final String itemOrderAssociatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); itemOrderFunctionCall.addArgument(itemOrderAssociatedFieldJavaName); final FunctionCall itemOrderFunctionCallNullCase = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQueryWithNullSecondaryField"); return new IfBlock(new Condition(new Comparison(itemOrderAssociatedFieldJavaName, "0", Comparison.Comparator.GREATER_THAN))) .addContent(itemOrderFunctionCall) .elseClause(new ElseBlock().addContent(itemOrderFunctionCallNullCase)); } private FunctionCall getItemOrderFunctionCall(final String functionName, final String parameterFunctionName) { return new FunctionCall(functionName, "DBQueries") .addArgument("db") .addArgument(new FunctionCall(parameterFunctionName, parametersVar)) .addArgument(quickQuote(tableName)) .addArgument("id") .addArgument("itemOrder") .byItself(); } private IfBlock checkForItemOrderOperationOnUninitializedBean() { return new IfBlock(new Condition("id == 0")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Item Order operations not allowed on beans that have not been saved to the database")) ); } private static FunctionCall getPreUpdateConversionCall() { return new FunctionCall("preUpdateConversions").byItself(); } private void addUpdateDB() { if (columns.hasLastUpdate()) javaClass.addContent( new FunctionDeclaration("isUpdateOK", "boolean").addContent( new ReturnStatement("updateOK") ) ).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunction = new FunctionDeclaration("updateDB"); if (columns.hasModifiedBy()) updateDBFunction.addArgument(new FunctionArgument("String", "username")); updateDBFunction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCall = new FunctionCall("createRecord").byItself(); if (columns.hasModifiedBy()) createRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id == 0")).addContent(createRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCall = new FunctionCall("updateRecord").byItself(); if (columns.hasModifiedBy()) updateRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); updateDBFunction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ); javaClass.addContent(updateDBFunction).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunctionWithTransaction = new FunctionDeclaration("updateDB", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")); if (columns.hasModifiedBy()) updateDBFunctionWithTransaction.addArgument(new FunctionArgument("String", "username")); updateDBFunctionWithTransaction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCallWithTransaction = new FunctionCall("createRecord").addArgument("transaction"); if (columns.hasModifiedBy()) createRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id == 0")).addContent(new Assignment("id", createRecordCallWithTransaction)).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCallWithTransaction = new FunctionCall("updateRecord").addArgument("transaction").byItself(); if (columns.hasModifiedBy()) updateRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCallWithTransaction).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); updateDBFunctionWithTransaction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ).addContent( new ReturnStatement("-1") ); javaClass.addContent(updateDBFunctionWithTransaction).addContent(EMPTY_LINE); final FunctionDeclaration preUpdateConversionsFunction = new FunctionDeclaration("preUpdateConversions"); preUpdateConversionsFunction.addContent( ifNotDataOK().addContent( new ExceptionThrow("IllegalArgumentException") .addArgument(new FunctionCall("toStrings", "ErrorMessage") .addArgument(new FunctionCall("getErrorMessages"))) ) ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if ((type.equals("int") || type.equals("long")) && !field.startsWith("id")) preUpdateConversionsFunction.addContent( new Assignment(field, new FunctionCall("Strings.get" + capitalize(type) + "Val").addArgument(field + "Str")) ); if (JAVA_TEMPORAL_TYPES.contains(type)) preUpdateConversionsFunction.addContent( new IfBlock(new Condition(new FunctionCall("isEmpty", "Strings").addArgument(field + "Str"), true)).addContent( new Assignment(field, new FunctionCall("convertStringTo" + type).addArgument(field + "Str")) ).elseClause(new ElseBlock().addContent( new Assignment(field, "null") )) ); if (type.equals("Money")) preUpdateConversionsFunction.addContent( new Assignment(field, new ObjectCreation("Money") .addArgument(field + "Str") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))) ); } } javaClass.addContent(preUpdateConversionsFunction).addContent(EMPTY_LINE); } private void addDataOK() { final FunctionDeclaration dataOKFunction = new FunctionDeclaration("isDataOK", "boolean").addContent( new FunctionCall("clearErrorMessages", internalsVar).byItself() ).addContent( new VarDeclaration("boolean", "ok", "true") ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); final IfBlock checkRequired = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Required"))).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "EmptyErrorMessage")) ).addContent(new Assignment("ok", "false")); final IfBlock checkOKAndUnique = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "OK"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "BadFormatErrorMessage")) ).addContent(new Assignment("ok", "false")); if (column.isUnique()) checkOKAndUnique.elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Unique"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "NotUniqueErrorMessage")) ).addContent(new Assignment("ok", "false")) )); dataOKFunction.addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Empty"))).addContent(checkRequired) .elseClause(new ElseBlock().addContent(checkOKAndUnique)) ).addContent(EMPTY_LINE); } } dataOKFunction.addContent( new ReturnStatement("ok") ); javaClass.addContent(dataOKFunction).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final ReturnStatement returnStatement; if ((type.equals("int") || type.equals("long")) && field.startsWith("id")) returnStatement = new ReturnStatement(new Comparison(field, "0", Comparison.Comparator.EQUAL)); else { final String arg; if (type.equals("String")) arg = field; else arg = field + "Str"; returnStatement = new ReturnStatement(new FunctionCall("isEmpty", "Strings").addArgument(arg)); } javaClass.addContent( new FunctionDeclaration("is" + fieldCap + "Empty", "boolean").addContent(returnStatement) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "EmptyErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getRequiredErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final FunctionDeclaration isOKFunction = new FunctionDeclaration("is" + fieldCap + "OK", "boolean"); if ((type.equals("int") || type.equals("long"))) { if (field.startsWith("id")) isOKFunction.addContent( new IfBlock(new Condition("id == 0")).addContent( new ReturnStatement( new Comparison(field, "0", Comparison.Comparator.GREATER_THAN) ) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement( new FunctionCall("isIdOK", column.getAssociatedBeanClass()) .addArgument(field)) ); else { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isNumber", "FormatCheckHelper").addArgument(field + "Str"))); } } else if (JAVA_TEMPORAL_TYPES.contains(type)) { isOKFunction.addContent(new ReturnStatement(new FunctionCall("validate" + type + "Format").addArgument(field + "Str"))); } else if (type.equals("String")) { if (field.equalsIgnoreCase("email") || field.equalsIgnoreCase("e-mail")) { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isEmailValid", "FormatCheckHelper").addArgument(field))); } else isOKFunction.addContent(new ReturnStatement("true")); } else if (type.equals("Money")) { isOKFunction.addContent( new ReturnStatement(new FunctionCall("isValOK", parametersVar + ".getDefaultMoneyFormat()") .addArgument(field + "Str")) ); } else throw new IllegalStateException("Apparently unsupported type " + type + " encountered."); javaClass.addContent(isOKFunction).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "BadFormatErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getBadFormatErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { importsManager.addImport("org.dbbeans.sql.queries.BooleanCheckQuery"); final FunctionCall dbAccessFunctionCall = new FunctionCall("processQuery", "!dbAccess"); javaClass.addContent( new FunctionDeclaration("is" + capitalize(column.getJavaName() + "Unique"), "boolean").addContent( // TODO: IMPLEMENT!!! new ReturnStatement( dbAccessFunctionCall .addArgument(Strings.quickQuote(getNotUniqueQuery(column))) .addArgument(new AnonymousClassCreation("BooleanCheckQuery").setContext(dbAccessFunctionCall, 1).addContent( new FunctionDeclaration("setupPreparedStatement") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .annotate("@Override").addException("SQLException").addContent( new FunctionCall("set" + capitalize(column.getJavaType()), "stat") .addArgument("1").addArgument(column.getJavaName()).byItself() ).addContent( new FunctionCall("setLong", "stat") .addArguments("2", "id").byItself() ) )) ) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "NotUniqueErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getNotUniqueErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } javaClass.addContent( new FunctionDeclaration("getErrorMessages", "List<ErrorMessage>").addContent( new ReturnStatement(new FunctionCall("getErrorMessages", internalsVar)) ) ).addContent(EMPTY_LINE); } private String getNotUniqueQuery(final Column column) { return "SELECT id FROM " + tableName + " WHERE " + column.getSqlName() + "=? AND id <> ?"; } private void addReset() { final FunctionDeclaration resetFunction = new FunctionDeclaration("reset"); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (type.equals("boolean")) resetFunction.addContent(new Assignment(field, "false")); else if (type.equals("int") || type.equals("long")) resetFunction.addContent(new Assignment(field, "0")); else if (type.equals("String")) resetFunction.addContent(new Assignment(field, EMPTY_STRING)); else if (type.equals("Money")) resetFunction.addContent(new Assignment(field, new ObjectCreation("Money") .addArgument("0") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar)))); else resetFunction.addContent(new Assignment(field, "null")); if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("int")) && !field.startsWith("id"))) resetFunction.addContent(new Assignment(field + "Str", EMPTY_STRING)); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) resetFunction.addContent(new FunctionCall("clear", relationship.getJavaName()).byItself()); resetFunction.addContent(new FunctionCall("clearErrorMessages", internalsVar).byItself()); javaClass.addContent(resetFunction).addContent(EMPTY_LINE); final FunctionDeclaration fullResetFunction = new FunctionDeclaration("fullReset").addContent( new FunctionCall("reset").byItself() ).addContent( new Assignment("id", "0") ); for (Column column: columns.getList()) { if (column.isLastUpdate()) fullResetFunction.addContent(new Assignment("lastUpdate", "0")); if (column.isModifiedBy()) fullResetFunction.addContent(new Assignment("modifiedBy", "null")); if (column.isItemOrder()) fullResetFunction.addContent(new Assignment("itemOrder", "0")); } javaClass.addContent(fullResetFunction).addContent(EMPTY_LINE); } private void addDelete() { final FunctionDeclaration deleteFunction = new FunctionDeclaration("delete"); final FunctionCall accessDB = new FunctionCall("addUpdate", "transaction").byItself(); deleteFunction.addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ); if (columns.hasItemOrder()) deleteFunction.addContent( new VarDeclaration("long", "curItemOrder").markAsFinal() ).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new Assignment("curItemOrder", "0") ).elseClause(new ElseBlock().addContent( new Assignment("curItemOrder", "itemOrder") )) ); deleteFunction.addContent( accessDB.addArgument(quickQuote(getDeleteSQLQuery())) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(accessDB).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").addArguments("1", "id").byItself() ) )) ); if (columns.hasItemOrder()) { final IfBlock checkItemOrderNotMax = new IfBlock(new Condition(new Comparison("curItemOrder", "0", Comparison.Comparator.GREATER_THAN))); final Column itemOrderField = columns.getItemOrderField(); if (itemOrderField.isUnique()) checkItemOrderNotMax.addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", null) ); else { final String itemOrderAssociatedField = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); checkItemOrderNotMax.addContent( new IfBlock(new Condition(new Comparison(itemOrderAssociatedField, "0"))).addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", null) ).elseClause(new ElseBlock().addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", itemOrderAssociatedField) ))); } deleteFunction.addContent(checkItemOrderNotMax); } deleteFunction.addContent( new FunctionCall("deleteExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( EMPTY_LINE ).addContent( new FunctionCall("postDeleteActions").byItself() ).addContent( new FunctionCall("fullReset").byItself() ); javaClass.addContent(deleteFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("deleteExtraDbActions").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postDeleteActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private FunctionCall getUpdateItemOrderAboveFunctionCall(final String queryRetrievalFunction, final String itemOrderAssociatedField) { final FunctionCall functionCall = new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall(queryRetrievalFunction, parametersVar)) .addArgument("transaction") .addArgument("curItemOrder"); if (itemOrderAssociatedField != null) functionCall.addArgument(itemOrderAssociatedField); return functionCall; } private FunctionCall getStatSetFunction(final String type, final String field, final int index) { return new FunctionCall("set" + capitalize(type), "stat").byItself().addArguments(Integer.toString(index), field); } private JavaCodeBlock getFieldCreationOrUpdate(final Column column, final int index) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (column.isRequired()) return getStatSetFunction(type, field, index); if (column.hasAssociatedBean()) return new IfBlock(new Condition(new Comparison(field, "0"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types.INTEGER") ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); if (JAVA_TEMPORAL_TYPES.contains(type)) return new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types." + type.toUpperCase()) ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); return getStatSetFunction(type, field, index); } private void addCreate() { int index = 0; final JavaClass recordCreationSetupClass = new JavaClass("RecordCreationSetup").implementsInterface("DBQuerySetup").visibility(Visibility.PRIVATE); final FunctionDeclaration setupStatFunction = new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!column.isId()) { if (type.equals("Money")) { final String suggestedType = Column.getSuggestedType(column.getSqlTypeName(), column.getPrecision()); if (suggestedType.equals("int")) setupStatFunction.addContent( new FunctionCall("setInt", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getIntVal", field)) ); else if (suggestedType.equals("long")) setupStatFunction.addContent( new FunctionCall("setLong", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getVal", field)) ); else throw new IllegalStateException("Money cannot be used with non INTEGER SQL field: " + column.getSqlName()); } else { setupStatFunction.addContent( getFieldCreationOrUpdate(column, ++index) ); } } } javaClass.addContent(recordCreationSetupClass.addContent(setupStatFunction)).addContent(EMPTY_LINE); javaClass.addContent( new JavaClass("RecordUpdateSetup").extendsClass("RecordCreationSetup").visibility(Visibility.PRIVATE).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setupPreparedStatement", "super").byItself().addArgument("stat") ).addContent( new FunctionCall("setLong", "stat").byItself().addArguments(Integer.toString(++index), "id") ) ) ).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunction = new FunctionDeclaration("createRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()).addContent( new FunctionCall("preCreateExtraDbActions").byItself().addArgument("transaction") ).addContent( new VarDeclaration("long", "id", new FunctionCall("createRecord").addArgument("transaction")).markAsFinal() ); addOneToManyRelationshipDBUpdateFunctionCalls(createRecordFunction); createRecordFunction.addContent( new FunctionCall("createExtraDbActions").byItself().addArguments("transaction", "id") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent(EMPTY_LINE).addContent( new Assignment("this.id", "id") ).addContent( new FunctionCall("postCreateActions").byItself() ); javaClass.addContent(createRecordFunction).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunctionWithTransaction = new FunctionDeclaration("createRecord", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE); if (columns.hasItemOrder()) { final Column itemOrderField = columns.getItemOrderField(); final IfBlock uninitializedItemOrderCase = new IfBlock(new Condition(new Comparison("itemOrder", "0"))); if (itemOrderField.isUnique()) uninitializedItemOrderCase.addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) ); else { uninitializedItemOrderCase.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, true), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) )) ); } createRecordFunctionWithTransaction.addContent(uninitializedItemOrderCase).addContent(EMPTY_LINE); } createRecordFunctionWithTransaction.addContent( new ReturnStatement(new FunctionCall("addRecordCreation", "transaction") .addArgument(quickQuote(getInsertSQLQuery())) .addArgument(new ObjectCreation("RecordCreationSetup"))) ); javaClass.addContent(createRecordFunctionWithTransaction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preCreateExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("createExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postCreateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipDBUpdateFunctionCalls(final FunctionDeclaration function) { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) function.addContent( new FunctionCall("update" + capitalize(relationship.getJavaName()) + "InDB").byItself().addArguments("transaction", "id") ); } } private void addUpdate() { final FunctionDeclaration updateRecordFunction = new FunctionDeclaration("updateRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new FunctionCall("preUpdateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("updateRecord").byItself().addArgument("transaction") ); addOneToManyRelationshipDBUpdateFunctionCalls(updateRecordFunction); updateRecordFunction.addContent( new FunctionCall("updateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( new FunctionCall("postUpdateActions").byItself() ); javaClass.addContent(updateRecordFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateRecord").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE).addContent( new FunctionCall("addUpdate", "transaction").byItself() .addArgument(quickQuote(getUpdateSQLQuery())) .addArgument(new ObjectCreation("RecordUpdateSetup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preUpdateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postUpdateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipInDB() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) { final FunctionDeclaration updateRelationshipFunction = new FunctionDeclaration("update" + capitalize(relationship.getJavaName()) + "InDB") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")) .visibility(Visibility.PRIVATE); final FunctionCall dbAccessFunction = new FunctionCall("addUpdate", "transaction").byItself(); updateRelationshipFunction.addContent( dbAccessFunction .addArgument(quickQuote(getDeleteOneToManyRelationshipQuery(relationship.getTable(), relationship.getIdSqlName()))) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(dbAccessFunction).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").byItself().addArguments("1", "id") ) )) ).addContent(EMPTY_LINE); final String var = uncapitalize(relationship.getBeanClass()); updateRelationshipFunction.addContent( new ForLoop(relationship.getBeanClass() + " " + var + ": " + relationship.getJavaName()).addContent( new FunctionCall("resetId", var).byItself() ).addContent( new FunctionCall("setId" + beanName, var).addArgument("id").byItself() ).addContent( new FunctionCall("updateDB", var).addArgument("transaction").byItself() ) ); javaClass.addContent(updateRelationshipFunction).addContent(EMPTY_LINE); } } } private void addTemporalFunctions() { if (types.contains("Date")) { javaClass.addContent( new FunctionDeclaration("formatDate", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Date", "date")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("date") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToDate", "Date").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getDateFromYYMD", "Dates").addArguments("str", quickQuote("-")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Date", "date")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateDateFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputDateFormat", "simpleInputDateFormat", new ObjectCreation("SimpleInputDateFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputDateFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Time")) { javaClass.addContent( new FunctionDeclaration("formatTime", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Time", "time")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getTimeInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("time") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTime", "Time").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimeFromString", "Dates").addArguments("str", quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Time", "time")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimeFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimeFormat", "simpleInputTimeFormat", new ObjectCreation("SimpleInputTimeFormat").addArgument(quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimeFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Timestamp")) { javaClass.addContent( new FunctionDeclaration("formatTimestamp", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Timestamp", "timestamp")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateTimeInstance", "DateFormat").addArguments("DateFormat.LONG", "DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("timestamp") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTimestamp", "Timestamp").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimestampFromYYMD", "Dates").addArguments("str", quickQuote("-"), quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Timestamp", "timestamp")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimestampFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimestampFormat", "simpleInputTimestampFormat", new ObjectCreation("SimpleInputTimestampFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-"), quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimestampFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } } private void addGetAll() { javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getAll").addArgument(new FunctionCall("getOrderByFields", parametersVar))) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "orderBy")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("null", "orderBy", "null")) ) ).addContent(EMPTY_LINE); final ObjectCreation newBeanFromFields = new ObjectCreation(beanName); int index = 0; for (Column column: columns.getList()) { ++index; final String javaType = column.getJavaType(); if (javaType.equals("Money")) newBeanFromFields .addArgument(new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(index))) .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))); else newBeanFromFields .addArgument(new FunctionCall("get" + capitalize(javaType), "rs") .addArguments(Integer.toString(index))); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) newBeanFromFields.addArgument(new FunctionCall("getSelection", relationship.getBeanClass()) .addArgument(new OperatorExpression("\"id_" + uncamelize(beanVarName) + "=\"", new FunctionCall("getLong", "rs").addArgument("1"), OperatorExpression.Operator.ADD))); javaClass.addContent( new JavaClass("GetSelectionQueryProcess") .implementsInterface("DBQueryRetrieveData<List<" + beanName + ">>") .visibility(Visibility.PRIVATE) .markAsStatic() .addContent( new FunctionDeclaration("processResultSet", "List<" + beanName + ">") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent( VarDeclaration.createListDeclaration(beanName, "list") .markAsFinal() ).addContent(EMPTY_LINE).addContent( new WhileBlock(new Condition(new FunctionCall("next", "rs"))).addContent( new FunctionCall("add", "list") .byItself() .addArgument(newBeanFromFields) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("list") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("whereClause", "null")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new ReturnStatement(new FunctionCall("getSelection") .addArgument("whereClause") .addArguments(new FunctionCall("getOrderByFields", parametersVar)) .addArgument("setup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("String", "orderBy")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .andCondition(new Condition(new Comparison("setup", "null", Comparison.Comparator.NEQ)))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot accept setup code without a WHERE clause.")) ) ).addContent(EMPTY_LINE).addContent( new VarDeclaration("StringBuilder", "query", new ObjectCreation("StringBuilder")).markAsFinal() ).addContent( new FunctionCall("append", "query").addArgument(quickQuote(getAllFieldsQuery())).byItself() ).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" WHERE "))).addArgument("whereClause").byItself() ) ).addContent( new IfBlock(new Condition(new Comparison("orderBy", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" ORDER BY "))).addArgument("orderBy").byItself() ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .orCondition(new Condition(new Comparison("setup", "null")))).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument("setup") .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE); } private void addGetIdNamePairs() { javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").markAsStatic().addArguments( new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs").addArguments("null", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").visibility(Visibility.PROTECTED).markAsStatic().addArguments( new FunctionArgument("String", "whereClause"), new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs", "DBQueries").addArguments("db", quickQuote(tableName), "whereClause", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); } private void addGetCount() { javaClass.addContent( new FunctionDeclaration("getCount", "long").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getLongCount", "DBQueries").addArguments("db", quickQuote(tableName))) ) ).addContent(EMPTY_LINE); } private void addIdOK() { javaClass.addContent( new FunctionDeclaration("isIdOK", "boolean").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent( new ReturnStatement(new FunctionCall("isIdOK", "DBQueries").addArguments("db", quickQuote(tableName), "id")) ) ).addContent(EMPTY_LINE); } private void addHumanReadableTitle() { javaClass.addContent( new FunctionDeclaration("getHumanReadableTitle", "String") .markAsStatic() .addArgument(new FunctionArgument("long", "id")) .addContent( new IfBlock(new Condition("id == 0")).addContent( new ReturnStatement("\"\"") ) ) .addContent(EMPTY_LINE) .addContent( new ReturnStatement(new FunctionCall("getHumanReadableTitle", "DBQueries") .addArguments("db", quickQuote(tableName), "id") .addArgument(new FunctionCall("getNamingFields", parametersVar))) ) ).addContent(EMPTY_LINE); } private void addSetLocale() { javaClass.addContent( new FunctionDeclaration("setLocale").addArgument(new FunctionArgument("Locale", "locale")).addContent( new FunctionCall("setLocale", internalsVar).addArgument("locale").byItself() ) ).addContent(EMPTY_LINE); } private void createSourceCode() { sourceFile.setStartComment(SourceFiles.getCommentAndVersion()); addImports(); addClassModifiers(); addProperties(); addConstructors(); addSetIdFunction(); addEquals(); addToString(); addSetters(); addGetters(); addLabelGetters(); addRequiredIndicators(); addUniqueIndicators(); addOneToManyRelationshipManagement(); addItemOrderManagement(); addUpdateDB(); addDataOK(); addReset(); addDelete(); addCreate(); addUpdate(); addOneToManyRelationshipInDB(); addTemporalFunctions(); addGetAll(); addGetIdNamePairs(); addGetCount(); addIdOK(); addHumanReadableTitle(); addSetLocale(); } private String getReadSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); buf.append(" WHERE id=?"); return buf.toString(); } private String getAllFieldsQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); buf.append(name); buf.append(", "); } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); return buf.toString(); } private String getReadSQLQueryOneToManyRelationship(final String tableName, final String indexField) { return "SELECT id FROM " + tableName + " WHERE " + indexField + "=?"; } private String getDeleteSQLQuery() { return "DELETE FROM " + tableName + " WHERE id=?"; } private String getInsertSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("INSERT INTO "); buf.append(tableName); buf.append(" ("); int count = 0; for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { count++; buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(") VALUES ("); for (int i = 0; i < count; i++) buf.append("?, "); buf.delete(buf.length() - 2, buf.length()); buf.append(")"); return buf.toString(); } private String getUpdateSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("UPDATE "); buf.append(tableName); buf.append(" SET "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append("=?, "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" WHERE id=?"); if (columns.hasLastUpdate()) buf.append(" AND last_update=?"); return buf.toString(); } private String getDeleteOneToManyRelationshipQuery(final String tableName, final String indexField) { return "DELETE FROM " + tableName + " WHERE " + indexField + "=?"; } private FunctionDeclaration getTemporalConvertToStringFunction(final String className, final String varName) { return new FunctionDeclaration("convert" + className + "ToString", "String").addArgument(new FunctionArgument(className, varName)).addContent( new IfBlock(new Condition(new Comparison(varName, "null"))).addContent( new ReturnStatement(EMPTY_STRING) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("toString", varName)) ).visibility(Visibility.PROTECTED); } private void addIndicator(final String javaName, final String indicatorName, final boolean value, final boolean isFinal) { final FunctionDeclaration indicator = new FunctionDeclaration("is" + capitalize(javaName) + indicatorName, "boolean"); if (isFinal) indicator.markAsFinal(); if (value) indicator.addContent(new ReturnStatement("true")); else indicator.addContent(new ReturnStatement("false")); javaClass.addContent(indicator).addContent(EMPTY_LINE); } }
package org.beanmaker; import java.util.List; import java.util.Set; import org.jcodegen.java.AnonymousClassCreation; import org.jcodegen.java.Assignment; import org.jcodegen.java.Comparison; import org.jcodegen.java.Condition; import org.jcodegen.java.ConstructorDeclaration; import org.jcodegen.java.ElseBlock; import org.jcodegen.java.ElseIfBlock; import org.jcodegen.java.ExceptionThrow; import org.jcodegen.java.ForLoop; import org.jcodegen.java.FunctionArgument; import org.jcodegen.java.FunctionCall; import org.jcodegen.java.FunctionDeclaration; import org.jcodegen.java.GenericType; import org.jcodegen.java.IfBlock; import org.jcodegen.java.JavaClass; import org.jcodegen.java.JavaCodeBlock; import org.jcodegen.java.LineOfCode; import org.jcodegen.java.ObjectCreation; import org.jcodegen.java.OperatorExpression; import org.jcodegen.java.ReturnStatement; import org.jcodegen.java.VarDeclaration; import org.jcodegen.java.Visibility; import org.jcodegen.java.WhileBlock; import org.dbbeans.util.Strings; import static org.beanmaker.SourceFiles.chopId; import static org.dbbeans.util.Strings.*; public class BaseClassSourceFile extends BeanCodeWithDBInfo { private final Set<String> types; private final String internalsVar; private final String parametersVar; public BaseClassSourceFile(final String beanName, final String packageName, final Columns columns, final String tableName) { super(beanName, packageName, "Base", columns, tableName); internalsVar = beanVarName + "Internals"; parametersVar = Strings.uncamelize(beanName).toUpperCase() + "_PARAMETERS"; types = columns.getJavaTypes(); createSourceCode(); } private void addImports() { importsManager.addImport("java.sql.PreparedStatement"); importsManager.addImport("java.sql.ResultSet"); importsManager.addImport("java.sql.SQLException"); importsManager.addImport("java.util.ArrayList"); importsManager.addImport("java.util.List"); importsManager.addImport("java.util.Locale"); importsManager.addImport("org.beanmaker.util.BeanInternals"); importsManager.addImport("org.beanmaker.util.DbBeanInterface"); importsManager.addImport("org.beanmaker.util.DBQueries"); importsManager.addImport("org.beanmaker.util.ErrorMessage"); importsManager.addImport("org.beanmaker.util.IdNamePair"); importsManager.addImport("org.dbbeans.sql.DBQueryRetrieveData"); importsManager.addImport("org.dbbeans.sql.DBQuerySetup"); importsManager.addImport("org.dbbeans.sql.DBQuerySetupProcess"); importsManager.addImport("org.dbbeans.sql.DBTransaction"); importsManager.addImport("org.dbbeans.util.Strings"); if (columns.containsNumericalData()) importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); if (types.contains("Date")) { importsManager.addImport("java.sql.Date"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); } if (types.contains("Time")) { importsManager.addImport("java.sql.Time"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputTimeFormat"); } if (types.contains("Timestamp")) { importsManager.addImport("java.sql.Timestamp"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); importsManager.addImport("org.dbbeans.util.SimpleInputTimestampFormat"); } if (types.contains("Money")) { importsManager.addImport("org.dbbeans.util.Money"); importsManager.addImport("org.dbbeans.util.MoneyFormat"); } if (columns.hasLastUpdate()) importsManager.addImport("org.dbbeans.util.Dates"); } private void addClassModifiers() { javaClass.markAsAbstract().extendsClass("DbBean").implementsInterface("DbBeanInterface"); } private void addProperties() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final VarDeclaration declaration; if (type.equals("String")) declaration = new VarDeclaration("String", field, EMPTY_STRING); else if (type.equals("Money")) declaration = new VarDeclaration("Money", field, new ObjectCreation("Money") .addArgument("0") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))); else declaration = new VarDeclaration(type, field); addProperty(declaration); if (type.equals("Money")) addProperty(new VarDeclaration("String", field + "Str", new FunctionCall("toString", field))); if (JAVA_TEMPORAL_TYPES.contains(type) || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) addProperty(new VarDeclaration("String", field + "Str", EMPTY_STRING)); } if (columns.hasLastUpdate()) addProperty("boolean", "updateOK"); if (columns.hasOneToManyRelationships()) { boolean first = true; for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { if (first) { newLine(); first = false; } addProperty(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName())); } } newLine(); javaClass.addContent(new VarDeclaration("String", "DATABASE_TABLE_NAME", quickQuote(tableName)).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); javaClass.addContent(new VarDeclaration("String", "DATABASE_FIELD_LIST", quickQuote(getStaticFieldList())).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); newLine(); javaClass.addContent( new VarDeclaration("BeanInternals", internalsVar, new ObjectCreation("BeanInternals").addArgument(quickQuote(bundleName))).markAsFinal().visibility(Visibility.PROTECTED) ); final String parametersClass = beanName + "Parameters"; javaClass.addContent( new VarDeclaration(parametersClass, parametersVar, new ObjectCreation(parametersClass)).markAsFinal().markAsStatic().visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); if (columns.hasExtraFields()) { for (ExtraField extraField: columns.getExtraFields()) { javaClass.addContent(new LineOfCode(extraField.toString())); if (extraField.requiresImport()) importsManager.addImport(extraField.getRequiredImport()); if (extraField.requiresSecondaryImport()) importsManager.addImport(extraField.getSecondaryRequiredImport()); if (extraField.requiresTernaryImport()) importsManager.addImport(extraField.getTernaryRequiredImport()); } newLine(); } } private String getStaticFieldList() { final StringBuilder list = new StringBuilder(); for (Column column: columns.getList()) list.append(tableName).append(".").append(column.getSqlName()).append(", "); list.delete(list.length() - 2, list.length()); return list.toString(); } private void addConstructors() { javaClass.addContent(getBaseConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getIdArgumentConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getCopyConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getFieldConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getResultSetConstructor()).addContent(EMPTY_LINE); } private ConstructorDeclaration getBaseConstructor() { return javaClass.createConstructor(); } private ConstructorDeclaration getIdArgumentConstructor() { return getBaseConstructor().addArgument(new FunctionArgument("long", "id")).addContent("setId(id);"); } private ConstructorDeclaration getCopyConstructor() { final ConstructorDeclaration copyConstructor = getBaseConstructor(); copyConstructor.addArgument(new FunctionArgument(beanName + "Base", "model")).addContent(new Assignment("id", "0")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (field.equals("itemOrder")) copyConstructor.addContent(new Assignment("itemOrder", "0")); else if (field.startsWith("id") || type.equals("boolean") || type.equals("String")) copyConstructor.addContent(new Assignment(field, "model." + field)); else copyConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument("model." + field).byItself()); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); copyConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": model." + javaName).addContent( new FunctionCall("add", javaName).byItself().addArgument( new ObjectCreation(beanClass).addArgument(new FunctionCall("getId", beanObject)) ) ) ); } return copyConstructor; } private ConstructorDeclaration getFieldConstructor() { final ConstructorDeclaration fieldConstructor = getBaseConstructor().visibility(Visibility.PROTECTED); for (Column column: columns.getList()) fieldConstructor.addArgument(new FunctionArgument(column.getJavaType(), column.getJavaName())); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (field.startsWith("id") || field.equals("itemOrder") || type.equals("boolean") || type.equals("String")) fieldConstructor.addContent(new Assignment("this." + field, field)); else fieldConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument(field).byItself()); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); fieldConstructor.addArgument(new FunctionArgument(new GenericType("List", beanClass).toString(), javaName)); fieldConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": " + javaName).addContent( new FunctionCall("add", "this." + javaName).byItself().addArgument(beanObject) ) ); } return fieldConstructor; } private ConstructorDeclaration getResultSetConstructor() { final ConstructorDeclaration rsConstructor = getBaseConstructor().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("ResultSet", "rs")).addException("SQLException"); for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) rsConstructor.addArgument(new FunctionArgument(new GenericType("List", relationship.getBeanClass()).toString(), relationship.getJavaName())); final FunctionCall thisCall = new FunctionCall("this").byItself(); int index = 0; for (Column column: columns.getList()) { if (column.getJavaType().equals("Money")) thisCall.addArgument(new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(++index)))); else thisCall.addArgument(new FunctionCall("get" + capitalize(column.getJavaType()), "rs").addArgument(Integer.toString(++index))); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) thisCall.addArgument(relationship.getJavaName()); return rsConstructor.addContent(thisCall); } private void addSetIdFunction() { final List<OneToManyRelationship> relationships = columns.getOneToManyRelationships(); final FunctionDeclaration function = new FunctionDeclaration("setId") .addArgument(new FunctionArgument("long", "id")); // function inner class for database row retrieval final JavaClass databaseInnerClass = new JavaClass("DataFromDBQuery").visibility(Visibility.NONE) .implementsInterface("DBQuerySetupProcess"); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (type.equals("int") || type.equals("long")) databaseInnerClass.addContent(new VarDeclaration(type, field, "0")); else if (type.equals("String") || JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money")) databaseInnerClass.addContent(new VarDeclaration(type, field, "null")); else if (type.equals("boolean")) databaseInnerClass.addContent(new VarDeclaration(type, field, "false")); else throw new IllegalStateException("Java type not allowed: " + type); } } databaseInnerClass.addContent(new VarDeclaration("boolean", "idOK", "false")) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRS = getInnerClassProcessRSFunctionStart(); final IfBlock ifRsNext = new IfBlock(new Condition("rs.next()")); int index = 0; for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { ++index; if (type.equals("Money")) ifRsNext.addContent(new Assignment(field, new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(index))) .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar)))); else { final String getterName = "get" + capitalize(type); ifRsNext.addContent(new Assignment(field, new FunctionCall(getterName, "rs") .addArgument(Integer.toString(index)))); } } } ifRsNext.addContent(new Assignment("idOK", "true")); processRS.addContent(ifRsNext); databaseInnerClass.addContent(processRS); function.addContent(databaseInnerClass).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final JavaClass extraDBInnerClass = new JavaClass("DataFromDBQuery" + capitalize(relationship.getJavaName())) .visibility(Visibility.NONE).implementsInterface("DBQuerySetupProcess") .addContent(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName()).markAsFinal()) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRSExtra = getInnerClassProcessRSFunctionStart() .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", relationship.getJavaName()) .byItself() .addArgument(new ObjectCreation(relationship.getBeanClass()) .addArgument("rs.getLong(1)")))); extraDBInnerClass.addContent(processRSExtra); function.addContent(extraDBInnerClass).addContent(EMPTY_LINE); } } // check for bad ID function.addContent(new IfBlock(new Condition("id <= 0")).addContent("throw new IllegalArgumentException(\"id = \" + id + \" <= 0\");")) .addContent(EMPTY_LINE); // instantiate DBQuery inner class & use it to retrieve data function.addContent( new VarDeclaration("DataFromDBQuery", "dataFromDBQuery", new ObjectCreation("DataFromDBQuery")).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQuery())) .addArgument("dataFromDBQuery") ).addContent(EMPTY_LINE); // check if data was returned function.addContent( new IfBlock(new Condition("!dataFromDBQuery.idOK")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"id = \" + id + \" does not exist\"") ) ).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final String cappedJavaName = capitalize(relationship.getJavaName()); function.addContent( new VarDeclaration("DataFromDBQuery" + cappedJavaName, "dataFromDBQuery" + cappedJavaName, new ObjectCreation("DataFromDBQuery" + cappedJavaName)).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQueryOneToManyRelationship(relationship.getTable(), relationship.getIdSqlName()))) .addArgument("dataFromDBQuery" + cappedJavaName) ).addContent(EMPTY_LINE); } } // extra DB actions function.addContent("initExtraDbActions(id);").addContent(EMPTY_LINE); // fields assignment function.addContent(new Assignment("this.id", "id")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { function.addContent(new Assignment("this." + field, "dataFromDBQuery." + field)); if (JAVA_TEMPORAL_TYPES.contains(type)) function.addContent( new Assignment(field +"Str", new FunctionCall("convert" + type + "ToString").addArgument(field)) ); if ((type.equals("int") || type.equals("long")) && !field.equals("itemOrder") && !field.startsWith("id")) function.addContent( new Assignment(field +"Str", new FunctionCall("valueOf", "String").addArgument(field)) ); if (type.equals("Money")) function.addContent( new Assignment(field +"Str", new FunctionCall("toString", field)) ); } } for (OneToManyRelationship relationship: relationships) if (!relationship.isListOnly()) function.addContent( new Assignment("this." + relationship.getJavaName(), "dataFromDBQuery" + capitalize(relationship.getJavaName()) + "." + relationship.getJavaName()) ); function.addContent(EMPTY_LINE).addContent("postInitActions();"); javaClass.addContent(function).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("initExtraDbActions") .visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "id")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postInitActions") .visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("resetId") .addContent("id = 0;") ).addContent(EMPTY_LINE); } private FunctionDeclaration getInnerClassSetupPSWithIdFunction() { return new FunctionDeclaration("setupPreparedStatement") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent("stat.setLong(1, id);"); } private FunctionDeclaration getInnerClassProcessRSFunctionStart() { return new FunctionDeclaration("processResultSet") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("ResultSet", "rs")); } private void addEquals() { javaClass.addContent( new FunctionDeclaration("equals", "boolean").addArgument(new FunctionArgument("Object", "object")).annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition("object instanceof " + beanName)).addContent( new ReturnStatement("((" + beanName + ") object).getId() == id") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("hashCode", "int").annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("-1") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("31 * ((int) (id ^ (id >>> 32))) + 17") ) ).addContent(EMPTY_LINE); } private void addToString() { final String returnExpression = "\"[" + beanName + " - " + tableName + " javaClass.addContent( new FunctionDeclaration("toString", "String").annotate("@Override").addContent( new ReturnStatement(returnExpression) ) ).addContent(EMPTY_LINE); } private void addSetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id") && !field.equals("lastUpdate") && !field.equals("modifiedBy") && !field.equals("itemOrder")) { final FunctionDeclaration setter = new FunctionDeclaration("set" + capitalize(field)) .addArgument(new FunctionArgument(type, field)); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new Assignment("this." + field, "null") ).elseClause(new ElseBlock().addContent( new Assignment("this." + field, new ObjectCreation(type) .addArgument(new FunctionCall("getTime", field))) )) ); else setter.addContent( new Assignment("this." + field, field) ); if (type.equals("int") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Integer").addArgument(field)) ); if (type.equals("long") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Long").addArgument(field)) ); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new Assignment(field + "Str", new FunctionCall("convert" + capitalize(type) + "ToString").addArgument(field)) ); if (type.equals("Money")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", field)) ); javaClass.addContent(setter).addContent(EMPTY_LINE); if (column.couldHaveAssociatedBean() && column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final String associatedBeanObject = uncapitalize(chopId(field)); final FunctionDeclaration fromObjectSetter = new FunctionDeclaration("set" + capitalize(associatedBeanObject)) .addArgument(new FunctionArgument(associatedBeanClass, associatedBeanObject)) .addContent(new IfBlock(new Condition(new Comparison(new FunctionCall("getId", associatedBeanObject), "0"))) .addContent(new ExceptionThrow("IllegalArgumentException") .addArgument(quickQuote("Cannot accept uninitialized " + associatedBeanClass + " bean (id = 0) as argument.")))) .addContent(EMPTY_LINE) .addContent(new Assignment(field, new FunctionCall("getId", associatedBeanObject))); javaClass.addContent(fromObjectSetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id"))) { final FunctionDeclaration strSetter = new FunctionDeclaration("set" + capitalize(field) + "Str") .addArgument(new FunctionArgument("String", field + "Str")) .addContent(new Assignment("this." + field + "Str", field + "Str")); javaClass.addContent(strSetter).addContent(EMPTY_LINE); } } } } private void addGetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String prefix; if (type.equals("boolean")) prefix = "is"; else prefix = "get"; final FunctionDeclaration getter = new FunctionDeclaration(prefix + capitalize(field), type); if (JAVA_TEMPORAL_TYPES.contains(type)) getter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent(new ReturnStatement("null")) ).addContent( EMPTY_LINE ).addContent( new ReturnStatement(new ObjectCreation(type).addArgument(new FunctionCall("getTime", field))) ); else getter.addContent( new ReturnStatement(field) ); javaClass.addContent(getter).addContent(EMPTY_LINE); if (column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final FunctionDeclaration associatedBeanGetter = new FunctionDeclaration("get" + chopId(field), associatedBeanClass) .addContent(new ReturnStatement(new ObjectCreation(associatedBeanClass).addArgument(field))); javaClass.addContent(associatedBeanGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) { final FunctionDeclaration strGetter = new FunctionDeclaration("get" + capitalize(field) + "Str", "String") .addContent(new ReturnStatement(field + "Str")); javaClass.addContent(strGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type)) { final String capField = capitalize(field); final FunctionDeclaration formattedGetter = new FunctionDeclaration("get" + capField + "Formatted", "String") .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Empty"))) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Required"))) .addContent(getCannotDisplayBadDataException())) .addContent(new ReturnStatement(EMPTY_STRING))) .addContent(EMPTY_LINE) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "OK"), true)).addContent(getCannotDisplayBadDataException())) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("format" + type).addArgument(new FunctionCall("convertStringTo" + type).addArgument(field + "Str")))); javaClass.addContent(formattedGetter).addContent(EMPTY_LINE); } if (type.equals("boolean")) { final FunctionDeclaration booleanValGetter = new FunctionDeclaration("get" + capitalize(field) + "Val", "String") .addContent(new IfBlock(new Condition(field)) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("true_value"))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("false_value")))); javaClass.addContent(booleanValGetter).addContent(EMPTY_LINE); } } } private void addLabelGetters() { for (Column column: columns.getList()) { final String field = column.getJavaName(); if (!column.isSpecial()) javaClass.addContent( new FunctionDeclaration("get" + capitalize(field) + "Label", "String").addContent( new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } private ExceptionThrow getCannotDisplayBadDataException() { return new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot display bad data")); } private void addRequiredIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "Required", column.isRequired(), false); } private void addUniqueIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "ToBeUnique", column.isUnique(), false); } private void addOneToManyRelationshipManagement() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { final String beanClass = relationship.getBeanClass(); final String itemName = uncapitalize(beanClass); final String listName = relationship.getJavaName(); if (relationship.isListOnly()) { importsManager.addImport("org.dbbeans.sql.DBQuerySetupRetrieveData"); final FunctionDeclaration preparedStatementSetup = new FunctionDeclaration("setupPreparedStatement") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent(new FunctionCall("setLong", "stat") .addArgument("1") .addArgument("id") .byItself()); final FunctionCall dbAccessFunction = new FunctionCall("processQuery", "dbAccess").byItself(); final FunctionDeclaration listGetter = new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(VarDeclaration.createListDeclaration(beanClass, listName).markAsFinal()) .addContent(EMPTY_LINE) .addContent(dbAccessFunction .addArgument(new OperatorExpression(quickQuote("SELECT ") + " + " + beanClass + ".DATABASE_FIELD_LIST + " + quickQuote(" FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=? ORDER BY "), new FunctionCall("getOrderByFields", beanClass + "." + Strings.uncamelize(beanClass).toUpperCase() + "_PARAMETERS"), OperatorExpression.Operator.ADD)) .addArgument(new AnonymousClassCreation("DBQuerySetupProcess").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(EMPTY_LINE) .addContent(new FunctionDeclaration("processResultSet") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", listName).byItself() .addArgument(new ObjectCreation(beanClass) .addArgument("rs"))))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(listName)); javaClass.addContent(listGetter).addContent(EMPTY_LINE); final FunctionCall dbAccessForCountFunction = new FunctionCall("processQuery", "dbAccess"); final FunctionDeclaration countGetter = new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement( dbAccessForCountFunction .addArgument(quickQuote("SELECT COUNT(id) FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=?")) .addArgument(new AnonymousClassCreation("DBQuerySetupRetrieveData<Long>").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(new FunctionDeclaration("processResultSet", "Long") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new FunctionCall("next", "rs").byItself()) .addContent(new ReturnStatement(new FunctionCall("getLong", "rs").addArgument("1"))))) )); javaClass.addContent(countGetter).addContent(EMPTY_LINE); } else { importsManager.addImport("java.util.Collections"); javaClass.addContent( new FunctionDeclaration("add" + beanClass) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(new FunctionCall("add", listName).byItself() .addArgument(itemName)) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + beanClass, beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("get", listName).addArgument("index"))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("insert" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("add", listName).addArgument("index").addArgument(itemName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("delete" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("remove", listName).addArgument("index").byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("clear" + capitalize(listName)) .addContent(new FunctionCall("clear", listName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(new ReturnStatement(new FunctionCall("unmodifiableList", "Collections").addArgument(listName))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement(new FunctionCall("size", listName))) ).addContent(EMPTY_LINE); } } } private IfBlock getOneToManyRelationshipIndexOutOfBoundTest(final String listName) { return new IfBlock(new Condition(new Comparison("index", "0", Comparison.Comparator.LESS_THAN)) .orCondition(new Condition(new Comparison("index", new FunctionCall("size", listName), Comparison.Comparator.GT_EQUAL)))) .addContent(new ExceptionThrow("IndexOutOfBoundsException") .addArgument(getOneToManyRelationshipIndexOutOfBoundExceptionText(listName))); } private String getOneToManyRelationshipIndexOutOfBoundExceptionText(final String listName) { return "\"Bounds : 0-\" + " + listName + ".size() + \", index : \" + index"; } private void addItemOrderManagement() { if (!columns.hasItemOrder()) return; final Column itemOrderField = columns.getItemOrderField(); javaClass.addContent( new FunctionDeclaration("isFirstItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new ReturnStatement("itemOrder == 1") ) ).addContent(EMPTY_LINE); final FunctionDeclaration isLastItemOrderFunction = new FunctionDeclaration("isLastItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE); if (!itemOrderField.isUnique()) isLastItemOrderFunction.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, true))) ).addContent(EMPTY_LINE) ); isLastItemOrderFunction.addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, false))) ); javaClass.addContent(isLastItemOrderFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveUp").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isFirstItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot move Item Order above position 1 which it currently occupies")) ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveUp", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveDown").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"Cannot move Item Order below max position: \" + itemOrder") ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveDown", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder++;") ) ).addContent(EMPTY_LINE); if (itemOrderField.isUnique()) { javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } else { final String associatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); final String associatedFieldJavaFunction = "get" + camelize(itemOrderField.getItemOrderAssociatedField()); javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addArgument(new FunctionArgument("long...", "parameters")).addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound", "parameters").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQueryWithNullSecondaryField", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) ).addElseIfClause(new ElseIfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQueryWithNullSecondaryField", parametersVar)) .addArgument(beanVarName) )).elseClause(new ElseBlock().addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "queryDest")) .addArgument(new FunctionArgument("long", "destLowerBound")) .addArgument(new FunctionArgument("String", "queryOrig")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound", associatedFieldJavaName) )) ).addContent( new IfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder", associatedFieldJavaName) )) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderReassociateWith").addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Bean must be saved in DB before reassociation.") ) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, associatedFieldJavaName))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Association already exists.") ) ).addContent(EMPTY_LINE).addContent( new FunctionCall("itemOrderMove").addArgument(associatedFieldJavaName).byItself() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart().addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new VarDeclaration("long", "newItemOrder") ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)) .addArgument(associatedFieldJavaName), "1", OperatorExpression.Operator.ADD)) )) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, "0"))).addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", parametersVar)) .addArgument("transaction").addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQuery", parametersVar)) .addArgument("transaction").addArgument("itemOrder") .addArgument("this." + associatedFieldJavaName) )) ).addContent( new Assignment("this." + associatedFieldJavaName, associatedFieldJavaName) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } javaClass.addContent( new FunctionDeclaration("itemOrderMoveCompleteTransaction").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addContent(new Assignment("itemOrder", "newItemOrder")) .addContent(new FunctionCall("updateRecord").addArgument("transaction").byItself()) .addContent(new FunctionCall("commit", "transaction").byItself()) ).addContent(EMPTY_LINE); } private FunctionDeclaration getItemOrderMoveDeclarationStart() { return new FunctionDeclaration("itemOrderMove").visibility(Visibility.PROTECTED); } private FunctionDeclaration getBaseItemOrderMoveFunction() { return getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "query")) .addArgument(new FunctionArgument("long", "lowerBound")) .addArgument(new FunctionArgument("long", "upperBound")) .addContent(new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()); } private FunctionCall getItemOrderMoveCall() { return new FunctionCall("itemOrderMove").byItself().addArgument("newItemOrder"); } private FunctionCall getDBQueriesUpdateItemOrdersAboveCall() { return new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself(); } private FunctionCall getItemOrderCompleteTransactionFunctionCall() { return new FunctionCall("itemOrderMoveCompleteTransaction").addArguments("newItemOrder", "transaction").byItself(); } private FunctionCall getMaxItemOrderFunctionCall(final Column itemOrderField, final boolean withTransaction, final boolean nullSecondaryVariant) { final FunctionCall functionCall = new FunctionCall("getMaxItemOrder", "DBQueries"); if (withTransaction) functionCall.addArgument("transaction"); else functionCall.addArgument("db"); if (nullSecondaryVariant) functionCall.addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)); else { functionCall.addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)); if (!itemOrderField.isUnique()) functionCall.addArgument(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()))); } return functionCall; } private JavaCodeBlock getItemOrderFunctionCalls(final String functionName, final Column itemOrderField) { final FunctionCall itemOrderFunctionCall = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQuery"); if (itemOrderField.isUnique()) return itemOrderFunctionCall; final String itemOrderAssociatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); itemOrderFunctionCall.addArgument(itemOrderAssociatedFieldJavaName); final FunctionCall itemOrderFunctionCallNullCase = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQueryWithNullSecondaryField"); return new IfBlock(new Condition(new Comparison(itemOrderAssociatedFieldJavaName, "0", Comparison.Comparator.GREATER_THAN))) .addContent(itemOrderFunctionCall) .elseClause(new ElseBlock().addContent(itemOrderFunctionCallNullCase)); } private FunctionCall getItemOrderFunctionCall(final String functionName, final String parameterFunctionName) { return new FunctionCall(functionName, "DBQueries") .addArgument("db") .addArgument(new FunctionCall(parameterFunctionName, parametersVar)) .addArgument(quickQuote(tableName)) .addArgument("id") .addArgument("itemOrder") .byItself(); } private IfBlock checkForItemOrderOperationOnUninitializedBean() { return new IfBlock(new Condition("id == 0")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Item Order operations not allowed on beans that have not been saved to the database")) ); } private static FunctionCall getPreUpdateConversionCall() { return new FunctionCall("preUpdateConversions").byItself(); } private void addUpdateDB() { if (columns.hasLastUpdate()) javaClass.addContent( new FunctionDeclaration("isUpdateOK", "boolean").addContent( new ReturnStatement("updateOK") ) ).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunction = new FunctionDeclaration("updateDB"); if (columns.hasModifiedBy()) updateDBFunction.addArgument(new FunctionArgument("String", "username")); updateDBFunction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCall = new FunctionCall("createRecord").byItself(); if (columns.hasModifiedBy()) createRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id == 0")).addContent(createRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCall = new FunctionCall("updateRecord").byItself(); if (columns.hasModifiedBy()) updateRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); updateDBFunction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ); javaClass.addContent(updateDBFunction).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunctionWithTransaction = new FunctionDeclaration("updateDB", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")); if (columns.hasModifiedBy()) updateDBFunctionWithTransaction.addArgument(new FunctionArgument("String", "username")); updateDBFunctionWithTransaction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCallWithTransaction = new FunctionCall("createRecord").addArgument("transaction"); if (columns.hasModifiedBy()) createRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id == 0")).addContent(new Assignment("id", createRecordCallWithTransaction)).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCallWithTransaction = new FunctionCall("updateRecord").addArgument("transaction").byItself(); if (columns.hasModifiedBy()) updateRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCallWithTransaction).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); updateDBFunctionWithTransaction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ).addContent( new ReturnStatement("-1") ); javaClass.addContent(updateDBFunctionWithTransaction).addContent(EMPTY_LINE); final FunctionDeclaration preUpdateConversionsFunction = new FunctionDeclaration("preUpdateConversions"); preUpdateConversionsFunction.addContent( ifNotDataOK().addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "BAD DATA") ) ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if ((type.equals("int") || type.equals("long")) && !field.startsWith("id")) preUpdateConversionsFunction.addContent( new Assignment(field, new FunctionCall("Strings.get" + capitalize(type) + "Val").addArgument(field + "Str")) ); if (JAVA_TEMPORAL_TYPES.contains(type)) preUpdateConversionsFunction.addContent( new IfBlock(new Condition(new FunctionCall("isEmpty", "Strings").addArgument(field + "Str"), true)).addContent( new Assignment(field, new FunctionCall("convertStringTo" + type).addArgument(field + "Str")) ).elseClause(new ElseBlock().addContent( new Assignment(field, "null") )) ); if (type.equals("Money")) preUpdateConversionsFunction.addContent( new Assignment(field, new ObjectCreation("Money") .addArgument(field + "Str") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))) ); } } javaClass.addContent(preUpdateConversionsFunction).addContent(EMPTY_LINE); } private void addDataOK() { final FunctionDeclaration dataOKFunction = new FunctionDeclaration("isDataOK", "boolean").addContent( new FunctionCall("clearErrorMessages", internalsVar).byItself() ).addContent( new VarDeclaration("boolean", "ok", "true") ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); final IfBlock checkRequired = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Required"))).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "EmptyErrorMessage")) ).addContent(new Assignment("ok", "false")); final IfBlock checkOKAndUnique = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "OK"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "BadFormatErrorMessage")) ).addContent(new Assignment("ok", "false")); if (column.isUnique()) checkOKAndUnique.elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Unique"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "NotUniqueErrorMessage")) ).addContent(new Assignment("ok", "false")) )); dataOKFunction.addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Empty"))).addContent(checkRequired) .elseClause(new ElseBlock().addContent(checkOKAndUnique)) ).addContent(EMPTY_LINE); } } dataOKFunction.addContent( new ReturnStatement("ok") ); javaClass.addContent(dataOKFunction).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final ReturnStatement returnStatement; if ((type.equals("int") || type.equals("long")) && field.startsWith("id")) returnStatement = new ReturnStatement(new Comparison(field, "0", Comparison.Comparator.EQUAL)); else { final String arg; if (type.equals("String")) arg = field; else arg = field + "Str"; returnStatement = new ReturnStatement(new FunctionCall("isEmpty", "Strings").addArgument(arg)); } javaClass.addContent( new FunctionDeclaration("is" + fieldCap + "Empty", "boolean").addContent(returnStatement) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "EmptyErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getRequiredErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final FunctionDeclaration isOKFunction = new FunctionDeclaration("is" + fieldCap + "OK", "boolean"); if ((type.equals("int") || type.equals("long"))) { if (field.startsWith("id")) isOKFunction.addContent(new ReturnStatement(new FunctionCall("isIdOK", column.getAssociatedBeanClass()).addArgument(field))); else { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isNumber", "FormatCheckHelper").addArgument(field + "Str"))); } } else if (JAVA_TEMPORAL_TYPES.contains(type)) { isOKFunction.addContent(new ReturnStatement(new FunctionCall("validate" + type + "Format").addArgument(field + "Str"))); } else if (type.equals("String")) { if (field.equalsIgnoreCase("email") || field.equalsIgnoreCase("e-mail")) { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isEmailValid", "FormatCheckHelper").addArgument(field))); } else isOKFunction.addContent(new ReturnStatement("true")); } else if (type.equals("Money")) { isOKFunction.addContent( new ReturnStatement(new FunctionCall("isValOK", parametersVar + ".getDefaultMoneyFormat()") .addArgument(field + "Str")) ); } else throw new IllegalStateException("Apparently unsupported type " + type + " encountered."); javaClass.addContent(isOKFunction).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "BadFormatErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getBadFormatErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { importsManager.addImport("org.dbbeans.sql.queries.BooleanCheckQuery"); final FunctionCall dbAccessFunctionCall = new FunctionCall("processQuery", "!dbAccess"); javaClass.addContent( new FunctionDeclaration("is" + capitalize(column.getJavaName() + "Unique"), "boolean").addContent( // TODO: IMPLEMENT!!! new ReturnStatement( dbAccessFunctionCall .addArgument(Strings.quickQuote(getNotUniqueQuery(column))) .addArgument(new AnonymousClassCreation("BooleanCheckQuery").setContext(dbAccessFunctionCall, 1).addContent( new FunctionDeclaration("setupPreparedStatement") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .annotate("@Override").addException("SQLException").addContent( new FunctionCall("set" + capitalize(column.getJavaType()), "stat") .addArgument("1").addArgument(column.getJavaName()).byItself() ).addContent( new FunctionCall("setLong", "stat") .addArguments("2", "id").byItself() ) )) ) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "NotUniqueErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getNotUniqueErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } javaClass.addContent( new FunctionDeclaration("getErrorMessages", "List<ErrorMessage>").addContent( new ReturnStatement(new FunctionCall("getErrorMessages", internalsVar)) ) ).addContent(EMPTY_LINE); } private String getNotUniqueQuery(final Column column) { return "SELECT id FROM " + tableName + " WHERE " + column.getSqlName() + "=? AND id <> ?"; } private void addReset() { final FunctionDeclaration resetFunction = new FunctionDeclaration("reset"); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (type.equals("boolean")) resetFunction.addContent(new Assignment(field, "false")); else if (type.equals("int") || type.equals("long")) resetFunction.addContent(new Assignment(field, "0")); else if (type.equals("String")) resetFunction.addContent(new Assignment(field, EMPTY_STRING)); else if (type.equals("Money")) resetFunction.addContent(new Assignment(field, new ObjectCreation("Money") .addArgument("0") .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar)))); else resetFunction.addContent(new Assignment(field, "null")); if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("int")) && !field.startsWith("id"))) resetFunction.addContent(new Assignment(field + "Str", EMPTY_STRING)); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) resetFunction.addContent(new FunctionCall("clear", relationship.getJavaName()).byItself()); resetFunction.addContent(new FunctionCall("clearErrorMessages", internalsVar).byItself()); javaClass.addContent(resetFunction).addContent(EMPTY_LINE); final FunctionDeclaration fullResetFunction = new FunctionDeclaration("fullReset").addContent( new FunctionCall("reset").byItself() ).addContent( new Assignment("id", "0") ); for (Column column: columns.getList()) { if (column.isLastUpdate()) fullResetFunction.addContent(new Assignment("lastUpdate", "0")); if (column.isModifiedBy()) fullResetFunction.addContent(new Assignment("modifiedBy", "null")); if (column.isItemOrder()) fullResetFunction.addContent(new Assignment("itemOrder", "0")); } javaClass.addContent(fullResetFunction).addContent(EMPTY_LINE); } private void addDelete() { final FunctionDeclaration deleteFunction = new FunctionDeclaration("delete"); final FunctionCall accessDB = new FunctionCall("addUpdate", "transaction").byItself(); deleteFunction.addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ); if (columns.hasItemOrder()) deleteFunction.addContent( new VarDeclaration("long", "curItemOrder").markAsFinal() ).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new Assignment("curItemOrder", "0") ).elseClause(new ElseBlock().addContent( new Assignment("curItemOrder", "itemOrder") )) ); deleteFunction.addContent( accessDB.addArgument(quickQuote(getDeleteSQLQuery())) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(accessDB).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").addArguments("1", "id").byItself() ) )) ); if (columns.hasItemOrder()) { final IfBlock checkItemOrderNotMax = new IfBlock(new Condition(new Comparison("curItemOrder", "0", Comparison.Comparator.GREATER_THAN))); final Column itemOrderField = columns.getItemOrderField(); if (itemOrderField.isUnique()) checkItemOrderNotMax.addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", null) ); else { final String itemOrderAssociatedField = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); checkItemOrderNotMax.addContent( new IfBlock(new Condition(new Comparison(itemOrderAssociatedField, "0"))).addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", null) ).elseClause(new ElseBlock().addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", itemOrderAssociatedField) ))); } deleteFunction.addContent(checkItemOrderNotMax); } deleteFunction.addContent( new FunctionCall("deleteExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( EMPTY_LINE ).addContent( new FunctionCall("postDeleteActions").byItself() ).addContent( new FunctionCall("fullReset").byItself() ); javaClass.addContent(deleteFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("deleteExtraDbActions").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postDeleteActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private FunctionCall getUpdateItemOrderAboveFunctionCall(final String queryRetrievalFunction, final String itemOrderAssociatedField) { final FunctionCall functionCall = new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall(queryRetrievalFunction, parametersVar)) .addArgument("transaction") .addArgument("curItemOrder"); if (itemOrderAssociatedField != null) functionCall.addArgument(itemOrderAssociatedField); return functionCall; } private FunctionCall getStatSetFunction(final String type, final String field, final int index) { return new FunctionCall("set" + capitalize(type), "stat").byItself().addArguments(Integer.toString(index), field); } private JavaCodeBlock getFieldCreationOrUpdate(final Column column, final int index) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (column.isRequired()) return getStatSetFunction(type, field, index); if (column.hasAssociatedBean()) return new IfBlock(new Condition(new Comparison(field, "0"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types.INTEGER") ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); if (JAVA_TEMPORAL_TYPES.contains(type)) return new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types." + type.toUpperCase()) ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); return getStatSetFunction(type, field, index); } private void addCreate() { int index = 0; final JavaClass recordCreationSetupClass = new JavaClass("RecordCreationSetup").implementsInterface("DBQuerySetup").visibility(Visibility.PRIVATE); final FunctionDeclaration setupStatFunction = new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!column.isId()) { if (type.equals("Money")) { final String suggestedType = Column.getSuggestedType(column.getSqlTypeName(), column.getPrecision()); if (suggestedType.equals("int")) setupStatFunction.addContent( new FunctionCall("setInt", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getIntVal", field)) ); else if (suggestedType.equals("long")) setupStatFunction.addContent( new FunctionCall("setLong", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getVal", field)) ); else throw new IllegalStateException("Money cannot be used with non INTEGER SQL field: " + column.getSqlName()); } else { setupStatFunction.addContent( getFieldCreationOrUpdate(column, ++index) ); } } } javaClass.addContent(recordCreationSetupClass.addContent(setupStatFunction)).addContent(EMPTY_LINE); javaClass.addContent( new JavaClass("RecordUpdateSetup").extendsClass("RecordCreationSetup").visibility(Visibility.PRIVATE).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setupPreparedStatement", "super").byItself().addArgument("stat") ).addContent( new FunctionCall("setLong", "stat").byItself().addArguments(Integer.toString(++index), "id") ) ) ).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunction = new FunctionDeclaration("createRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()).addContent( new FunctionCall("preCreateExtraDbActions").byItself().addArgument("transaction") ).addContent( new VarDeclaration("long", "id", new FunctionCall("createRecord").addArgument("transaction")).markAsFinal() ); addOneToManyRelationshipDBUpdateFunctionCalls(createRecordFunction); createRecordFunction.addContent( new FunctionCall("createExtraDbActions").byItself().addArguments("transaction", "id") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent(EMPTY_LINE).addContent( new Assignment("this.id", "id") ).addContent( new FunctionCall("postCreateActions").byItself() ); javaClass.addContent(createRecordFunction).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunctionWithTransaction = new FunctionDeclaration("createRecord", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE); if (columns.hasItemOrder()) { final Column itemOrderField = columns.getItemOrderField(); final IfBlock uninitializedItemOrderCase = new IfBlock(new Condition(new Comparison("itemOrder", "0"))); if (itemOrderField.isUnique()) uninitializedItemOrderCase.addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) ); else { uninitializedItemOrderCase.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, true), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) )) ); } createRecordFunctionWithTransaction.addContent(uninitializedItemOrderCase).addContent(EMPTY_LINE); } createRecordFunctionWithTransaction.addContent( new ReturnStatement(new FunctionCall("addRecordCreation", "transaction") .addArgument(quickQuote(getInsertSQLQuery())) .addArgument(new ObjectCreation("RecordCreationSetup"))) ); javaClass.addContent(createRecordFunctionWithTransaction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preCreateExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("createExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postCreateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipDBUpdateFunctionCalls(final FunctionDeclaration function) { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) function.addContent( new FunctionCall("update" + capitalize(relationship.getJavaName()) + "InDB").byItself().addArguments("transaction", "id") ); } } private void addUpdate() { final FunctionDeclaration updateRecordFunction = new FunctionDeclaration("updateRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new FunctionCall("preUpdateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("updateRecord").byItself().addArgument("transaction") ); addOneToManyRelationshipDBUpdateFunctionCalls(updateRecordFunction); updateRecordFunction.addContent( new FunctionCall("updateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( new FunctionCall("postUpdateActions").byItself() ); javaClass.addContent(updateRecordFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateRecord").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE).addContent( new FunctionCall("addUpdate", "transaction").byItself() .addArgument(quickQuote(getUpdateSQLQuery())) .addArgument(new ObjectCreation("RecordUpdateSetup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preUpdateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postUpdateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipInDB() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) { final FunctionDeclaration updateRelationshipFunction = new FunctionDeclaration("update" + capitalize(relationship.getJavaName()) + "InDB") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")) .visibility(Visibility.PRIVATE); final FunctionCall dbAccessFunction = new FunctionCall("addUpdate", "transaction").byItself(); updateRelationshipFunction.addContent( dbAccessFunction .addArgument(quickQuote(getDeleteOneToManyRelationshipQuery(relationship.getTable(), relationship.getIdSqlName()))) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(dbAccessFunction).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").byItself().addArguments("1", "id") ) )) ).addContent(EMPTY_LINE); final String var = uncapitalize(relationship.getBeanClass()); updateRelationshipFunction.addContent( new ForLoop(relationship.getBeanClass() + " " + var + ": " + relationship.getJavaName()).addContent( new FunctionCall("resetId", var).byItself() ).addContent( new FunctionCall("setId" + beanName, var).addArgument("id").byItself() ).addContent( new FunctionCall("updateDB", var).addArgument("transaction").byItself() ) ); javaClass.addContent(updateRelationshipFunction).addContent(EMPTY_LINE); } } } private void addTemporalFunctions() { if (types.contains("Date")) { javaClass.addContent( new FunctionDeclaration("formatDate", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Date", "date")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("date") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToDate", "Date").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getDateFromYYMD", "Dates").addArguments("str", quickQuote("-")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Date", "date")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateDateFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputDateFormat", "simpleInputDateFormat", new ObjectCreation("SimpleInputDateFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputDateFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Time")) { javaClass.addContent( new FunctionDeclaration("formatTime", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Time", "time")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getTimeInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("time") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTime", "Time").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimeFromString", "Dates").addArguments("str", quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Time", "time")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimeFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimeFormat", "simpleInputTimeFormat", new ObjectCreation("SimpleInputTimeFormat").addArgument(quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimeFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Timestamp")) { javaClass.addContent( new FunctionDeclaration("formatTimestamp", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Timestamp", "timestamp")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateTimeInstance", "DateFormat").addArguments("DateFormat.LONG", "DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("timestamp") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTimestamp", "Timestamp").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimestampFromYYMD", "Dates").addArguments("str", quickQuote("-"), quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Timestamp", "timestamp")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimestampFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimestampFormat", "simpleInputTimestampFormat", new ObjectCreation("SimpleInputTimestampFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-"), quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimestampFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } } private void addGetAll() { javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getAll").addArgument(new FunctionCall("getOrderByFields", parametersVar))) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "orderBy")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("null", "orderBy", "null")) ) ).addContent(EMPTY_LINE); final ObjectCreation newBeanFromFields = new ObjectCreation(beanName); int index = 0; for (Column column: columns.getList()) { ++index; final String javaType = column.getJavaType(); if (javaType.equals("Money")) newBeanFromFields .addArgument(new ObjectCreation("Money") .addArgument(new FunctionCall("getLong", "rs").addArgument(Integer.toString(index))) .addArgument(new FunctionCall("getDefaultMoneyFormat", parametersVar))); else newBeanFromFields .addArgument(new FunctionCall("get" + capitalize(javaType), "rs") .addArguments(Integer.toString(index))); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) newBeanFromFields.addArgument(new FunctionCall("getSelection", relationship.getBeanClass()) .addArgument(new OperatorExpression("\"id_" + uncamelize(beanVarName) + "=\"", new FunctionCall("getLong", "rs").addArgument("1"), OperatorExpression.Operator.ADD))); javaClass.addContent( new JavaClass("GetSelectionQueryProcess") .implementsInterface("DBQueryRetrieveData<List<" + beanName + ">>") .visibility(Visibility.PRIVATE) .markAsStatic() .addContent( new FunctionDeclaration("processResultSet", "List<" + beanName + ">") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent( VarDeclaration.createListDeclaration(beanName, "list") .markAsFinal() ).addContent(EMPTY_LINE).addContent( new WhileBlock(new Condition(new FunctionCall("next", "rs"))).addContent( new FunctionCall("add", "list") .byItself() .addArgument(newBeanFromFields) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("list") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("whereClause", "null")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new ReturnStatement(new FunctionCall("getSelection") .addArgument("whereClause") .addArguments(new FunctionCall("getOrderByFields", parametersVar)) .addArgument("setup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("String", "orderBy")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .andCondition(new Condition(new Comparison("setup", "null", Comparison.Comparator.NEQ)))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot accept setup code without a WHERE clause.")) ) ).addContent(EMPTY_LINE).addContent( new VarDeclaration("StringBuilder", "query", new ObjectCreation("StringBuilder")).markAsFinal() ).addContent( new FunctionCall("append", "query").addArgument(quickQuote(getAllFieldsQuery())).byItself() ).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" WHERE "))).addArgument("whereClause").byItself() ) ).addContent( new IfBlock(new Condition(new Comparison("orderBy", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" ORDER BY "))).addArgument("orderBy").byItself() ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .orCondition(new Condition(new Comparison("setup", "null")))).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument("setup") .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE); } private void addGetIdNamePairs() { javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").markAsStatic().addArguments( new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs").addArguments("null", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").visibility(Visibility.PROTECTED).markAsStatic().addArguments( new FunctionArgument("String", "whereClause"), new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs", "DBQueries").addArguments("db", quickQuote(tableName), "whereClause", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); } private void addGetCount() { javaClass.addContent( new FunctionDeclaration("getCount", "long").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getLongCount", "DBQueries").addArguments("db", quickQuote(tableName))) ) ).addContent(EMPTY_LINE); } private void addIdOK() { javaClass.addContent( new FunctionDeclaration("isIdOK", "boolean").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent( new ReturnStatement(new FunctionCall("isIdOK", "DBQueries").addArguments("db", quickQuote(tableName), "id")) ) ).addContent(EMPTY_LINE); } private void addHumanReadableTitle() { javaClass.addContent( new FunctionDeclaration("getHumanReadableTitle", "String") .markAsStatic() .addArgument(new FunctionArgument("long", "id")) .addContent( new IfBlock(new Condition("id == 0")).addContent( new ReturnStatement("\"\"") ) ) .addContent(EMPTY_LINE) .addContent( new ReturnStatement(new FunctionCall("getHumanReadableTitle", "DBQueries") .addArguments("db", quickQuote(tableName), "id") .addArgument(new FunctionCall("getNamingFields", parametersVar))) ) ).addContent(EMPTY_LINE); } private void addSetLocale() { javaClass.addContent( new FunctionDeclaration("setLocale").addArgument(new FunctionArgument("Locale", "locale")).addContent( new FunctionCall("setLocale", internalsVar).addArgument("locale").byItself() ) ).addContent(EMPTY_LINE); } private void createSourceCode() { sourceFile.setStartComment(SourceFiles.getCommentAndVersion()); addImports(); addClassModifiers(); addProperties(); addConstructors(); addSetIdFunction(); addEquals(); addToString(); addSetters(); addGetters(); addLabelGetters(); addRequiredIndicators(); addUniqueIndicators(); addOneToManyRelationshipManagement(); addItemOrderManagement(); addUpdateDB(); addDataOK(); addReset(); addDelete(); addCreate(); addUpdate(); addOneToManyRelationshipInDB(); addTemporalFunctions(); addGetAll(); addGetIdNamePairs(); addGetCount(); addIdOK(); addHumanReadableTitle(); addSetLocale(); } private String getReadSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); buf.append(" WHERE id=?"); return buf.toString(); } private String getAllFieldsQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); buf.append(name); buf.append(", "); } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); return buf.toString(); } private String getReadSQLQueryOneToManyRelationship(final String tableName, final String indexField) { return "SELECT id FROM " + tableName + " WHERE " + indexField + "=?"; } private String getDeleteSQLQuery() { return "DELETE FROM " + tableName + " WHERE id=?"; } private String getInsertSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("INSERT INTO "); buf.append(tableName); buf.append(" ("); int count = 0; for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { count++; buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(") VALUES ("); for (int i = 0; i < count; i++) buf.append("?, "); buf.delete(buf.length() - 2, buf.length()); buf.append(")"); return buf.toString(); } private String getUpdateSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("UPDATE "); buf.append(tableName); buf.append(" SET "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append("=?, "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" WHERE id=?"); if (columns.hasLastUpdate()) buf.append(" AND last_update=?"); return buf.toString(); } private String getDeleteOneToManyRelationshipQuery(final String tableName, final String indexField) { return "DELETE FROM " + tableName + " WHERE " + indexField + "=?"; } private FunctionDeclaration getTemporalConvertToStringFunction(final String className, final String varName) { return new FunctionDeclaration("convert" + className + "ToString", "String").addArgument(new FunctionArgument(className, varName)).addContent( new IfBlock(new Condition(new Comparison(varName, "null"))).addContent( new ReturnStatement(EMPTY_STRING) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("toString", varName)) ).visibility(Visibility.PROTECTED); } private void addIndicator(final String javaName, final String indicatorName, final boolean value, final boolean isFinal) { final FunctionDeclaration indicator = new FunctionDeclaration("is" + capitalize(javaName) + indicatorName, "boolean"); if (isFinal) indicator.markAsFinal(); if (value) indicator.addContent(new ReturnStatement("true")); else indicator.addContent(new ReturnStatement("false")); javaClass.addContent(indicator).addContent(EMPTY_LINE); } }
package org.biojava.bio.seq.io; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.biojava.bio.BioError; import org.biojava.bio.BioException; import org.biojava.bio.seq.DNATools; import org.biojava.bio.seq.NucleotideTools; import org.biojava.bio.seq.ProteinTools; import org.biojava.bio.seq.RNATools; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.SequenceIterator; import org.biojava.bio.seq.db.HashSequenceDB; import org.biojava.bio.seq.db.IDMaker; import org.biojava.bio.seq.db.SequenceDB; import org.biojava.bio.symbol.Alignment; import org.biojava.bio.symbol.Alphabet; import org.biojava.bio.symbol.FiniteAlphabet; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.utils.AssertionFailure; import org.biojava.utils.ChangeVetoException; /** * A set of convenience methods for handling common file formats. * * @author Thomas Down * @author Mark Schreiber * @author Nimesh Singh * @author Matthew Pocock * @author Keith James * @since 1.1 */ public final class SeqIOTools { private static SequenceBuilderFactory _emblBuilderFactory; private static SequenceBuilderFactory _genbankBuilderFactory; private static SequenceBuilderFactory _genpeptBuilderFactory; private static SequenceBuilderFactory _swissprotBuilderFactory; private static SequenceBuilderFactory _fastaBuilderFactory; /** * This can't be instantiated. */ private SeqIOTools() { } /** * Get a default SequenceBuilderFactory for handling EMBL * files. */ public static SequenceBuilderFactory getEmblBuilderFactory() { if (_emblBuilderFactory == null) { _emblBuilderFactory = new EmblProcessor.Factory(SmartSequenceBuilder.FACTORY); } return _emblBuilderFactory; } /** * Iterate over the sequences in an EMBL-format stream. */ public static SequenceIterator readEmbl(BufferedReader br) { return new StreamReader(br, new EmblLikeFormat(), getDNAParser(), getEmblBuilderFactory()); } /** * Iterate over the sequences in an EMBL-format stream, but for RNA. */ public static SequenceIterator readEmblRNA(BufferedReader br) { return new StreamReader(br, new EmblLikeFormat(), getRNAParser(), getEmblBuilderFactory()); } /** * Iterate over the sequences in an EMBL-format stream. */ public static SequenceIterator readEmblNucleotide(BufferedReader br) { return new StreamReader(br, new EmblLikeFormat(), getNucleotideParser(), getEmblBuilderFactory()); } /** * Get a default SequenceBuilderFactory for handling GenBank * files. */ public static SequenceBuilderFactory getGenbankBuilderFactory() { if (_genbankBuilderFactory == null) { _genbankBuilderFactory = new GenbankProcessor.Factory(SmartSequenceBuilder.FACTORY); } return _genbankBuilderFactory; } /** * Iterate over the sequences in an GenBank-format stream. */ public static SequenceIterator readGenbank(BufferedReader br) { return new StreamReader(br, new GenbankFormat(), getDNAParser(), getGenbankBuilderFactory()); } /** * Get a default SequenceBuilderFactory for handling Genpept * files. */ public static SequenceBuilderFactory getGenpeptBuilderFactory() { if (_genpeptBuilderFactory == null) { _genpeptBuilderFactory = new GenbankProcessor.Factory(SmartSequenceBuilder.FACTORY); } return _genpeptBuilderFactory; } /** * Iterate over the sequences in an Genpept-format stream. */ public static SequenceIterator readGenpept(BufferedReader br) { return new StreamReader(br, new GenbankFormat(), getProteinParser(), getGenpeptBuilderFactory()); } /** * Get a default SequenceBuilderFactory for handling Swissprot * files. */ public static SequenceBuilderFactory getSwissprotBuilderFactory() { if (_swissprotBuilderFactory == null) { _swissprotBuilderFactory = new SwissprotProcessor.Factory(SmartSequenceBuilder.FACTORY); } return _swissprotBuilderFactory; } /** * Iterate over the sequences in an Swissprot-format stream. */ public static SequenceIterator readSwissprot(BufferedReader br) { return new StreamReader(br, new EmblLikeFormat(), getProteinParser(), getSwissprotBuilderFactory()); } /** * Get a default SequenceBuilderFactory for handling FASTA * files. */ public static SequenceBuilderFactory getFastaBuilderFactory() { if (_fastaBuilderFactory == null) { _fastaBuilderFactory = new FastaDescriptionLineParser.Factory(SmartSequenceBuilder.FACTORY); } return _fastaBuilderFactory; } /** * Iterate over the sequences in an FASTA-format stream of DNA sequences. */ public static SequenceIterator readFastaDNA(BufferedReader br) { return new StreamReader(br, new FastaFormat(), getDNAParser(), getFastaBuilderFactory()); } /** * Iterate over the sequences in an FASTA-format stream of RNA sequences. */ public static SequenceIterator readFastaRNA(BufferedReader br) { return new StreamReader(br, new FastaFormat(), getRNAParser(), getFastaBuilderFactory()); } /** * Iterate over the sequences in an FASTA-format stream of Protein sequences. */ public static SequenceIterator readFastaProtein(BufferedReader br) { return new StreamReader(br, new FastaFormat(), getProteinParser(), getFastaBuilderFactory()); } /** * Create a sequence database from a fasta file provided as an * input stream. Note this somewhat duplicates functionality in * the readFastaDNA and readFastaProtein methods but uses a stream * rather than a reader and returns a SequenceDB rather than a * SequenceIterator. If the returned DB is likely to be large then * the above mentioned methods should be used. * * @throws BioException if problems occur during reading of the * stream. * @since 1.2 */ public static SequenceDB readFasta(InputStream seqFile, Alphabet alpha) throws BioException { HashSequenceDB db = new HashSequenceDB(IDMaker.byName); SequenceBuilderFactory sbFact = new FastaDescriptionLineParser.Factory(SmartSequenceBuilder.FACTORY); FastaFormat fFormat = new FastaFormat(); for (SequenceIterator seqI = new StreamReader(seqFile, fFormat, alpha.getTokenization("token"), sbFact);seqI.hasNext();) { Sequence seq = seqI.nextSequence(); try { db.addSequence(seq); } catch (ChangeVetoException cve) { throw new AssertionFailure( "Could not successfully add sequence " + seq.getName() + " to sequence database", cve); } } return db; } /** * Write a sequenceDB to an output stream in fasta format. * * @throws IOException if there was an error while writing. * @since 1.2 */ public static void writeFasta(OutputStream os, SequenceDB db) throws IOException { StreamWriter sw = new StreamWriter(os,new FastaFormat()); sw.writeStream(db.sequenceIterator()); } /** * Writes sequences from a SequenceIterator to an OutputStream in * Fasta Format. This makes for a useful format filter where a * StreamReader can be sent to the StreamWriter after formatting. * * @throws IOException if there was an error while writing. * @since 1.2 */ public static void writeFasta(OutputStream os, SequenceIterator in) throws IOException { StreamWriter sw = new StreamWriter(os,new FastaFormat()); sw.writeStream(in); } /** * Writes a single Sequence to an OutputStream in Fasta format. * * @param os the OutputStream. * @param seq the Sequence. * @throws IOException if there was an error while writing. */ public static void writeFasta(OutputStream os, Sequence seq) throws IOException { writeFasta(os, new SingleSeqIterator(seq)); } /** * Writes a stream of Sequences to an OutputStream in EMBL format. * * @param os the OutputStream. * @param in a SequenceIterator. * @exception IOException if there was an error while writing. */ public static void writeEmbl(OutputStream os, SequenceIterator in) throws IOException { StreamWriter sw = new StreamWriter(os, new EmblLikeFormat()); sw.writeStream(in); } /** * Writes a single Sequence to an OutputStream in EMBL format. * * @param os the OutputStream. * @param seq the Sequence. * @throws IOException if there was an error while writing. */ public static void writeEmbl(OutputStream os, Sequence seq) throws IOException { writeEmbl(os, new SingleSeqIterator(seq)); } /** * Writes a stream of Sequences to an OutputStream in SwissProt * format. * * @param os the OutputStream. * @param in a SequenceIterator. * @exception IOException if there was an error while writing. */ public static void writeSwissprot(OutputStream os, SequenceIterator in) throws IOException, BioException { SequenceFormat former = new EmblLikeFormat(); PrintStream ps = new PrintStream(os); while (in.hasNext()) { former.writeSequence(in.nextSequence(), ps); } } /** * Writes a single Sequence to an OutputStream in SwissProt format. * * @param os the OutputStream. * @param seq the Sequence. * @throws IOException if there was an error while writing. */ public static void writeSwissprot(OutputStream os, Sequence seq) throws IOException, BioException { writeSwissprot(os, new SingleSeqIterator(seq)); } /** * Writes a stream of Sequences to an OutputStream in Genpept * format. * * @param os the OutputStream. * @param in a SequenceIterator. * @exception IOException if there was an error while writing. */ public static void writeGenpept(OutputStream os, SequenceIterator in) throws IOException, BioException { SequenceFormat former = new GenpeptFormat(); PrintStream ps = new PrintStream(os); while (in.hasNext()) { former.writeSequence(in.nextSequence(), ps); } } /** * Writes a single Sequence to an OutputStream in Genpept format. * * @param os the OutputStream. * @param seq the Sequence. * @throws IOException if there was an error while writing. */ public static void writeGenpept(OutputStream os, Sequence seq) throws IOException, BioException { writeGenpept(os, new SingleSeqIterator(seq)); } /** * Writes a stream of Sequences to an OutputStream in Genbank * format. * * @param os the OutputStream. * @param in a SequenceIterator. * @exception IOException if there was an error while writing. */ public static void writeGenbank(OutputStream os, SequenceIterator in) throws IOException { StreamWriter sw = new StreamWriter(os, new GenbankFormat()); sw.writeStream(in); } /** * Writes a single Sequence to an OutputStream in Genbank format. * * @param os the OutputStream. * @param seq the Sequence. * @throws IOException if there was an error while writing. */ public static void writeGenbank(OutputStream os, Sequence seq) throws IOException { writeGenbank(os, new SingleSeqIterator(seq)); } public static int identifyFormat(String formatName, String alphabetName) { int format, alpha; if (formatName.equalsIgnoreCase("raw")) { format = SeqIOConstants.RAW; } else if (formatName.equalsIgnoreCase("fasta")) { format = SeqIOConstants.FASTA; } else if (formatName.equalsIgnoreCase("nbrf")) { format = SeqIOConstants.NBRF; } else if (formatName.equalsIgnoreCase("ig")) { format = SeqIOConstants.IG; } else if (formatName.equalsIgnoreCase("embl")) { format = SeqIOConstants.EMBL; } else if (formatName.equalsIgnoreCase("swissprot") || formatName.equalsIgnoreCase("swiss")) { if (alphabetName.equalsIgnoreCase("aa") || alphabetName.equalsIgnoreCase("protein")) { return SeqIOConstants.SWISSPROT; } else { throw new IllegalArgumentException("Illegal format and alphabet " + "combination " + formatName + " + " + alphabetName); } } else if (formatName.equalsIgnoreCase("genbank")) { format = SeqIOConstants.GENBANK; } else if (formatName.equalsIgnoreCase("genpept")) { if (alphabetName.equalsIgnoreCase("aa") || alphabetName.equalsIgnoreCase("protein")) { return SeqIOConstants.GENPEPT; } else { throw new IllegalArgumentException("Illegal format and alphabet " + "combination " + formatName + " + " + alphabetName); } } else if (formatName.equalsIgnoreCase("refseq")) { format = SeqIOConstants.REFSEQ; } else if (formatName.equalsIgnoreCase("gcg")) { format = SeqIOConstants.GCG; } else if (formatName.equalsIgnoreCase("gff")) { format = SeqIOConstants.GFF; } else if (formatName.equalsIgnoreCase("pdb")) { if (alphabetName.equalsIgnoreCase("aa") || alphabetName.equalsIgnoreCase("protein")) { return SeqIOConstants.PDB; } else { throw new IllegalArgumentException("Illegal format and alphabet " + "combination " + formatName + " + " + alphabetName); } } else if (formatName.equalsIgnoreCase("phred")) { if (alphabetName.equalsIgnoreCase("dna")) { return SeqIOConstants.PHRED; } else { throw new IllegalArgumentException("Illegal format and alphabet " + "combination " + formatName + " + " + alphabetName); } } else { return SeqIOConstants.UNKNOWN; } if (alphabetName.equalsIgnoreCase("dna")) { alpha = SeqIOConstants.DNA; } else if (alphabetName.equalsIgnoreCase("rna")) { alpha = SeqIOConstants.RNA; } else if (alphabetName.equalsIgnoreCase("aa") || alphabetName.equalsIgnoreCase("protein")) { alpha = SeqIOConstants.AA; } else { return SeqIOConstants.UNKNOWN; } return (format | alpha); } /** * <code>getSequenceFormat</code> accepts a value which represents * a sequence format and returns the relevant * <code>SequenceFormat</code> object. * * @param identifier an <code>int</code> which represents a binary * value with bits set according to the scheme described in * <code>SeqIOConstants</code>. * * @return a <code>SequenceFormat</code>. * * @exception BioException if an error occurs. */ public static SequenceFormat getSequenceFormat(int identifier) throws BioException { // Mask the sequence format bytes int alphaType = identifier & (~ 0xffff); if (alphaType == 0) throw new IllegalArgumentException("No alphabet was set in the identifier"); // Mask alphabet bytes int formatType = identifier & (~ 0xffff0000); if (formatType == 0) throw new IllegalArgumentException("No format was set in the identifier"); switch (identifier) { case SeqIOConstants.FASTA_DNA: case SeqIOConstants.FASTA_RNA: case SeqIOConstants.FASTA_AA: return new FastaFormat(); case SeqIOConstants.EMBL_DNA: case SeqIOConstants.EMBL_RNA: return new EmblLikeFormat(); case SeqIOConstants.GENBANK_DNA: case SeqIOConstants.GENBANK_RNA: return new GenbankFormat(); case SeqIOConstants.SWISSPROT: return new EmblLikeFormat(); default: throw new BioException("No SequenceFormat available for " + "format/alphabet identifier '" + identifier + "'"); } } /** * <code>getBuilderFactory</code> accepts a value which represents * a sequence format and returns the relevant * <code>SequenceBuilderFactory</code> object. * * @param identifier an <code>int</code> which represents a binary * value with bits set according to the scheme described in * <code>SeqIOConstants</code>. * * @return a <code>SequenceBuilderFactory</code>. * * @exception BioException if an error occurs. */ public static SequenceBuilderFactory getBuilderFactory(int identifier) throws BioException { // Mask the sequence format bytes int alphaType = identifier & (~ 0xffff); if (alphaType == 0) throw new IllegalArgumentException("No alphabet was set in the identifier"); // Mask alphabet bytes int formatType = identifier & (~ 0xffff0000); if (formatType == 0) throw new IllegalArgumentException("No format was set in the identifier"); switch (identifier) { case SeqIOConstants.FASTA_DNA: case SeqIOConstants.FASTA_RNA: case SeqIOConstants.FASTA_AA: return getFastaBuilderFactory(); case SeqIOConstants.EMBL_DNA: return getEmblBuilderFactory(); case SeqIOConstants.GENBANK_DNA: return getGenbankBuilderFactory(); case SeqIOConstants.SWISSPROT: return getSwissprotBuilderFactory(); case SeqIOConstants.GENPEPT: return getGenpeptBuilderFactory(); default: throw new BioException("No SequenceBuilderFactory available for " + "format/alphabet identifier '" + identifier + "'"); } } /** * <code>getAlphabet</code> accepts a value which represents a * sequence format and returns the relevant * <code>FiniteAlphabet</code> object. * * @param identifier an <code>int</code> which represents a binary * value with bits set according to the scheme described in * <code>SeqIOConstants</code>. * * @return a <code>FiniteAlphabet</code>. * * @exception BioException if an error occurs. */ public static FiniteAlphabet getAlphabet(int identifier) throws BioException { // Mask the sequence format bytes int alphaType = identifier & (~ 0xffff); if (alphaType == 0) throw new IllegalArgumentException("No alphabet was set in the identifier"); switch (alphaType) { case SeqIOConstants.DNA: return DNATools.getDNA(); case SeqIOConstants.RNA: return RNATools.getRNA(); case SeqIOConstants.AA: return ProteinTools.getAlphabet(); default: throw new BioException("No FiniteAlphabet available for " + "alphabet identifier '" + identifier + "'"); } } // The following methods provide an alternate interface for // reading and writing sequences and alignments. (Nimesh Singh). /** * Attempts to guess the filetype of a file given the name. For * use with the functions below that take an int fileType as a * parameter. EMBL and Genbank files are assumed to contain DNA * sequence. * * @deprecated because there is no standard file naming convention * and guessing by file name is inherantly error prone and bad. */ public static int guessFileType(File seqFile) throws IOException, FileNotFoundException { //First tries by matching an extension String fileName = seqFile.getName(); try { if (Pattern.matches(".*\\u002eem.*", fileName)) { return SeqIOConstants.EMBL_DNA; } else if (Pattern.matches(".*\\u002edat.*", fileName)) { return SeqIOConstants.EMBL_DNA; } else if (Pattern.matches(".*\\u002egb.*", fileName)) { return SeqIOConstants.GENBANK_DNA; } else if (Pattern.matches(".*\\u002esp.*", fileName)) { return SeqIOConstants.SWISSPROT; } else if (Pattern.matches(".*\\u002egp.*", fileName)) { return SeqIOConstants.GENPEPT; } else if (Pattern.matches(".*\\u002efa.*", fileName)) { return guessFastaType(seqFile); } else if (Pattern.matches(".*\\u002emsf.*", fileName)) { return guessMsfType(seqFile); } } catch (PatternSyntaxException e) { throw new BioError("Internal error in SeqIOTools", e); } //Reads the file to guess based on content BufferedReader br = new BufferedReader(new FileReader(seqFile)); String line1 = br.readLine(); String line2 = br.readLine(); br.close(); if (line1.startsWith(">")) { return guessFastaType(seqFile); } else if (line1.startsWith("PileUp")) { return guessMsfType(seqFile); } else if (line1.startsWith("!!AA_MULTIPLE_ALIGNMENT")) { return AlignIOConstants.MSF_AA; } else if (line1.startsWith("!!NA_MULTIPLE_ALIGNMENT")) { return AlignIOConstants.MSF_DNA; } else if (line1.startsWith("ID")) { for (int i = 0; i < line1.length(); i++) { if (Character.toUpperCase(line1.charAt(i)) == 'P' && Character.toUpperCase(line1.charAt(i+1)) == 'R' && Character.toUpperCase(line1.charAt(i+2)) == 'T') { return SeqIOConstants.SWISSPROT; } } return SeqIOConstants.EMBL_DNA; } else if (line1.toUpperCase().startsWith("LOCUS")) { for (int i = 0; i < line1.length(); i++) { if (Character.toUpperCase(line1.charAt(i)) == 'A' && Character.toUpperCase(line1.charAt(i+1)) == 'A') { return SeqIOConstants.GENPEPT; } } return SeqIOConstants.GENBANK_DNA; } else if (line1.length() >= 45 && line1.substring(19, 45).equalsIgnoreCase("GENETIC SEQUENCE DATA BANK")) { return guessGenType(fileName); } else { return SeqIOConstants.UNKNOWN; } } /** * Attempts to retrieve the most appropriate * <code>SequenceBuilder</code> object for some combination of * <code>Alphabet</code> and <code>SequenceFormat</code> * * @param format currently supports <code>FastaFormat</code>, * <code>GenbankFormat</code>, <code>EmblLikeFormat</code> * @param alpha currently only supports the DNA and Protein * alphabets * * @return the <code>SequenceBuilderFactory</code> * * @throws BioException if the combination of alpha and format is * unrecognized. * * @deprecated as this essentially duplicates the operation * available in the method <code>identifyBuilderFactory</code>. */ public static SequenceBuilderFactory formatToFactory(SequenceFormat format, Alphabet alpha) throws BioException { if ((format instanceof FastaFormat) && (alpha == DNATools.getDNA() || alpha == ProteinTools.getAlphabet())) { return getFastaBuilderFactory(); } else if (format instanceof GenbankFormat && alpha == DNATools.getDNA()) { return getGenbankBuilderFactory(); } else if (format instanceof GenbankFormat && alpha == ProteinTools.getAlphabet()) { return getGenpeptBuilderFactory(); } else if (format instanceof EmblLikeFormat && alpha == DNATools.getDNA()){ return getEmblBuilderFactory(); } else if (format instanceof EmblLikeFormat && alpha == ProteinTools.getAlphabet()) { return getSwissprotBuilderFactory(); } else { throw new BioException("Unknown combination of" + " Alphabet and Format"); } } /** * Reads a file with the specified format and alphabet * @param formatName the name of the format eg genbank or * swissprot (case insensitive) * @param alphabetName the name of the alphabet eg dna or rna or * protein (case insensitive) * @param br a BufferedReader for the input * @return either an Alignment object or a SequenceIterator * (depending on the format read) * @throws BioException if an error occurs while reading or a * unrecognized format, alphabet combination is used (eg swissprot * and DNA). * * @since 1.3 */ public static Object fileToBiojava(String formatName, String alphabetName, BufferedReader br) throws BioException { int fileType = identifyFormat(formatName, alphabetName); return fileToBiojava(fileType, br); } /** * Reads a file and returns the corresponding Biojava object. You * need to cast it as an Alignment or a SequenceIterator as * appropriate. */ public static Object fileToBiojava(int fileType, BufferedReader br) throws BioException { // Mask the sequence format bytes int alphaType = fileType & (~ 0xffff); if (alphaType == 0) throw new IllegalArgumentException("No alphabet was set in the identifier"); // Mask alphabet bytes int formatType = fileType & (~ 0xffff0000); if (formatType == 0) throw new IllegalArgumentException("No format was set in the identifier"); switch (fileType) { case AlignIOConstants.MSF_DNA: case AlignIOConstants.MSF_AA: case AlignIOConstants.FASTA_DNA: case AlignIOConstants.FASTA_AA: return fileToAlign(fileType, br); case SeqIOConstants.FASTA_DNA: case SeqIOConstants.FASTA_AA: case SeqIOConstants.EMBL_DNA: case SeqIOConstants.GENBANK_DNA: case SeqIOConstants.SWISSPROT: case SeqIOConstants.GENPEPT: return fileToSeq(fileType, br); default: throw new BioException("Unknown file type '" + fileType + "'"); } } public static void biojavaToFile(String formatName, String alphabetName, OutputStream os, Object biojava) throws BioException, IOException, IllegalSymbolException{ int fileType = identifyFormat(formatName,alphabetName); biojavaToFile(fileType, os, biojava); } /** * Converts a Biojava object to the given filetype. */ public static void biojavaToFile(int fileType, OutputStream os, Object biojava) throws BioException, IOException, IllegalSymbolException { switch (fileType) { case AlignIOConstants.MSF_DNA: case AlignIOConstants.MSF_AA: case AlignIOConstants.FASTA_DNA: case AlignIOConstants.FASTA_AA: alignToFile(fileType, os, (Alignment) biojava); break; case SeqIOConstants.FASTA_DNA: case SeqIOConstants.FASTA_AA: case SeqIOConstants.EMBL_DNA: case SeqIOConstants.GENBANK_DNA: case SeqIOConstants.SWISSPROT: case SeqIOConstants.GENPEPT: if(biojava instanceof SequenceDB){ seqToFile(fileType, os, ((SequenceDB)biojava).sequenceIterator()); }else if(biojava instanceof Sequence){ seqToFile(fileType, os, new SingleSeqIterator((Sequence)biojava)); }else{ seqToFile(fileType, os, (SequenceIterator) biojava); } break; default: throw new BioException("Unknown file type '" + fileType + "'"); } } /** * Helper function for guessFileName. */ private static int guessFastaType(File seqFile) throws IOException, FileNotFoundException { BufferedReader br = new BufferedReader(new FileReader(seqFile)); String line = br.readLine(); line = br.readLine(); br.close(); for (int i = 0; i < line.length(); i++) { if (Character.toUpperCase(line.charAt(i)) == 'F' || Character.toUpperCase(line.charAt(i)) == 'L' || Character.toUpperCase(line.charAt(i)) == 'I' || Character.toUpperCase(line.charAt(i)) == 'P' || Character.toUpperCase(line.charAt(i)) == 'Q' || Character.toUpperCase(line.charAt(i)) == 'E') { return SeqIOConstants.FASTA_AA; } } return SeqIOConstants.FASTA_DNA; } private static SymbolTokenization getDNAParser() { try { return DNATools.getDNA().getTokenization("token"); } catch (BioException ex) { throw new BioError("Assertion failing:" + " Couldn't get DNA token parser",ex); } } private static SymbolTokenization getRNAParser() { try { return RNATools.getRNA().getTokenization("token"); } catch (BioException ex) { throw new BioError("Assertion failing:" + " Couldn't get RNA token parser",ex); } } private static SymbolTokenization getNucleotideParser() { try { return NucleotideTools.getNucleotide().getTokenization("token"); } catch (BioException ex) { throw new BioError("Assertion failing:" + " Couldn't get nucleotide token parser",ex); } } private static SymbolTokenization getProteinParser() { try { return ProteinTools.getTAlphabet().getTokenization("token"); } catch (BioException ex) { throw new BioError("Assertion failing:" + " Couldn't get PROTEIN token parser",ex); } } /** * Helper function for guessFileName. */ private static int guessMsfType(File seqFile) throws IOException, FileNotFoundException { BufferedReader br = new BufferedReader(new FileReader(seqFile)); String line = br.readLine(); if (line.startsWith("!!NA_MULTIPLE_ALIGNMENT")) { return AlignIOConstants.MSF_DNA; } else if (line.startsWith("!!AA_MULTIPLE_ALIGNMENT")) { return AlignIOConstants.MSF_AA; } else { while (line.indexOf("Type: ") == -1) { line = br.readLine(); } br.close(); int typeIndex = line.indexOf("Type: ") + 6; if (line.substring(typeIndex).startsWith("N")) { return AlignIOConstants.MSF_DNA; } else if (line.substring(typeIndex).startsWith("P")) { return AlignIOConstants.MSF_AA; } else { return AlignIOConstants.UNKNOWN; } } } /** * Helper function for guessFileName. */ private static int guessGenType(String fileName) throws IOException, FileNotFoundException { BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); while (line.indexOf("LOCUS") == -1) { line = br.readLine(); } br.close(); for (int i = 0; i < line.length(); i++) { if (Character.toUpperCase(line.charAt(i)) == 'A' && Character.toUpperCase(line.charAt(i+1)) == 'A') { return SeqIOConstants.GENPEPT; } } return SeqIOConstants.GENBANK_DNA; } /** * Converts a file to an Biojava alignment. */ private static Alignment fileToAlign(int fileType, BufferedReader br) throws BioException { switch(fileType) { case AlignIOConstants.MSF_DNA: case AlignIOConstants.MSF_AA: return (new MSFAlignmentFormat()).read(br); case AlignIOConstants.FASTA_DNA: case AlignIOConstants.FASTA_AA: return (new FastaAlignmentFormat()).read(br); default: throw new BioException("Unknown file type '" + fileType + "'"); } } /** * Converts a file to a Biojava sequence. */ private static SequenceIterator fileToSeq(int fileType, BufferedReader br) throws BioException { switch (fileType) { case SeqIOConstants.FASTA_DNA: return SeqIOTools.readFastaDNA(br); case SeqIOConstants.FASTA_AA: return SeqIOTools.readFastaProtein(br); case SeqIOConstants.EMBL_DNA: return SeqIOTools.readEmbl(br); case SeqIOConstants.GENBANK_DNA: return SeqIOTools.readGenbank(br); case SeqIOConstants.SWISSPROT: return SeqIOTools.readSwissprot(br); case SeqIOConstants.GENPEPT: return SeqIOTools.readGenpept(br); default: throw new BioException("Unknown file type '" + fileType + "'"); } } /** * Converts a Biojava alignment to the given filetype. */ private static void alignToFile(int fileType, OutputStream os, Alignment align) throws BioException, IllegalSymbolException { switch(fileType) { case AlignIOConstants.MSF_DNA: (new MSFAlignmentFormat()).writeDna(os, align); break; case AlignIOConstants.MSF_AA: (new MSFAlignmentFormat()).writeProtein(os, align); break; case AlignIOConstants.FASTA_DNA: (new FastaAlignmentFormat()).writeDna(os, align); break; case AlignIOConstants.FASTA_AA: (new FastaAlignmentFormat()).writeProtein(os, align); break; default: throw new BioException("Unknown file type '" + fileType + "'"); } } /** * Converts a Biojava sequence to the given filetype. */ private static void seqToFile(int fileType, OutputStream os, SequenceIterator seq) throws IOException, BioException { switch (fileType) { case SeqIOConstants.FASTA_DNA: case SeqIOConstants.FASTA_AA: SeqIOTools.writeFasta(os, seq); break; case SeqIOConstants.EMBL_DNA: SeqIOTools.writeEmbl(os, seq); break; case SeqIOConstants.SWISSPROT: SeqIOTools.writeSwissprot(os, seq); break; case SeqIOConstants.GENBANK_DNA: SeqIOTools.writeGenbank(os, seq); break; case SeqIOConstants.GENPEPT: SeqIOTools.writeGenpept(os, seq); break; default: throw new BioException("Unknown file type '" + fileType + "'"); } } private static final class SingleSeqIterator implements SequenceIterator { private Sequence seq; SingleSeqIterator(Sequence seq) { this.seq = seq; } public boolean hasNext() { return seq != null; } public Sequence nextSequence() { Sequence seq = this.seq; this.seq = null; return seq; } } }
package org.chromium.sdk; /** * Exposes additional data if variable is a property of object and its property descriptor * is available. */ public interface JsObjectProperty extends JsVariable { /** * @return whether property described as 'writable' */ boolean isWritable(); /** * @return property getter value (function or undefined) or null if not an accessor property */ JsValue getGetter(); /** * @return {@link #getGetter()} result as function or null if cannot cast */ JsFunction getGetterAsFunction(); /** * @return property setter value (function or undefined) or null if not an accessor property */ JsValue getSetter(); /** * @return whether property described as 'configurable' */ boolean isConfigurable(); /** * @return whether property described as 'enumerable' */ boolean isEnumerable(); /** * Asynchronously evaluates property getter and returns property value. Must only be used * if {@link #getGetterAsFunction()} returns not null; otherwise behavior is undefined and * implementation-specific. */ RelayOk evaluateGet(JsEvaluateContext.EvaluateCallback callback, SyncCallback syncCallback); }
package org.cloudbus.cloudsim; import org.cloudbus.cloudsim.core.CloudSim; /** * CloudSim ResCloudlet represents a Cloudlet submitted to CloudResource for processing. This class * keeps track the time for all activities in the CloudResource for a specific Cloudlet. Before a * Cloudlet exits the CloudResource, it is RECOMMENDED to call this method * {@link #finalizeCloudlet()}. * <p> * It contains a Cloudlet object along with its arrival time and the ID of the machine and the Pe * (Processing Element) allocated to it. It acts as a placeholder for maintaining the amount of * resource share allocated at various times for simulating any scheduling using internal events. * * @author Manzur Murshed * @author Rajkumar Buyya * @since CloudSim Toolkit 1.0 */ public class ResCloudlet { /** The Cloudlet object. */ private final Cloudlet cloudlet; /** The Cloudlet arrival time for the first time. */ private double arrivalTime; /** The estimation of Cloudlet finished time. */ private double finishedTime; /** The length of Cloudlet finished so far. */ private long cloudletFinishedSoFar; /** * Cloudlet execution start time. This attribute will only hold the latest time since a Cloudlet * can be cancel, paused or resumed. */ private double startExecTime; /** The total time to complete this Cloudlet. */ private double totalCompletionTime; // The below attributes are only be used by the SpaceShared policy. /** The machine id this Cloudlet is assigned to. */ private int machineId; /** The Pe id this Cloudlet is assigned to. */ private int peId; /** The an array of machine IDs. */ private int[] machineArrayId = null; /** The an array of Pe IDs. */ private int[] peArrayId = null; /** The index of machine and Pe arrays. */ private int index; // NOTE: Below attributes are related to AR stuff /** The Constant NOT_FOUND. */ private static final int NOT_FOUND = -1; /** The reservation start time. */ private final long startTime; /** The reservation duration time. */ private final int duration; /** The reservation id. */ private final int reservId; /** The num Pe needed to execute this Cloudlet. */ private int pesNumber; /** * Allocates a new ResCloudlet object upon the arrival of a Cloudlet object. The arriving time * is determined by {@link gridsim.CloudSim#clock()}. * * @param cloudlet a cloudlet object * @see gridsim.CloudSim#clock() * @pre cloudlet != null * @post $none */ public ResCloudlet(Cloudlet cloudlet) { // when a new ResCloudlet is created, then it will automatically set // the submission time and other properties, such as remaining length this.cloudlet = cloudlet; startTime = 0; reservId = NOT_FOUND; duration = 0; init(); } /** * Allocates a new ResCloudlet object upon the arrival of a Cloudlet object. Use this * constructor to store reserved Cloudlets, i.e. Cloudlets that done reservation before. The * arriving time is determined by {@link gridsim.CloudSim#clock()}. * * @param cloudlet a cloudlet object * @param startTime a reservation start time. Can also be interpreted as starting time to * execute this Cloudlet. * @param duration a reservation duration time. Can also be interpreted as how long to execute * this Cloudlet. * @param reservID a reservation ID that owns this Cloudlet * @see gridsim.CloudSim#clock() * @pre cloudlet != null * @pre startTime > 0 * @pre duration > 0 * @pre reservID > 0 * @post $none */ public ResCloudlet(Cloudlet cloudlet, long startTime, int duration, int reservID) { this.cloudlet = cloudlet; this.startTime = startTime; reservId = reservID; this.duration = duration; init(); } /** * Gets the Cloudlet or reservation start time. * * @return Cloudlet's starting time * @pre $none * @post $none */ public long getStartTime() { return startTime; } /** * Gets the reservation duration time. * * @return reservation duration time * @pre $none * @post $none */ public int getDurationTime() { return duration; } /** * Gets the number of PEs required to execute this Cloudlet. * * @return number of Pe * @pre $none * @post $none */ public int getNumberOfPes() { return pesNumber; } /** * Gets the reservation ID that owns this Cloudlet. * * @return a reservation ID * @pre $none * @post $none */ public int getReservationID() { return reservId; } /** * Checks whether this Cloudlet is submitted by reserving or not. * * @return <tt>true</tt> if this Cloudlet has reserved before, <tt>false</tt> otherwise * @pre $none * @post $none */ public boolean hasReserved() { if (reservId == NOT_FOUND) { return false; } return true; } /** * Initialises all local attributes. * * @pre $none * @post $none */ private void init() { // get number of PEs required to run this Cloudlet pesNumber = cloudlet.getNumberOfPes(); // if more than 1 Pe, then create an array if (pesNumber > 1) { machineArrayId = new int[pesNumber]; peArrayId = new int[pesNumber]; } arrivalTime = CloudSim.clock(); cloudlet.setSubmissionTime(arrivalTime); // default values finishedTime = NOT_FOUND; // Cannot finish in this hourly slot. machineId = NOT_FOUND; peId = NOT_FOUND; index = 0; totalCompletionTime = 0.0; startExecTime = 0.0; // In case a Cloudlet has been executed partially by some other grid // hostList. cloudletFinishedSoFar = cloudlet.getCloudletFinishedSoFar() * Consts.MILLION; } /** * Gets this Cloudlet entity Id. * * @return the Cloudlet entity Id * @pre $none * @post $none */ public int getCloudletId() { return cloudlet.getCloudletId(); } /** * Gets the user or owner of this Cloudlet. * * @return the Cloudlet's user Id * @pre $none * @post $none */ public int getUserId() { return cloudlet.getUserId(); } /** * Gets the Cloudlet's length. * * @return Cloudlet's length * @pre $none * @post $none */ public long getCloudletLength() { return cloudlet.getCloudletLength(); } /** * Gets the total Cloudlet's length (across all PEs). * * @return total Cloudlet's length * @pre $none * @post $none */ public long getCloudletTotalLength() { return cloudlet.getCloudletTotalLength(); } /** * Gets the Cloudlet's class type. * * @return class type of the Cloudlet * @pre $none * @post $none */ public int getCloudletClassType() { return cloudlet.getClassType(); } /** * Sets the Cloudlet status. * * @param status the Cloudlet status * @return <tt>true</tt> if the new status has been set, <tt>false</tt> otherwise * @pre status >= 0 * @post $none */ public boolean setCloudletStatus(int status) { // gets Cloudlet's previous status int prevStatus = cloudlet.getCloudletStatus(); // if the status of a Cloudlet is the same as last time, then ignore if (prevStatus == status) { return false; } boolean success = true; try { double clock = CloudSim.clock(); // gets the current clock // sets Cloudlet's current status cloudlet.setCloudletStatus(status); // if a previous Cloudlet status is INEXEC if (prevStatus == Cloudlet.INEXEC) { // and current status is either CANCELED, PAUSED or SUCCESS if (status == Cloudlet.CANCELED || status == Cloudlet.PAUSED || status == Cloudlet.SUCCESS) { // then update the Cloudlet completion time totalCompletionTime += (clock - startExecTime); index = 0; return true; } } if (prevStatus == Cloudlet.RESUMED && status == Cloudlet.SUCCESS) { // then update the Cloudlet completion time totalCompletionTime += (clock - startExecTime); return true; } // if a Cloudlet is now in execution //ATAKAN: Do not reset startTime when resumes //if (status == Cloudlet.INEXEC || (prevStatus == Cloudlet.PAUSED && status == Cloudlet.RESUMED)) { if (status == Cloudlet.INEXEC && prevStatus == Cloudlet.CREATED) { startExecTime = clock; cloudlet.setExecStartTime(startExecTime); } } catch (Exception e) { success = false; } return success; } /** * Gets the Cloudlet's execution start time. * * @return Cloudlet's execution start time * @pre $none * @post $none */ public double getExecStartTime() { return cloudlet.getExecStartTime(); } /** * Sets this Cloudlet's execution parameters. These parameters are set by the CloudResource * before departure or sending back to the original Cloudlet's owner. * * @param wallClockTime the time of this Cloudlet resides in a CloudResource (from arrival time * until departure time). * @param actualCPUTime the total execution time of this Cloudlet in a CloudResource. * @pre wallClockTime >= 0.0 * @pre actualCPUTime >= 0.0 * @post $none */ public void setExecParam(double wallClockTime, double actualCPUTime) { cloudlet.setExecParam(wallClockTime, actualCPUTime); } /** * Sets the machine and Pe (Processing Element) ID. * * @param machineId machine ID * @param peId Pe ID * @pre machineID >= 0 * @pre peID >= 0 * @post $none */ public void setMachineAndPeId(int machineId, int peId) { // if this job only requires 1 Pe this.machineId = machineId; this.peId = peId; // if this job requires many PEs if (peArrayId != null && pesNumber > 1) { machineArrayId[index] = machineId; peArrayId[index] = peId; index++; } } /** * Gets machine ID. * * @return machine ID or <tt>-1</tt> if it is not specified before * @pre $none * @post $result >= -1 */ public int getMachineId() { return machineId; } /** * Gets Pe ID. * * @return Pe ID or <tt>-1</tt> if it is not specified before * @pre $none * @post $result >= -1 */ public int getPeId() { return peId; } /** * Gets a list of Pe IDs. <br> * NOTE: To get the machine IDs corresponding to these Pe IDs, use {@link #getMachineIdList()}. * * @return an array containing Pe IDs. * @pre $none * @post $none */ public int[] getPeIdList() { return peArrayId; } /** * Gets a list of Machine IDs. <br> * NOTE: To get the Pe IDs corresponding to these machine IDs, use {@link #getPeIdList()}. * * @return an array containing Machine IDs. * @pre $none * @post $none */ public int[] getMachineIdList() { return machineArrayId; } /** * Gets the remaining cloudlet length. * * @return cloudlet length * @pre $none * @post $result >= 0 */ public long getRemainingCloudletLength() { long length = cloudlet.getCloudletTotalLength() * Consts.MILLION - cloudletFinishedSoFar; // Remaining Cloudlet length can't be negative number. if (length < 0) { return 0; } return (long) Math.floor(length / Consts.MILLION); } /** * Finalizes all relevant information before <tt>exiting</tt> the CloudResource entity. This * method sets the final data of: * <ul> * <li>wall clock time, i.e. the time of this Cloudlet resides in a CloudResource (from arrival * time until departure time). * <li>actual CPU time, i.e. the total execution time of this Cloudlet in a CloudResource. * <li>Cloudlet's finished so far * </ul> * * @pre $none * @post $none */ public void finalizeCloudlet() { // Sets the wall clock time and actual CPU time double wallClockTime = CloudSim.clock() - arrivalTime; cloudlet.setExecParam(wallClockTime, totalCompletionTime); long finished = 0; //if (cloudlet.getCloudletTotalLength() * Consts.MILLION < cloudletFinishedSoFar) { if (cloudlet.getCloudletStatus()==Cloudlet.SUCCESS) { finished = cloudlet.getCloudletLength(); } else { finished = cloudletFinishedSoFar / Consts.MILLION; } cloudlet.setCloudletFinishedSoFar(finished); } /** * A method that updates the length of cloudlet that has been completed. * * @param miLength cloudlet length in Instructions (I) * @pre miLength >= 0.0 * @post $none */ public void updateCloudletFinishedSoFar(long miLength) { cloudletFinishedSoFar += miLength; } /** * Gets arrival time of a cloudlet. * * @return arrival time * @pre $none * @post $result >= 0.0 */ public double getCloudletArrivalTime() { return arrivalTime; } /** * Sets the finish time for this Cloudlet. If time is negative, then it is being ignored. * * @param time finish time * @pre time >= 0.0 * @post $none */ public void setFinishTime(double time) { if (time < 0.0) { return; } finishedTime = time; } /** * Gets the Cloudlet's finish time. * * @return finish time of a cloudlet or <tt>-1.0</tt> if it cannot finish in this hourly slot * @pre $none * @post $result >= -1.0 */ public double getClouddletFinishTime() { return finishedTime; } /** * Gets this Cloudlet object. * * @return cloudlet object * @pre $none * @post $result != null */ public Cloudlet getCloudlet() { return cloudlet; } /** * Gets the Cloudlet status. * * @return Cloudlet status * @pre $none * @post $none */ public int getCloudletStatus() { return cloudlet.getCloudletStatus(); } /** * Get unique string identificator of the VM. * * @return string uid */ public String getUid() { return getUserId() + "-" + getCloudletId(); } }
package org.exist.xmldb; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.exist.Namespaces; import org.exist.dom.DocumentTypeImpl; import org.exist.util.MimeType; import org.exist.util.serializer.DOMSerializer; import org.exist.util.serializer.SAXSerializer; import org.exist.xquery.value.StringValue; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xmldb.api.base.ErrorCodes; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.TransformerException; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class RemoteXMLResource extends AbstractRemoteResource implements XMLResource { private final static Properties emptyProperties = new Properties(); /** * Use external XMLReader to parse XML. */ private XMLReader xmlReader = null; protected String id; protected int handle = -1; protected int pos = -1; private String content = null; protected Properties outputProperties = null; protected LexicalHandler lexicalHandler = null; private static Logger LOG = Logger.getLogger(RemoteXMLResource.class.getName()); public RemoteXMLResource(RemoteCollection parent, XmldbURI docId, String id) throws XMLDBException { this(parent, -1, -1, docId, id); } public RemoteXMLResource( RemoteCollection parent, int handle, int pos, XmldbURI docId, String id) throws XMLDBException { super(parent,docId); this.handle = handle; this.pos = pos; this.id = id; this.mimeType=MimeType.XML_TYPE.getName(); } public Object getContent() throws XMLDBException { if (content != null) { return new StringValue(content).getStringValue(true); } Object res=super.getContent(); if(res!=null) { if(res instanceof byte[]) { try { return new String((byte[])res,"UTF-8"); } catch(UnsupportedEncodingException uee) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, uee.getMessage(), uee); } } else { return res; } } return null; // Backward compatible code (perhaps it is not needed?) /* if (properties.getProperty(EXistOutputKeys.COMPRESS_OUTPUT, "no").equals("yes")) { try { data = Compressor.uncompress(data); } catch (IOException e) { } } try { content = new String(data, properties.getProperty(OutputKeys.ENCODING, "UTF-8")); // fixme! - this should probably be earlier in the chain before serialisation. /ljo content = new StringValue(content).getStringValue(true); } catch (UnsupportedEncodingException ue) { LOG.warn(ue); content = new String(data); content = new StringValue(content).getStringValue(true); } return content; */ } public Node getContentAsDOM() throws XMLDBException { InputSource is=null; if(content!=null) { is=new InputSource(new StringReader(content)); } else { is=new InputSource(getStreamContent()); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); // <frederic.glorieux@ajlsm.com> return a full DOM doc, with root PI and comments return doc; } catch (SAXException saxe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, saxe.getMessage(), saxe); } catch (ParserConfigurationException pce) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, pce.getMessage(), pce); } catch(IOException ioe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe); } } public void getContentAsSAX(ContentHandler handler) throws XMLDBException { InputSource is=null; if(content!=null) { is=new InputSource(new StringReader(content)); } else { is=new InputSource(getStreamContent()); } XMLReader reader = null; if (xmlReader == null) { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setNamespaceAware(true); saxFactory.setValidating(false); try { SAXParser sax = saxFactory.newSAXParser(); reader = sax.getXMLReader(); } catch (ParserConfigurationException pce) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, pce.getMessage(), pce); } catch (SAXException saxe) { saxe.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, saxe.getMessage(), saxe); } } else { reader = xmlReader; } try { reader.setContentHandler(handler); if(lexicalHandler != null) { reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, lexicalHandler); } reader.parse(is); } catch (SAXException saxe) { saxe.printStackTrace(); throw new XMLDBException(ErrorCodes.VENDOR_ERROR, saxe.getMessage(), saxe); } catch (IOException ioe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe); } } public String getNodeId() { return id == null ? "1" : id; } public String getDocumentId() throws XMLDBException { return path.lastSegment().toString(); } public String getId() throws XMLDBException { if (id == null || id.equals("1")) return getDocumentId(); return getDocumentId() + '_' + id; } public String getResourceType() throws XMLDBException { return "XMLResource"; } /** * Sets the external XMLReader to use. * * @param xmlReader the XMLReader */ public void setXMLReader(XMLReader xmlReader) { this.xmlReader = xmlReader; } public void setContent(Object value) throws XMLDBException { content = null; if(!super.setContentInternal(value)) { if(value instanceof String) { content = new String((String)value); } else if(value instanceof byte[]) { try { content = new String((byte[])value,"UTF-8"); } catch(UnsupportedEncodingException uee) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, uee.getMessage(), uee); } } else { content = value.toString(); } } } public void setContentAsDOM(Node root) throws XMLDBException { try { File tmpfile=File.createTempFile("eXistRXR", ".xml"); tmpfile.deleteOnExit(); FileOutputStream fos=new FileOutputStream(tmpfile); BufferedOutputStream bos=new BufferedOutputStream(fos); OutputStreamWriter osw=new OutputStreamWriter(bos,"UTF-8"); DOMSerializer xmlout = new DOMSerializer(osw, getProperties()); try { switch (root.getNodeType()) { case Node.ELEMENT_NODE : xmlout.serialize((Element) root); break; case Node.DOCUMENT_FRAGMENT_NODE : xmlout.serialize((DocumentFragment) root); break; case Node.DOCUMENT_NODE : xmlout.serialize((Document) root); break; default : throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "invalid node type"); } setContent(tmpfile); } catch (TransformerException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage(), e); } finally { try { osw.close(); } catch(IOException ioe) { // IgnoreIT(R) } try { bos.close(); } catch(IOException ioe) { // IgnoreIT(R) } try { fos.close(); } catch(IOException ioe) { // IgnoreIT(R) } } } catch(IOException ioe) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe); } } public ContentHandler setContentAsSAX() throws XMLDBException { freeLocalResources(); content = null; return new InternalXMLSerializer(); } private class InternalXMLSerializer extends SAXSerializer { File tmpfile=null; OutputStreamWriter writer = null; public InternalXMLSerializer() { super(); } public void startDocument() throws SAXException { try { File tmpfile=File.createTempFile("eXistRXR", ".xml"); tmpfile.deleteOnExit(); FileOutputStream fos=new FileOutputStream(tmpfile); BufferedOutputStream bos=new BufferedOutputStream(fos); writer=new OutputStreamWriter(bos,"UTF-8"); setOutput(writer, emptyProperties); } catch(IOException ioe) { throw new SAXException("Unable to create temp file for serialization data",ioe); } super.startDocument(); } /** * @see org.xml.sax.DocumentHandler#endDocument() */ public void endDocument() throws SAXException { super.endDocument(); try { setContent(tmpfile); } catch(XMLDBException xe) { throw new SAXException("Unable to close temp file containing serialized data",xe); } try { if (writer != null) writer.close(); } catch (IOException e) { throw new SAXException("Unable to close temp file containing serialized data",e); } } } /* (non-Javadoc) * @see org.xmldb.api.modules.XMLResource#getSAXFeature(java.lang.String) */ public boolean getSAXFeature(String arg0) throws SAXNotRecognizedException, SAXNotSupportedException { return false; } /* (non-Javadoc) * @see org.xmldb.api.modules.XMLResource#setSAXFeature(java.lang.String, boolean) */ public void setSAXFeature(String arg0, boolean arg1) throws SAXNotRecognizedException, SAXNotSupportedException { } public void setLexicalHandler(LexicalHandler handler) { lexicalHandler = handler; } protected void setProperties(Properties properties) { this.outputProperties = properties; } protected Properties getProperties() { return outputProperties == null ? parent.properties : outputProperties; } public DocumentType getDocType() throws XMLDBException { DocumentType result = null; List params = new ArrayList(1); Object[] request = null; params.add(path.toString()); try { request = (Object[]) parent.getClient().execute("getDocType", params); if (!request[0].equals("")) { result = new DocumentTypeImpl((String)request[0],(String)request[1],(String)request[2]); } return result; } catch (XmlRpcException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } } public void setDocType(DocumentType doctype) throws XMLDBException { if (doctype != null ) { List params = new ArrayList(4); params.add(path.toString()); params.add(doctype.getName()); params.add(doctype.getPublicId() == null ? "" : doctype.getPublicId()); params.add(doctype.getSystemId() == null ? "" : doctype.getSystemId()); try { parent.getClient().execute("setDocType", params); } catch (XmlRpcException e) { throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e.getMessage(), e); } } } public void getContentIntoAStream(OutputStream os) throws XMLDBException { getContentIntoAStreamInternal(os,content,id!=null,handle,pos); } public Object getExtendedContent() throws XMLDBException { return getExtendedContentInternal(content,id!=null,handle,pos); } public InputStream getStreamContent() throws XMLDBException { return getStreamContentInternal(content,id!=null,handle,pos); } public long getStreamLength() throws XMLDBException { return getStreamLengthInternal(content); } }
package org.helioviewer.jhv.opengl; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.helioviewer.jhv.base.BufferUtils; import org.helioviewer.jhv.base.logging.Log; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.GL2; public class GLLine { private int[] vboAttribRefs; private int[] vboAttribLens = { 3, 3, 3, 1, 4 }; private VBO[] vbos = new VBO[5]; private VBO ivbo; private boolean hasPoints = false; public void setData(GL2 gl, FloatBuffer points, FloatBuffer colors) { hasPoints = false; int plen = points.limit() / 3; if (plen != colors.limit() / 4 || plen < 2) { Log.error("Something is wrong with the vertices or colors from this line."); return; } setBufferData(gl, points, colors, plen); hasPoints = true; } public void render(GL2 gl, double aspect, double thickness) { if (!hasPoints) return; GLSLLineShader.line.bind(gl); GLSLLineShader.line.setAspect(aspect); GLSLLineShader.line.setThickness(thickness); GLSLLineShader.line.bindParams(gl); bindVBOs(gl); gl.glDrawElements(GL2.GL_TRIANGLES, ivbo.bufferSize, GL2.GL_UNSIGNED_INT, 0); unbindVBOs(gl); GLSLShader.unbind(gl); } private void bindVBOs(GL2 gl) { for (VBO vbo : vbos) { vbo.bindArray(gl); } ivbo.bindArray(gl); } private void unbindVBOs(GL2 gl) { for (VBO vbo : vbos) { vbo.unbindArray(gl); } ivbo.unbindArray(gl); } private void initVBOs(GL2 gl) { for (int i = 0; i < vboAttribRefs.length; i++) { vbos[i] = VBO.gen_float_VBO(vboAttribRefs[i], vboAttribLens[i]); vbos[i].init(gl); } ivbo = VBO.gen_index_VBO(); ivbo.init(gl); } private void disposeVBOs(GL2 gl) { for (int i = 0; i < vbos.length; i++) { if (vbos[i] != null) { vbos[i].dispose(gl); vbos[i] = null; } } if (ivbo != null) { ivbo.dispose(gl); ivbo = null; } } private IntBuffer gen_indices(int plen) { IntBuffer indicesBuffer = BufferUtils.newIntBuffer(6 * plen); for (int j = 0; j < 2 * plen - 3; j = j + 2) { indicesBuffer.put(j + 0); indicesBuffer.put(j + 1); indicesBuffer.put(j + 2); indicesBuffer.put(j + 2); indicesBuffer.put(j + 1); indicesBuffer.put(j + 3); } indicesBuffer.flip(); return indicesBuffer; } private void addPoint(FloatBuffer to, FloatBuffer from, int start, int n) { for (int i = start; i < start + n; i++) { to.put(from.get(i)); } for (int i = start; i < start + n; i++) { to.put(from.get(i)); } } public void init(GL2 gl) { vboAttribRefs = new int[] { GLSLLineShader.previousLineRef, GLSLLineShader.lineRef, GLSLLineShader.nextLineRef, GLSLLineShader.directionRef, GLSLLineShader.linecolorRef }; initVBOs(gl); } private void setBufferData(GL2 gl, FloatBuffer points, FloatBuffer colors, int plen) { FloatBuffer previousLineBuffer = BufferUtils.newFloatBuffer(3 * 2 * plen); FloatBuffer lineBuffer = BufferUtils.newFloatBuffer(3 * 2 * plen); FloatBuffer nextLineBuffer = BufferUtils.newFloatBuffer(3 * 2 * plen); FloatBuffer directionBuffer = BufferUtils.newFloatBuffer(2 * 2 * plen); FloatBuffer colorBuffer = BufferUtils.newFloatBuffer(4 * 2 * plen); int dir = -1; for (int i = 0; i < 2 * plen; i++) { directionBuffer.put(dir); directionBuffer.put(-dir); } addPoint(previousLineBuffer, points, 0, 3); addPoint(lineBuffer, points, 0, 3); addPoint(nextLineBuffer, points, 3, 3); addPoint(colorBuffer, colors, 0, 4); for (int i = 1; i < plen - 1; i++) { addPoint(previousLineBuffer, points, 3 * (i - 1), 3); addPoint(lineBuffer, points, 3 * i, 3); addPoint(nextLineBuffer, points, 3 * (i + 1), 3); addPoint(colorBuffer, colors, 4 * i, 4); } addPoint(previousLineBuffer, points, 3 * (plen - 2), 3); addPoint(lineBuffer, points, 3 * (plen - 1), 3); addPoint(nextLineBuffer, points, 3 * (plen - 1), 3); addPoint(colorBuffer, colors, 4 * (plen - 1), 4); previousLineBuffer.flip(); lineBuffer.flip(); nextLineBuffer.flip(); directionBuffer.flip(); colorBuffer.flip(); vbos[0].bindBufferData(gl, previousLineBuffer, Buffers.SIZEOF_FLOAT); vbos[1].bindBufferData(gl, lineBuffer, Buffers.SIZEOF_FLOAT); vbos[2].bindBufferData(gl, nextLineBuffer, Buffers.SIZEOF_FLOAT); vbos[3].bindBufferData(gl, directionBuffer, Buffers.SIZEOF_FLOAT); vbos[4].bindBufferData(gl, colorBuffer, Buffers.SIZEOF_FLOAT); IntBuffer indexBuffer = gen_indices(plen); ivbo.bindBufferData(gl, indexBuffer, Buffers.SIZEOF_INT); } public void dispose(GL2 gl) { disposeVBOs(gl); } }
package org.irmacard.idemix; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Vector; import org.irmacard.idemix.util.IdemixLogEntry; import net.sourceforge.scuba.smartcards.CardService; import net.sourceforge.scuba.smartcards.CardServiceException; import net.sourceforge.scuba.smartcards.CommandAPDU; import net.sourceforge.scuba.smartcards.ProtocolCommand; import net.sourceforge.scuba.smartcards.ProtocolCommands; import net.sourceforge.scuba.smartcards.ProtocolResponse; import net.sourceforge.scuba.smartcards.ProtocolResponses; import net.sourceforge.scuba.smartcards.ResponseAPDU; import net.sourceforge.scuba.util.Hex; import com.ibm.zurich.idmx.api.ProverInterface; import com.ibm.zurich.idmx.api.RecipientInterface; import com.ibm.zurich.idmx.dm.Credential; import com.ibm.zurich.idmx.dm.Values; import com.ibm.zurich.idmx.dm.structure.AttributeStructure; import com.ibm.zurich.idmx.issuance.IssuanceSpec; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.ProofSpec; public class IdemixService extends CardService implements ProverInterface, RecipientInterface { /** * Universal version identifier to match versions during deserialisation. */ private static final long serialVersionUID = -6317383635196413L; /** * Control the amount of output generated by this class. */ private static final boolean VERBOSE = true; /** * SCUBA service to communicate with the card. */ protected CardService service; /** * Credential issuance specification. */ protected IssuanceSpec issuanceSpec; /** * Credential identifier. */ protected short credentialId; /** * Card Version, this is read when the applet is selected */ protected byte[] cardVersion = null; /* SCUBA / Smart Card Setup */ /** * Construct a new Idemix service based on some CardService, which will be * used for the actual communication with an Idemix applet. * * @param service the service to use for communication with the applet. */ public IdemixService(CardService service) { this.service = service; } /** * Construct a new Idemix service based on some CardService, which will be * used for the actual communication with an Idemix applet. * * @param service the service to use for communication with the applet. * @param credential identifier. */ public IdemixService(CardService service, short credentialId) { this.service = service; this.credentialId = credentialId; } /** * Open a communication channel to an Idemix applet. */ public void open() throws CardServiceException { if (!isOpen()) { service.open(); } cardVersion = selectApplication(); } /** * Check whether a communication channel with a smart card exists. * * @return whether the channel is open or not. */ public boolean isOpen() { return service.isOpen(); } /** * Send an APDU over the communication channel to the smart card. * * @param apdu the APDU to be send to the smart card. * @return ResponseAPDU the response from the smart card. * @throws CardServiceException if some error occurred while transmitting. */ public ResponseAPDU transmit(CommandAPDU capdu) throws CardServiceException { if (VERBOSE) { System.out.println(); System.out.println("C: " + Hex.bytesToHexString(capdu.getBytes())); } long start = System.nanoTime(); ResponseAPDU rapdu = service.transmit(capdu); long duration = (System.nanoTime() - start)/1000000; if (VERBOSE) { System.out.println(" duration: " + duration + " ms"); System.out.println("R: " + Hex.bytesToHexString(rapdu.getBytes())); } return rapdu; } public byte[] transmitControlCommand(int controlCode, byte[] command) throws CardServiceException { return service.transmitControlCommand(controlCode, command); } /** * Close the communication channel with the Idemix applet. */ public void close() { if (service != null) { service.close(); } } public byte[] getATR() throws CardServiceException { return service.getATR(); } public String getName() { return "Idemix: " + service.getName(); } /** * Execute a protocol command on the smart card. * * @param command to be executed on the card. * @return the response received from the card. * @throws CardServiceException if an error occurred. */ public ProtocolResponse execute(ProtocolCommand command) throws CardServiceException { ResponseAPDU response = transmit(command.getAPDU()); if (response.getSW() != 0x00009000) { // don't bother with the rest of the commands... throw new CardServiceException(String.format( "Command failed: \"%s\", SW: %04x (%s)", command.getDescription(), response.getSW(), command.getErrorMessage(response.getSW())), response.getSW()); } return new ProtocolResponse(command.getKey(), response); } /** * Execute a list of protocol commands on the smart card. * * @param commands to be executed on the card. * @return the responses received from the card. * @throws CardServiceException if an error occurred. */ public ProtocolResponses execute(ProtocolCommands commands) throws CardServiceException { ProtocolResponses responses = new ProtocolResponses(); for (ProtocolCommand command: commands) { ProtocolResponse response = execute(command); responses.put(response.getKey(), response); } return responses; } /** * Set the credential to interact with. * * @param identifier of the credential. */ public void setCredential(short identifier) { credentialId = identifier; } /** * Select the Idemix applet on the smart card. * * @throws CardServiceException if an error occurred. */ public byte[] selectApplication() throws CardServiceException { ProtocolResponse response = execute(IdemixSmartcard.selectApplicationCommand); return response.getData(); } /** * Send the pin to the card. This defaults to the credential pin. * * @throws CardServiceException if an error occurred. */ public void sendPin(byte[] pin) throws CardServiceException { sendCredentialPin(pin); } /** * Send credential pin to the card. This PIN has to be sent before * new credentials can be issued and before certain credentials can be * read. * * @param pin ASCII encoded pin * @return Number of tries left, or -1 in case of success * @throws CardServiceException if an error occurred. */ public int sendCredentialPin(byte[] pin) throws CardServiceException { return sendPin(IdemixSmartcard.P2_PIN_ATTRIBUTE, pin); } /** * Send card pin to the card. This PIN has to be sent before * any management operations are allowed on the card. * * @param pin ASCII encoded pin * @return Number of tries left, or -1 in case of success * @throws CardServiceException if an error occurred. */ public int sendCardPin(byte[] pin) throws CardServiceException { return sendPin(IdemixSmartcard.P2_PIN_ADMIN, pin); } /** * Send the pin to the card. * * @param pinID the type of PIN that is send to the card. * @param pin ASCII encoded pin * @return Number of tries left, or -1 in case of success * @throws CardServiceException if an error occurred. */ public int sendPin(byte pinID, byte[] pin) throws CardServiceException { try { execute(IdemixSmartcard.sendPinCommand(pinID, pin)); } catch (CardServiceException e) { if (!e.getMessage().toUpperCase().contains("63C")) { throw e; } return e.getSW() - 0x000063C0; } return -1; } /** * Update the pin on the card * * Note that to use this function one first needs to establish an * authenticated connection to the card. * @return Number of tries left, or -1 in case of success */ public int updatePin(byte[] oldPin, byte[] newPin) throws CardServiceException { return updatePin(IdemixSmartcard.P2_PIN_ATTRIBUTE, oldPin, newPin); } /** * Update the pin on the card * * Note that to use this function one first needs to establish an * authenticated connection to the card. * @return Number of tries left, or -1 in case of success */ public int updatePin(byte pinID, byte[] oldPin, byte[] newPin) throws CardServiceException { try { execute(IdemixSmartcard.updatePinCommand(pinID, oldPin, newPin)); } catch (CardServiceException e) { if (!e.getMessage().toUpperCase().contains("63C")) { throw e; } return e.getSW() - 0x000063C0; } return -1; } /** * Update the card-pin on the card * * Note that to use this function one first needs to establish an * authenticated connection to the card. * @return Number of tries left, or -1 in case of success */ public int updateCardPin(byte[] oldPin, byte[] newPin) throws CardServiceException { return updatePin(IdemixSmartcard.P2_PIN_ADMIN, oldPin, newPin); } /** * Update the credential-pin on the card * * Note that to use this function one first needs to establish an * authenticated connection to the card. * @return Number of tries left, or -1 in case of success */ public int updateCredentialPin(byte[] oldPin, byte[] newPin) throws CardServiceException { return updatePin(IdemixSmartcard.P2_PIN_ATTRIBUTE, oldPin, newPin); } /** * Generate the master secret: * * <pre> * m_0 * </pre> * * @throws CardServiceException if an error occurred. */ public void generateMasterSecret() throws CardServiceException { execute(IdemixSmartcard.generateMasterSecretCommand); } /** * @param theNonce1 * Nonce provided by the verifier. * @return Message containing the proof about the hidden and committed * attributes sent to the Issuer. */ public Message round1(final Message msg) { // Hide CardServiceExceptions, instead return null on failure try { ProtocolCommands commands = IdemixSmartcard.round1Commands(issuanceSpec, msg); ProtocolResponses responses = execute(commands); return IdemixSmartcard.processRound1Responses(responses); // Report caught exceptions } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Called with the second protocol flow as input, outputs the Credential. * This is the last step of the issuance protocol, where the Recipient * verifies that the signature is valid and outputs it. * * @param msg * the second flow of the protocol, a message from the Issuer * @return null */ public Credential round3(final Message msg) { // Hide CardServiceExceptions, instead return null on failure try { // send Signature execute(IdemixSmartcard.round3Commands(issuanceSpec, msg)); // Do NOT return the generated Idemix credential return null; // Report caught exceptions } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Builds an Identity mixer show-proof data structure, which can be passed * to the verifier for verification. * * @return Identity mixer show-proof data structure. */ public Proof buildProof(final BigInteger nonce, final ProofSpec spec) { // Hide CardServiceExceptions, instead return null on failure try { ProtocolCommands commands = IdemixSmartcard.buildProofCommands( nonce, spec, credentialId); ProtocolResponses responses = execute(commands); return IdemixSmartcard.processBuildProofResponses(responses, spec); // Report caught exceptions } catch (CardServiceException e) { System.err.println(e.getMessage() + "\n"); e.printStackTrace(); return null; } } /** * Set the specification of a certificate issuance: * * <ul> * <li> issuer public key, and * <li> context. * </ul> * * @param spec the specification to be set. * @throws CardServiceException if an error occurred. */ public void setIssuanceSpecification(IssuanceSpec spec) throws CardServiceException { issuanceSpec = spec; execute(IdemixSmartcard.setIssuanceSpecificationCommands(spec, credentialId)); } /** * Set the attributes: * * <pre> * m_1, ..., m_l * </pre> * * @param spec the issuance specification for the ordering of the values. * @param values the attributes to be set. * @throws CardServiceException if an error occurred. */ public void setAttributes(IssuanceSpec spec, Values values) throws CardServiceException { execute(IdemixSmartcard.setAttributesCommands(spec, values)); } public Vector<Integer> getCredentials() throws CardServiceException { Vector<Integer> list = new Vector<Integer>(); ProtocolResponse response = execute(IdemixSmartcard.getCredentialsCommand()); byte[] data = response.getData(); for (int i = 0; i < data.length; i = i+2) { int id = ((data[i] & 0xff) << 8) | data[i + 1]; if (id != 0) { list.add(id); } } return list; } public void selectCredential(short id) throws CardServiceException { execute(IdemixSmartcard.selectCredentialCommand(id)); } public HashMap<String, BigInteger> getAttributes(IssuanceSpec spec) throws CardServiceException { HashMap<String, BigInteger> attributes = new HashMap<String, BigInteger>(); ProtocolCommands commands = IdemixSmartcard.getAttributesCommands(spec); ProtocolResponses responses = execute(commands); for (AttributeStructure attribute : spec.getCredentialStructure().getAttributeStructs()) { String attName = attribute.getName(); attributes.put(attName, new BigInteger(1, responses.get("attr_" + attName).getData())); } return attributes; } public void removeCredential(short id) throws CardServiceException { execute(IdemixSmartcard.removeCredentialCommand(id)); } public short getCredentialFlags() throws CardServiceException { ProtocolResponse response = execute(IdemixSmartcard.getCredentialFlagsCommand()); byte[] data = response.getData(); return (short) ((data[0] << 8) | data[1]); } public void setCredentialFlags(short flags) throws CardServiceException { execute(IdemixSmartcard.setCredentialFlagsCommand(flags)); } private final int LOG_SIZE = 30; private final int LOG_ENTRY_SIZE = 16; private final byte LOG_ENTRIES_PER_APDU = 255 / 16; /** * FIXME: make non-interactive via IdemixSmartcard * @throws CardServiceException */ public List<IdemixLogEntry> getLogEntries() throws CardServiceException { ProtocolResponse response; Vector<IdemixLogEntry> list = new Vector<IdemixLogEntry>(); for (byte start_entry = 0; start_entry < LOG_SIZE; start_entry = (byte) (start_entry + LOG_ENTRIES_PER_APDU)) { response = execute(IdemixSmartcard.getLogCommand(start_entry)); byte[] data = response.getData(); for (int entry = 0; entry < LOG_ENTRIES_PER_APDU && entry + start_entry < LOG_SIZE; entry++) { byte[] log_entry = Arrays.copyOfRange(data, LOG_ENTRY_SIZE * entry, LOG_ENTRY_SIZE * (entry + 1)); System.out.println(Hex.bytesToHexString(log_entry)); list.add(new IdemixLogEntry(log_entry)); } } return list; } public byte[] getCardVersion() { return cardVersion; } }
package org.mozilla.javascript; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import org.mozilla.javascript.json.JsonParser; import org.mozilla.javascript.xml.XMLObject; /** * This class implements the JSON native object. See ECMA 15.12. * * @author Matthew Crumley, Raphael Speyer */ public final class NativeJSON extends IdScriptableObject { private static final long serialVersionUID = -4567599697595654984L; private static final Object JSON_TAG = "JSON"; private static final int MAX_STRINGIFY_GAP_LENGTH = 10; static void init(Scriptable scope, boolean sealed) { NativeJSON obj = new NativeJSON(); obj.activatePrototypeMap(MAX_ID); obj.setPrototype(getObjectPrototype(scope)); obj.setParentScope(scope); if (sealed) { obj.sealObject(); } ScriptableObject.defineProperty(scope, "JSON", obj, ScriptableObject.DONTENUM); } private NativeJSON() {} @Override public String getClassName() { return "JSON"; } @Override protected void initPrototypeId(int id) { if (id <= LAST_METHOD_ID) { String name; int arity; switch (id) { case Id_toSource: arity = 0; name = "toSource"; break; case Id_parse: arity = 2; name = "parse"; break; case Id_stringify: arity = 3; name = "stringify"; break; default: throw new IllegalStateException(String.valueOf(id)); } initPrototypeMethod(JSON_TAG, id, name, arity); } else { throw new IllegalStateException(String.valueOf(id)); } } @Override public Object execIdCall( IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(JSON_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int methodId = f.methodId(); switch (methodId) { case Id_toSource: return "JSON"; case Id_parse: { String jtext = ScriptRuntime.toString(args, 0); Object reviver = null; if (args.length > 1) { reviver = args[1]; } if (reviver instanceof Callable) { return parse(cx, scope, jtext, (Callable) reviver); } return parse(cx, scope, jtext); } case Id_stringify: { Object value = Undefined.instance, replacer = null, space = null; if (args.length > 0) { value = args[0]; if (args.length > 1) { replacer = args[1]; if (args.length > 2) { space = args[2]; } } } return stringify(cx, scope, value, replacer, space); } default: throw new IllegalStateException(String.valueOf(methodId)); } } private static Object parse(Context cx, Scriptable scope, String jtext) { try { return new JsonParser(cx, scope).parseValue(jtext); } catch (JsonParser.ParseException ex) { throw ScriptRuntime.constructError("SyntaxError", ex.getMessage()); } } public static Object parse(Context cx, Scriptable scope, String jtext, Callable reviver) { Object unfiltered = parse(cx, scope, jtext); Scriptable root = cx.newObject(scope); root.put("", root, unfiltered); return walk(cx, scope, reviver, root, ""); } private static Object walk( Context cx, Scriptable scope, Callable reviver, Scriptable holder, Object name) { final Object property; if (name instanceof Number) { property = holder.get(((Number) name).intValue(), holder); } else { property = holder.get(((String) name), holder); } if (property instanceof Scriptable) { Scriptable val = ((Scriptable) property); if (val instanceof NativeArray) { long len = ((NativeArray) val).getLength(); for (long i = 0; i < len; i++) { // indices greater than MAX_INT are represented as strings if (i > Integer.MAX_VALUE) { String id = Long.toString(i); Object newElement = walk(cx, scope, reviver, val, id); if (newElement == Undefined.instance) { val.delete(id); } else { val.put(id, val, newElement); } } else { int idx = (int) i; Object newElement = walk(cx, scope, reviver, val, Integer.valueOf(idx)); if (newElement == Undefined.instance) { val.delete(idx); } else { val.put(idx, val, newElement); } } } } else { Object[] keys = val.getIds(); for (Object p : keys) { Object newElement = walk(cx, scope, reviver, val, p); if (newElement == Undefined.instance) { if (p instanceof Number) val.delete(((Number) p).intValue()); else val.delete((String) p); } else { if (p instanceof Number) val.put(((Number) p).intValue(), val, newElement); else val.put((String) p, val, newElement); } } } } return reviver.call(cx, scope, holder, new Object[] {name, property}); } private static String repeat(char c, int count) { char chars[] = new char[count]; Arrays.fill(chars, c); return new String(chars); } private static class StringifyState { StringifyState( Context cx, Scriptable scope, String indent, String gap, Callable replacer, List<Object> propertyList) { this.cx = cx; this.scope = scope; this.indent = indent; this.gap = gap; this.replacer = replacer; this.propertyList = propertyList; } Stack<Scriptable> stack = new Stack<Scriptable>(); String indent; String gap; Callable replacer; List<Object> propertyList; Context cx; Scriptable scope; } public static Object stringify( Context cx, Scriptable scope, Object value, Object replacer, Object space) { String indent = ""; String gap = ""; List<Object> propertyList = null; Callable replacerFunction = null; if (replacer instanceof Callable) { replacerFunction = (Callable) replacer; } else if (replacer instanceof NativeArray) { propertyList = new LinkedList<Object>(); NativeArray replacerArray = (NativeArray) replacer; for (int i : replacerArray.getIndexIds()) { Object v = replacerArray.get(i, replacerArray); if (v instanceof String || v instanceof Number) { propertyList.add(v); } else if (v instanceof NativeString || v instanceof NativeNumber) { propertyList.add(ScriptRuntime.toString(v)); } } } if (space instanceof NativeNumber) { space = Double.valueOf(ScriptRuntime.toNumber(space)); } else if (space instanceof NativeString) { space = ScriptRuntime.toString(space); } if (space instanceof Number) { int gapLength = (int) ScriptRuntime.toInteger(space); gapLength = Math.min(MAX_STRINGIFY_GAP_LENGTH, gapLength); gap = (gapLength > 0) ? repeat(' ', gapLength) : ""; } else if (space instanceof String) { gap = (String) space; if (gap.length() > MAX_STRINGIFY_GAP_LENGTH) { gap = gap.substring(0, MAX_STRINGIFY_GAP_LENGTH); } } StringifyState state = new StringifyState(cx, scope, indent, gap, replacerFunction, propertyList); ScriptableObject wrapper = new NativeObject(); wrapper.setParentScope(scope); wrapper.setPrototype(ScriptableObject.getObjectPrototype(scope)); wrapper.defineProperty("", value, 0); return str("", wrapper, state); } private static Object str(Object key, Scriptable holder, StringifyState state) { Object value = null; if (key instanceof String) { value = getProperty(holder, (String) key); } else { value = getProperty(holder, ((Number) key).intValue()); } if (value instanceof Scriptable && hasProperty((Scriptable) value, "toJSON")) { Object toJSON = getProperty((Scriptable) value, "toJSON"); if (toJSON instanceof Callable) { value = callMethod(state.cx, (Scriptable) value, "toJSON", new Object[] {key}); } } if (state.replacer != null) { value = state.replacer.call(state.cx, state.scope, holder, new Object[] {key, value}); } if (value instanceof NativeNumber) { value = Double.valueOf(ScriptRuntime.toNumber(value)); } else if (value instanceof NativeString) { value = ScriptRuntime.toString(value); } else if (value instanceof NativeBoolean) { value = ((NativeBoolean) value).getDefaultValue(ScriptRuntime.BooleanClass); } else if (value instanceof NativeJavaObject) { value = ((NativeJavaObject) value).unwrap(); if (value instanceof Map) { Map<?, ?> map = (Map<?, ?>) value; NativeObject nObj = new NativeObject(); map.forEach( (k, v) -> { if (k instanceof CharSequence) { nObj.put(((CharSequence) k).toString(), nObj, v); } }); value = nObj; } else { if (value instanceof Collection<?>) { Collection<?> col = (Collection<?>) value; value = col.toArray(new Object[col.size()]); } if (value instanceof Object[]) { value = new NativeArray((Object[]) value); } } } else if (value instanceof XMLObject) { value = ((XMLObject) value).toString(); } if (value == null) return "null"; if (value.equals(Boolean.TRUE)) return "true"; if (value.equals(Boolean.FALSE)) return "false"; if (value instanceof CharSequence) { return quote(value.toString()); } if (value instanceof Number) { double d = ((Number) value).doubleValue(); if (!Double.isNaN(d) && d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY) { return ScriptRuntime.toString(value); } return "null"; } if (value instanceof Scriptable) { if (!(value instanceof Callable)) { if (value instanceof NativeArray) { return ja((NativeArray) value, state); } return jo((Scriptable) value, state); } } else if (!Undefined.isUndefined(value)) { throw ScriptRuntime.typeErrorById( "msg.json.cant.serialize", value.getClass().getName()); } return Undefined.instance; } private static String join(Collection<Object> objs, String delimiter) { if (objs == null || objs.isEmpty()) { return ""; } Iterator<Object> iter = objs.iterator(); if (!iter.hasNext()) return ""; StringBuilder builder = new StringBuilder(iter.next().toString()); while (iter.hasNext()) { builder.append(delimiter).append(iter.next()); } return builder.toString(); } private static String jo(Scriptable value, StringifyState state) { if (state.stack.search(value) != -1) { throw ScriptRuntime.typeErrorById("msg.cyclic.value"); } state.stack.push(value); String stepback = state.indent; state.indent = state.indent + state.gap; Object[] k = null; if (state.propertyList != null) { k = state.propertyList.toArray(); } else { k = value.getIds(); } List<Object> partial = new LinkedList<Object>(); for (Object p : k) { Object strP = str(p, value, state); if (strP != Undefined.instance) { String member = quote(p.toString()) + ":"; if (state.gap.length() > 0) { member = member + " "; } member = member + strP; partial.add(member); } } final String finalValue; if (partial.isEmpty()) { finalValue = "{}"; } else { if (state.gap.length() == 0) { finalValue = '{' + join(partial, ",") + '}'; } else { String separator = ",\n" + state.indent; String properties = join(partial, separator); finalValue = "{\n" + state.indent + properties + '\n' + stepback + '}'; } } state.stack.pop(); state.indent = stepback; return finalValue; } private static String ja(NativeArray value, StringifyState state) { if (state.stack.search(value) != -1) { throw ScriptRuntime.typeErrorById("msg.cyclic.value"); } state.stack.push(value); String stepback = state.indent; state.indent = state.indent + state.gap; List<Object> partial = new LinkedList<Object>(); long len = value.getLength(); for (long index = 0; index < len; index++) { Object strP; if (index > Integer.MAX_VALUE) { strP = str(Long.toString(index), value, state); } else { strP = str(Integer.valueOf((int) index), value, state); } if (strP == Undefined.instance) { partial.add("null"); } else { partial.add(strP); } } final String finalValue; if (partial.isEmpty()) { finalValue = "[]"; } else { if (state.gap.length() == 0) { finalValue = '[' + join(partial, ",") + ']'; } else { String separator = ",\n" + state.indent; String properties = join(partial, separator); finalValue = "[\n" + state.indent + properties + '\n' + stepback + ']'; } } state.stack.pop(); state.indent = stepback; return finalValue; } private static String quote(String string) { StringBuilder product = new StringBuilder(string.length() + 2); // two extra chars for " on either side product.append('"'); int length = string.length(); for (int i = 0; i < length; i++) { char c = string.charAt(i); switch (c) { case '"': product.append("\\\""); break; case '\\': product.append("\\\\"); break; case '\b': product.append("\\b"); break; case '\f': product.append("\\f"); break; case '\n': product.append("\\n"); break; case '\r': product.append("\\r"); break; case '\t': product.append("\\t"); break; default: if (c < ' ') { product.append("\\u"); String hex = String.format("%04x", Integer.valueOf((int) c)); product.append(hex); } else { product.append(c); } break; } } product.append('"'); return product.toString(); } // #string_id_map# @Override protected int findPrototypeId(String s) { int id; // switch (s) { case "toSource": id = Id_toSource; break; case "parse": id = Id_parse; break; case "stringify": id = Id_stringify; break; default: id = 0; break; } // #/generated# return id; } private static final int Id_toSource = 1, Id_parse = 2, Id_stringify = 3, LAST_METHOD_ID = 3, MAX_ID = 3; // #/string_id_map# }
package org.selfip.bkimmel.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import org.selfip.bkimmel.io.NullOutputStream; import org.selfip.bkimmel.io.StreamUtil; /** * Utility methods for working with classes. * @author brad */ public final class ClassUtil { /** * Gets an <code>InputStream</code> from which the specified class' * bytecode definition may be read. * @param cl The <code>Class</code> for which to get the stream. * @return An <code>InputStream</code> from which the specified class' * bytecode definition may be read. */ public static InputStream getClassAsStream(Class<?> cl) { String resourceName = cl.getSimpleName() + ".class"; return cl.getResourceAsStream(resourceName); } /** * Computes a digest from a class' bytecode. * @param cl The <code>Class</code> for which to compute the digest. * @param digest The <code>MessageDigest</code> to update. */ public static void getClassDigest(Class<?> cl, MessageDigest digest) { DigestOutputStream out = new DigestOutputStream(NullOutputStream.getInstance(), digest); try { writeClassToStream(cl, out); } catch (IOException e) { e.printStackTrace(); throw new UnexpectedException(e); } } /** * Writes a class' bytecode to an <code>OutputStream</code>. * @param cl The <code>Class</code> to write. * @param out The <code>OutputStream</code> to write to. * @throws IOException If unable to write to <code>out</code>. */ public static void writeClassToStream(Class<?> cl, OutputStream out) throws IOException { InputStream in = getClassAsStream(cl); StreamUtil.writeStream(in, out); } /** * Gets the outer class (a class with no enclosing class) that contains the * given class. * @param cl The <code>Class</code> for which to find the outer class. If * <code>class_</code> is an outer class, then <code>class_</code> is * returned. * @return The outer <code>Outer</code> class containing * <code>class_</code>. */ public static Class<?> getOuterClass(Class<?> cl) { Class<?> enclosingClass; while ((enclosingClass = cl.getEnclosingClass()) != null) { cl = enclosingClass; } return cl; } /** Declared private to prevent this class from being instantiated. */ private ClassUtil() {} }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc5933.ubot; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.RobotDrive; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static CANTalon driveTrainFrontLeftMotor; public static CANTalon driveTrainRearLeftMotor; public static CANTalon driveTrainFrontRightMotor; public static CANTalon driveTrainRearRightMotor; public static RobotDrive driveTrainRobotDrive; public static PowerDistributionPanel powerPowerDistributionPanel; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static void init() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrainFrontLeftMotor = new CANTalon(10); LiveWindow.addActuator("DriveTrain", "FrontLeftMotor", driveTrainFrontLeftMotor); driveTrainRearLeftMotor = new CANTalon(11); LiveWindow.addActuator("DriveTrain", "RearLeftMotor", driveTrainRearLeftMotor); driveTrainFrontRightMotor = new CANTalon(12); LiveWindow.addActuator("DriveTrain", "FrontRightMotor", driveTrainFrontRightMotor); driveTrainRearRightMotor = new CANTalon(13); LiveWindow.addActuator("DriveTrain", "RearRightMotor", driveTrainRearRightMotor); driveTrainRobotDrive = new RobotDrive(driveTrainFrontLeftMotor, driveTrainRearLeftMotor, driveTrainFrontRightMotor, driveTrainRearRightMotor); driveTrainRobotDrive.setSafetyEnabled(true); driveTrainRobotDrive.setExpiration(0.1); driveTrainRobotDrive.setSensitivity(0.5); driveTrainRobotDrive.setMaxOutput(1.0); powerPowerDistributionPanel = new PowerDistributionPanel(0); LiveWindow.addSensor("Power", "PowerDistributionPanel", powerPowerDistributionPanel); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } }
package com.kuxhausen.huemore; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.kuxhausen.huemore.billing.IabHelper; import com.kuxhausen.huemore.billing.IabResult; import com.kuxhausen.huemore.billing.Inventory; import com.kuxhausen.huemore.billing.Purchase; import com.kuxhausen.huemore.database.DatabaseDefinitions; import com.kuxhausen.huemore.database.DatabaseDefinitions.PlayItems; import com.kuxhausen.huemore.database.DatabaseHelper; import com.kuxhausen.huemore.database.DatabaseDefinitions.GroupColumns; import com.kuxhausen.huemore.database.DatabaseDefinitions.MoodColumns; import com.kuxhausen.huemore.database.DatabaseDefinitions.PreferencesKeys; import com.kuxhausen.huemore.network.GetBulbList; import com.kuxhausen.huemore.network.TransmitGroupMood; import com.kuxhausen.huemore.ui.registration.RegisterWithHubDialogFragment; /** * @author Eric Kuxhausen * */ public class MainActivity extends FragmentActivity implements GroupBulbPagingFragment.OnBulbGroupSelectedListener, MoodsFragment.OnMoodSelectedListener { DatabaseHelper databaseHelper = new DatabaseHelper(this); Integer[] bulbS; String mood; IabHelper mPlayHelper; MainActivity m; Inventory lastQuerriedInventory; public GetBulbList.OnListReturnedListener bulbListenerFragment; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hue_more); m = this; // Check whether the activity is using the layout version with // the fragment_container FrameLayout. If so, we must add the first // fragment if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create an instance of ExampleFragment GroupBulbPagingFragment firstFragment = new GroupBulbPagingFragment(); // GroupsFragment firstFragment = new GroupsFragment(); // In case this activity was started with special instructions from // an Intent, // pass the Intent's extras to the fragment as arguments firstFragment.setArguments(getIntent().getExtras()); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(this); if (!settings.contains(PreferencesKeys.First_Run)) { databaseHelper.initialPopulate();// initialize database // Mark no longer first run in preferences cache Editor edit = settings.edit(); edit.putBoolean(PreferencesKeys.First_Run, false); edit.putInt(PreferencesKeys.Bulbs_Unlocked, PreferencesKeys.ALWAYS_FREE_BULBS);// TODO load from // google store edit.commit(); } // check to see if the bridge IP address is setup yet if (!settings.contains(PreferencesKeys.Bridge_IP_Address)) { RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment(); rwhdf.show(this.getSupportFragmentManager(), "dialog"); } String firstChunk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgPUhHgGEdnpyPMAWgP3Xw/jHkReU1O0n6d4rtcULxOrVl/hcZlOsVyByMIZY5wMD84gmMXjbz8pFb4RymFTP7Yp8LSEGiw6DOXc7ydNd0lbZ4WtKyDEwwaio1wRbRPxdU7/4JBpMCh9L6geYx6nYLt0ExZEFxULV3dZJpIlEkEYaNGk/64gc0l34yybccYfORrWzu8u+"; String secondChunk = "5YxJ5k1ikIJJ2I7/2Rp5AXkj2dWybmT+AGx83zh8+iMGGawEQerGtso9NUqpyZWU08EO9DcF8r2KnFwjmyWvqJ2JzbqCMNt0A08IGQNOrd16/C/65GE6J/EtsggkNIgQti6jD7zd3b2NAQIDAQAB"; String base64EncodedPublicKey= firstChunk + secondChunk; // compute your public key and store it in base64EncodedPublicKey mPlayHelper = new IabHelper(this, base64EncodedPublicKey); mPlayHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { // Oh noes, there was a problem. Log.d("asdf", "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up! mPlayHelper.queryInventoryAsync(mGotInventoryListener); if(m.bulbListenerFragment != null){ GetBulbList pushGroupMood = new GetBulbList(); pushGroupMood.execute(m, m.bulbListenerFragment); } } }); } // Listener that's called when we finish querying the items and subscriptions we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d("asdf", "Query inventory finished."); if (result.isFailure()) { // handle error return; } else{ Log.d("asdf", "Query inventory was successful."); lastQuerriedInventory = inventory; int numUnlocked = PreferencesKeys.ALWAYS_FREE_BULBS; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7)) numUnlocked+=5; if(inventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8)) numUnlocked+=5; // update UI accordingly // Get preferences cache SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(m); if(numUnlocked>settings.getInt(PreferencesKeys.Bulbs_Unlocked, PreferencesKeys.ALWAYS_FREE_BULBS)){ // Update the number held in settings Editor edit = settings.edit(); edit.putInt(PreferencesKeys.Bulbs_Unlocked, numUnlocked); edit.commit(); } } /* * Check for items we own. Notice that for each purchase, we check * the developer payload to see if it's correct! See * verifyDeveloperPayload(). */ /* // Do we have the premium upgrade? Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); updateUi(); setWaitScreen(false); Log.d(TAG, "Initial inventory query finished; enabling main UI.");*/ } }; IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { mPlayHelper.queryInventoryAsync(mGotInventoryListener); } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); // Pass on the activity result to the helper for handling if (!mPlayHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { //Log.d(TAG, "onActivityResult handled by IABUtil."); } } @Override public void onResume() { super.onResume(); String firstChunk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgPUhHgGEdnpyPMAWgP3Xw/jHkReU1O0n6d4rtcULxOrVl/hcZlOsVyByMIZY5wMD84gmMXjbz8pFb4RymFTP7Yp8LSEGiw6DOXc7ydNd0lbZ4WtKyDEwwaio1wRbRPxdU7/4JBpMCh9L6geYx6nYLt0ExZEFxULV3dZJpIlEkEYaNGk/64gc0l34yybccYfORrWzu8u+"; String secondChunk = "5YxJ5k1ikIJJ2I7/2Rp5AXkj2dWybmT+AGx83zh8+iMGGawEQerGtso9NUqpyZWU08EO9DcF8r2KnFwjmyWvqJ2JzbqCMNt0A08IGQNOrd16/C/65GE6J/EtsggkNIgQti6jD7zd3b2NAQIDAQAB"; String base64EncodedPublicKey= firstChunk + secondChunk; mPlayHelper = new IabHelper(this, base64EncodedPublicKey); mPlayHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { // Oh noes, there was a problem. Log.d("asdf", "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up! mPlayHelper.queryInventoryAsync(mGotInventoryListener); if(m.bulbListenerFragment != null){ GetBulbList pushGroupMood = new GetBulbList(); pushGroupMood.execute(m, m.bulbListenerFragment); } } }); } /** Verifies the developer payload of a purchase. */ boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. It will be * the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase and * verifying it here might seem like a good approach, but this will fail in the * case where the user purchases an item on one device and then uses your app on * a different device, because on the other device you will not have access to the * random string you originally generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different between them, * so that one user's purchase can't be replayed to another user. * * 2. The payload must be such that you can verify it even when the app wasn't the * one who initiated the purchase flow (so that items purchased by the user on * one device work on other devices owned by the user). * * Using your own server to store and verify developer payloads across app * installations is recommended. */ return true; } @Override public void onStop(){ super.onStop(); if (mPlayHelper != null) mPlayHelper.dispose(); mPlayHelper = null; } @Override public void onDestroy() { super.onDestroy(); if (mPlayHelper != null) mPlayHelper.dispose(); mPlayHelper = null; } @Override public void onGroupBulbSelected(Integer[] bulb) { bulbS = bulb; // Capture the article fragment from the activity layout MoodManualPagingFragment moodFrag = (MoodManualPagingFragment) getSupportFragmentManager() .findFragmentById(R.id.moods_fragment); if (moodFrag != null) { // If article frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content moodFrag.reset(); } else { // If the frag is not available, we're in the one-pane layout and // must swap frags... // Create fragment and give it an argument for the selected article MoodManualPagingFragment newFragment = new MoodManualPagingFragment(); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); // Replace whatever is in the fragment_container view with this // fragment, // and add the transaction to the back stack so the user can // navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); transaction .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); } } @Override public void onMoodSelected(String moodParam) { mood = moodParam; pushMoodGroup(); } public void onBrightnessChanged(String brightnessState[]) { TransmitGroupMood pushGroupMood = new TransmitGroupMood(); pushGroupMood.execute(this, bulbS, brightnessState); } /* * test mood by applying to json states array to these bulbs * * @param states */ /* * public void testMood(Integer[] bulbs, String[] states) { * TransmitGroupMood pushGroupMood = new TransmitGroupMood(); * pushGroupMood.execute(this, bulbs, states); } */ /** * test mood by applying to json states array to previously selected moods * * @param states */ public void testMood(String[] states) { TransmitGroupMood pushGroupMood = new TransmitGroupMood(); pushGroupMood.execute(this, bulbS, states); } private void pushMoodGroup() { if (bulbS == null || mood == null) return; String[] moodColumns = { MoodColumns.STATE }; String[] mWereClause = { mood }; Cursor cursor = getContentResolver().query( DatabaseDefinitions.MoodColumns.MOODSTATES_URI, // Use the // default // content URI // for the // provider. moodColumns, // Return the note ID and title for each note. MoodColumns.MOOD + "=?", // selection clause mWereClause, // election clause args null // Use the default sort order. ); ArrayList<String> moodStates = new ArrayList<String>(); while (cursor.moveToNext()) { moodStates.add(cursor.getString(0)); } String[] moodS = moodStates.toArray(new String[moodStates.size()]); TransmitGroupMood pushGroupMood = new TransmitGroupMood(); pushGroupMood.execute(this, bulbS, moodS); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.action_register_with_hub: RegisterWithHubDialogFragment rwhdf = new RegisterWithHubDialogFragment(); rwhdf.show(getSupportFragmentManager(), "dialog"); return true; case R.id.action_unlock_more_bulbs: if (lastQuerriedInventory==null) mPlayHelper.queryInventoryAsync(mGotInventoryListener); else{ if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_1)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_1, 10001, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_2)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_2, 10002, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_3)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_3, 10003, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_4)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_4, 10004, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_5)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_5, 10005, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_6)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_6, 10006, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_7)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_7, 10007, mPurchaseFinishedListener, ""); else if(!lastQuerriedInventory.hasPurchase(PlayItems.FIVE_BULB_UNLOCK_8)) mPlayHelper.launchPurchaseFlow(this, PlayItems.FIVE_BULB_UNLOCK_8, 10008, mPurchaseFinishedListener, ""); } return true; default: return super.onOptionsItemSelected(item); } } }
package ru.spbau.tinydb.repl; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import ru.spbau.tinydb.common.DBANTLRErrorListener; import ru.spbau.tinydb.common.DBException; import ru.spbau.tinydb.engine.DataBaseEngine; import ru.spbau.tinydb.grammar.SQLGrammarLexer; import ru.spbau.tinydb.grammar.SQLGrammarParser; import ru.spbau.tinydb.queries.IQuery; import ru.spbau.tinydb.queries.SecondLevelId; import ru.spbau.tinydb.queries.SelectFromQuery; import java.io.*; import java.util.*; /** * @author adkozlov */ public abstract class REPLRunnable<Q> implements Runnable, AutoCloseable { private static final String SUCCESS_MESSAGE_FORMAT = "OK%s\n"; private static final String FAILURE_MESSAGE_FORMAT = "ERROR\n%s\n"; private static final String ROWS_AFFECTED_FORMAT = "\n%d rows affected"; private static final String ALREADY_EXISTS = "\nalready exists, not created"; private static final String NO_ROW_SELECTED = "no row selected"; @NotNull private String dbFileName; @NotNull private final BufferedReader stdIn; @NotNull private final PrintWriter stdOut; @NotNull private final PrintWriter stdErr; @Nullable private final FileOutputStream fileOutputStream; @Nullable private final FileOutputStream fileErrorsStream; private REPLRunnable(@NotNull String dbFileName, @NotNull InputStream standardInputStream, @NotNull OutputStream standardOutputStream, @NotNull OutputStream standardErrorsStream) { this.dbFileName = dbFileName; this.stdIn = new BufferedReader(new InputStreamReader(standardInputStream)); this.stdOut = new PrintWriter(new OutputStreamWriter(standardOutputStream)); this.stdErr = new PrintWriter(new OutputStreamWriter(standardErrorsStream)); this.fileOutputStream = standardOutputStream instanceof FileOutputStream ? (FileOutputStream) standardOutputStream : null; this.fileErrorsStream = standardErrorsStream instanceof FileOutputStream ? (FileOutputStream) standardErrorsStream : null; } protected REPLRunnable(@NotNull String dbFileName, @NotNull InputStream standardInputStream, @Nullable String outputFileName, @Nullable String errorsFileName) throws FileNotFoundException { this(dbFileName, standardInputStream, outputFileName != null ? new FileOutputStream(outputFileName) : System.out, errorsFileName != null ? new FileOutputStream(errorsFileName) : System.err ); } @NotNull public String getDbFileName() { return dbFileName; } public void setDbFileName(@NotNull String dbFileName) { this.dbFileName = dbFileName; } @NotNull public BufferedReader getStdIn() { return stdIn; } @NotNull public PrintWriter getStdOut() { return stdOut; } @NotNull public PrintWriter getStdErr() { return stdErr; } protected abstract void innerRun(); @Override public void run() { try (REPLRunnable runnable = this) { innerRun(); } catch (Exception e) { handleException(e); } } protected void executeAndPrintResult(@NotNull IQuery query) { Object result = executeQuery(query); if (result != null) { printQueryResult(query, result); } } @Nullable private Object executeQuery(@NotNull IQuery query) { try { return query.execute(DataBaseEngine.getDBInstance(dbFileName)); } catch (DBException e) { handleException(e); } return null; } private void printQueryResult(@NotNull IQuery query, @NotNull Object result) { if (result instanceof Integer) { printSuccessMessage(String.format(ROWS_AFFECTED_FORMAT, (Integer) result)); } else if (result instanceof Boolean) { printSuccessMessage((boolean) result ? "" : ALREADY_EXISTS); } else if (result instanceof Iterator) { SelectFromQuery select = (SelectFromQuery) query; printSelectQueryResult(select.getAttributes(), (Iterator<Map<SecondLevelId, Object>>) result); } else { printFailureMessage("unexpected type of result"); } } private void printSelectQueryResult(@NotNull List<String> attributesList, @NotNull Iterator<Map<SecondLevelId, Object>> result) { if (result.hasNext()) { Map<SecondLevelId, Object> row = result.next(); Set<SecondLevelId> attributes = getSelectedAttributes(attributesList, row.keySet()); for (SecondLevelId attribute : attributes) { stdOut.print(attribute + "\t"); } stdOut.flush(); printRow(row, attributes); while (result.hasNext()) { printRow(result.next(), attributes); } } else { stdOut.print(NO_ROW_SELECTED); } stdOut.println(); stdOut.flush(); } private void printRow(@NotNull Map<SecondLevelId, Object> row, @NotNull Set<SecondLevelId> attributes) { stdOut.println(); for (SecondLevelId attribute : attributes) { stdOut.print(row.get(attribute) + "\t"); } stdOut.flush(); } @NotNull private Set<SecondLevelId> getSelectedAttributes(@NotNull List<String> attributesList, @NotNull Set<SecondLevelId> allAttributes) { Set<SecondLevelId> result = new LinkedHashSet<>(); if (attributesList.isEmpty()) { result.addAll(allAttributes); } else { for (String attribute : attributesList) { for (SecondLevelId id : allAttributes) { if (attribute.equals(id.getAttributeName())) { result.add(id); } } } } return result; } protected void printSuccessMessage(@NotNull String message) { stdOut.printf(SUCCESS_MESSAGE_FORMAT, message); stdOut.flush(); } protected void printFailureMessage(@NotNull String message) { stdErr.printf(FAILURE_MESSAGE_FORMAT, message); stdErr.flush(); } protected void handleException(@NotNull Exception e) { String message = e.getMessage(); printFailureMessage(message != null ? message : e.toString()); } @NotNull protected abstract ANTLRInputStream createANTLRInputStream(@NotNull Q query) throws IOException; @Nullable protected final SQLGrammarParser createParser(@NotNull Q query) { try { return createParser(createLexer(createANTLRInputStream(query))); } catch (IOException e) { handleException(e); } return null; } @NotNull protected static SQLGrammarLexer createLexer(@NotNull ANTLRInputStream inputStream) { SQLGrammarLexer result = new SQLGrammarLexer(inputStream); result.removeErrorListeners(); result.addErrorListener(DBANTLRErrorListener.getInstance()); return result; } @NotNull private static SQLGrammarParser createParser(@NotNull SQLGrammarLexer lexer) { SQLGrammarParser result = new SQLGrammarParser(new CommonTokenStream(lexer)); result.removeErrorListeners(); result.addErrorListener(DBANTLRErrorListener.getInstance()); return result; } @Override public void close() throws Exception { closeNullableFileOutputStream(fileOutputStream); closeNullableFileOutputStream(fileErrorsStream); } private static void closeNullableFileOutputStream(@Nullable FileOutputStream fileOutputStream) throws IOException { if (fileOutputStream != null) { fileOutputStream.close(); } } }
package swarm.client.view.cell; import java.util.ArrayList; import java.util.logging.Logger; import swarm.client.app.AppContext; import swarm.client.entities.BufferCell; import swarm.client.entities.I_BufferCellListener; import swarm.client.managers.CameraManager; import swarm.client.view.E_ZIndex; import swarm.client.view.S_UI; import swarm.client.view.U_Css; import swarm.client.view.sandbox.SandboxManager; import swarm.client.view.tabs.code.I_CodeLoadListener; import swarm.client.view.widget.UIBlocker; import swarm.shared.app.S_CommonApp; import swarm.shared.utils.U_Bits; import swarm.shared.utils.U_Math; import swarm.shared.debugging.U_Debug; import swarm.shared.entities.A_Grid; import swarm.shared.entities.E_CodeSafetyLevel; import swarm.shared.entities.E_CodeType; import swarm.shared.structs.Code; import swarm.shared.structs.MutableCode; import swarm.shared.structs.Point; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; public class VisualCell extends AbsolutePanel implements I_BufferCellListener { static enum LayoutState { NOT_CHANGING, CHANGING_FROM_TIME, CHANGING_FROM_SNAP }; private static final Logger s_logger = Logger.getLogger(VisualCell.class.getName()); //private static final String SPINNER_HTML = "<img src='/r.img/spinner.gif?v=1' />"; private static int s_currentId = 0; private static final class CodeLoadListener implements I_CodeLoadListener { private final VisualCell m_this; CodeLoadListener(VisualCell thisArg) { m_this = thisArg; } @Override public void onCodeLoad() { m_this.setStatusHtml(null, false); } } private int m_id; private final AbsolutePanel m_contentPanel = new AbsolutePanel(); private final UIBlocker m_statusPanel = new UIBlocker(); private final AbsolutePanel m_glassPanel = new AbsolutePanel(); private final I_CellSpinner m_spinner; private final MutableCode m_utilCode = new MutableCode(E_CodeType.values()); private BufferCell m_bufferCell = null; //private final ArrayList<Image> //m_backgroundImages = new ArrayList<Image>(); private int m_currentImageIndex = -1; private int m_subCellDimension = -1; private int m_width = 0; private int m_height = 0; private int m_padding = 0; private int m_defaultWidth = 0; private int m_defaultHeight = 0; private int m_baseWidth = 0; private int m_baseHeight = 0; private int m_targetWidth = 0; private int m_targetHeight = 0; private int m_targetXOffset = 0; private int m_targetYOffset = 0; private int m_xOffset = 0; private int m_yOffset = 0; private int m_baseXOffset = 0; private int m_baseYOffset = 0; private double m_baseChangeValue = 0; private boolean m_isValidated = false; private final CodeLoadListener m_codeLoadListener = new CodeLoadListener(this); private final SandboxManager m_sandboxMngr; private final CameraManager m_cameraMngr; private E_CodeSafetyLevel m_codeSafetyLevel; private boolean m_isSnapping = false; private boolean m_isFocused = false; private LayoutState m_layoutState = LayoutState.NOT_CHANGING; private final double m_sizeChangeTime; public VisualCell(I_CellSpinner spinner, SandboxManager sandboxMngr, CameraManager cameraMngr, double sizeChangeTime) { m_spinner = spinner; m_cameraMngr = cameraMngr; m_sandboxMngr = sandboxMngr; m_sizeChangeTime = sizeChangeTime; m_id = s_currentId; s_currentId++; this.addStyleName("visual_cell"); m_glassPanel.addStyleName("sm_cell_glass"); //m_backgroundPanel.getElement().getStyle().setPosition(Position.ABSOLUTE); m_statusPanel.getElement().getStyle().setPosition(Position.RELATIVE); m_statusPanel.getElement().getStyle().setTop(-100, Unit.PCT); m_glassPanel.getElement().getStyle().setPosition(Position.ABSOLUTE); E_ZIndex.CELL_STATUS.assignTo(m_statusPanel); E_ZIndex.CELL_GLASS.assignTo(m_glassPanel); E_ZIndex.CELL_CONTENT.assignTo(m_contentPanel); m_statusPanel.setVisible(false); m_contentPanel.addStyleName("visual_cell_content"); /*int maxImages = smS_App.MAX_CELL_IMAGES; int currentBit = 1; for( int i = 0; i <= 1; i++ ) { Image image = new Image(); image.setUrl("/r.img/cell_size_" + currentBit + ".png"); image.getElement().getStyle().setDisplay(Display.NONE); //m_backgroundImages.add(image); //m_backgroundPanel.add(image); currentBit <<= 1; }*/ U_Css.allowUserSelect(m_contentPanel.getElement(), false); this.add(m_contentPanel); this.add(m_statusPanel); this.add(m_glassPanel); } public BufferCell getBufferCell() { return m_bufferCell; } LayoutState getSizeChangeState() { return m_layoutState; } int getId() { return m_id; } public int getWidth() { return m_width; } int getHeight() { return m_height; } public void update(double timeStep) { if( m_spinner.asWidget().getParent() != null ) { m_spinner.update(timeStep); } if( this.m_layoutState == LayoutState.CHANGING_FROM_SNAP ) { double snapProgress = m_cameraMngr.getWeightedSnapProgress(); //s_logger.severe("cell: " + " " + m_baseChangeValue + " " + snapProgress + " "); double mantissa = m_baseChangeValue == 1 ? 1 : (snapProgress - m_baseChangeValue) / (1-m_baseChangeValue); mantissa = U_Math.clampMantissa(mantissa); this.updateLayout(mantissa); } else if( this.m_layoutState == LayoutState.CHANGING_FROM_TIME ) { m_baseChangeValue += timeStep; double mantissa = m_baseChangeValue / m_sizeChangeTime; mantissa = U_Math.clampMantissa(mantissa); this.updateLayout(mantissa); } } private void updateLayout(double progressMantissa) { double widthDelta = (m_targetWidth - m_baseWidth) * progressMantissa; m_width = (int) (m_baseWidth + widthDelta); double heightDelta = (m_targetHeight - m_baseHeight) * progressMantissa; m_height = (int) (m_baseHeight + heightDelta); double xOffsetDelta = (m_targetXOffset - m_baseXOffset) * progressMantissa; m_xOffset = (int) (m_baseXOffset + xOffsetDelta); double yOffsetDelta = (m_targetYOffset - m_baseYOffset) * progressMantissa; m_yOffset = (int) (m_baseYOffset + yOffsetDelta); //s_logger.severe(m_xOffset + " " + m_targetXOffset + " " + m_baseXOffset); if( progressMantissa >= 1 ) { this.ensureTargetLayout(); } else { this.flushLayout(); } } void validate() { if( m_isValidated ) return; if( m_currentImageIndex != -1 ) { //m_backgroundImages.get(m_currentImageIndex).getElement().getStyle().setDisplay(Display.NONE); } if( m_subCellDimension == 1 ) { this.flushLayout(); this.getElement().getStyle().setPaddingRight(m_padding, Unit.PX); this.getElement().getStyle().setPaddingBottom(m_padding, Unit.PX); //m_backgroundPanel.setSize(m_width+m_padding + "px", m_height+m_padding + "px"); m_currentImageIndex = 0; //m_backgroundImages.get(m_currentImageIndex).getElement().getStyle().setDisplay(Display.BLOCK); //m_backgroundPanel.getElement().getStyle().clearBackgroundColor(); } else if( m_subCellDimension > 1 ) { U_Debug.ASSERT(false, "not implemented"); /*this.setStatusHtml(null, false); // shouldn't have to be done, but what the hell. this.setSize(m_width+"px", m_height+"px"); //m_backgroundPanel.setSize(m_width+"px", m_height+"px"); if( m_subCellDimension > S_CommonApp.MAX_IMAGED_CELL_SIZE ) { //m_backgroundPanel.getElement().getStyle().setBackgroundColor("white"); } else { //m_backgroundPanel.getElement().getStyle().clearBackgroundColor(); m_currentImageIndex = U_Bits.calcBitPosition(m_subCellDimension); //m_backgroundImages.get(m_currentImageIndex).getElement().getStyle().setDisplay(Display.BLOCK); } m_contentPanel.removeStyleName("visual_cell_content");*/ } m_isValidated = true; } private void flushLayout() { this.setSize(m_width+m_padding + "px", m_height+m_padding + "px"); } public void onCreate(BufferCell bufferCell, int width, int height, int padding, int subCellDimension) { m_bufferCell = bufferCell; this.getElement().getStyle().setPosition(Position.ABSOLUTE); m_currentImageIndex = -1; onCreatedOrRecycled(width, height, padding, subCellDimension); } private void onCreatedOrRecycled(int width, int height, int padding, int subCellDimension) { m_layoutState = LayoutState.NOT_CHANGING; m_isFocused = false; m_isValidated = false; m_subCellDimension = subCellDimension; m_targetWidth = m_defaultWidth = m_baseWidth = m_width = width; m_targetHeight = m_defaultHeight = m_baseHeight = m_height = height; m_padding = padding; this.flushLayout(); } public void setTargetLayout(int width, int height, int xOffset, int yOffset) { m_baseXOffset = m_xOffset; m_baseYOffset = m_yOffset; m_baseWidth = this.m_width; m_baseHeight = this.m_height; m_targetWidth = width; m_targetHeight = height; m_targetXOffset = xOffset; m_targetYOffset = yOffset; if( this.m_isSnapping ) { m_baseChangeValue = m_cameraMngr.getWeightedSnapProgress(); m_layoutState = LayoutState.CHANGING_FROM_SNAP; } else if( this.m_isFocused ) { this.ensureTargetLayout(); } } private void ensureTargetLayout() { m_baseWidth = m_width = m_targetWidth; m_baseHeight = m_height = m_targetHeight; m_baseXOffset = m_xOffset = m_targetXOffset; m_baseYOffset = m_yOffset = m_targetYOffset; m_layoutState = LayoutState.NOT_CHANGING; this.flushLayout(); } public void onDestroy() { m_bufferCell = null; m_isFocused = false; m_subCellDimension = -1; if( m_currentImageIndex != -1 ) { //m_backgroundImages.get(m_currentImageIndex).getElement().getStyle().setDisplay(Display.NONE); } if( !E_CodeSafetyLevel.isStatic(m_codeSafetyLevel) ) { this.insertSafeHtml(""); } m_codeSafetyLevel = null; this.pushDown(); } @Override public void onFocusGained() { m_isSnapping = false; m_isFocused = true; E_ZIndex.CELL_FOCUSED.assignTo(this); this.ensureTargetLayout(); this.m_glassPanel.setVisible(false); this.addStyleName("visual_cell_focused"); U_Css.allowUserSelect(m_contentPanel.getElement(), true); m_sandboxMngr.allowScrolling(m_contentPanel.getElement(), true); } @Override public void onFocusLost() { m_isSnapping = false; // just in case. m_isFocused = false; this.m_glassPanel.setVisible(true); this.removeStyleName("visual_cell_focused"); U_Css.allowUserSelect(m_contentPanel.getElement(), false); m_sandboxMngr.allowScrolling(m_contentPanel.getElement(), false); E_ZIndex.CELL_POPPED.assignTo(this); /*if( m_sandboxMngr.isRunning() ) { m_sandboxMngr.stop(m_contentPanel.getElement()); }*/ this.setToTargetSizeDefault(); } public int getXOffset() { return m_xOffset; } public int getYOffset() { return m_yOffset; } public void calcTopLeft(Point point_out) { A_Grid grid = m_bufferCell.getGrid(); m_bufferCell.getCoordinate().calcPoint(point_out, grid.getCellWidth(), grid.getCellHeight(), grid.getCellPadding(), 1); point_out.inc(m_xOffset, m_yOffset, 0); } public void calcTargetTopLeft(Point point_out) { A_Grid grid = m_bufferCell.getGrid(); m_bufferCell.getCoordinate().calcPoint(point_out, grid.getCellWidth(), grid.getCellHeight(), grid.getCellPadding(), 1); point_out.inc(m_targetXOffset, m_targetYOffset, 0); } public int getTargetWidth() { return m_targetWidth; } public int getTargetHeight() { return m_targetHeight; } private void setToTargetSizeDefault() { m_layoutState = LayoutState.CHANGING_FROM_TIME; m_baseChangeValue = 0; this.setTargetLayout(m_defaultWidth, m_defaultHeight, 0, 0); } public void popUp() { if( !m_isFocused ) { E_ZIndex.CELL_POPPED.assignTo(this); m_isSnapping = true; } } public void cancelPopUp() { boolean wasSnapping = m_isSnapping; m_isSnapping = false; if( m_layoutState == LayoutState.CHANGING_FROM_SNAP ) { this.setToTargetSizeDefault(); U_Debug.ASSERT(wasSnapping, "expected cell to know it was snapping"); } } public void pushDown() { this.getElement().getStyle().clearZIndex(); } @Override public void onCellRecycled(int width, int height, int padding, int subCellDimension) { if( subCellDimension != m_subCellDimension ) { m_isValidated = false; } this.onCreatedOrRecycled(width, height, padding, subCellDimension); this.insertSafeHtml(""); this.pushDown(); } @Override public void onError(E_CodeType eType) { //TODO: These are placeholder error messages...should have some prettier error text, or maybe nothing at all? switch( eType ) { case SPLASH: { this.setStatusHtml(null, false); this.showEmptyContent(); break; } case COMPILED: { this.setStatusHtml("Problem contacting server.", false); break; } } } @Override public void setCode(Code code, String cellNamespace) { this.setStatusHtml(null, false); /*if( m_sandboxMngr.isRunning() ) { m_sandboxMngr.stop(m_contentPanel.getElement()); }*/ m_codeSafetyLevel = code.getSafetyLevel(); m_sandboxMngr.start(m_contentPanel.getElement(), code, cellNamespace, m_codeLoadListener); } public E_CodeSafetyLevel getCodeSafetyLevel() { return m_codeSafetyLevel; } private void insertSafeHtml(String html) { m_utilCode.setRawCode(html); m_utilCode.setSafetyLevel(E_CodeSafetyLevel.NO_SANDBOX_STATIC); this.setCode(m_utilCode, ""); } UIBlocker getBlocker() { return m_statusPanel; } @Override public void showLoading() { if( m_spinner.asWidget().getParent() == null ) { m_spinner.reset(); this.m_statusPanel.setContent(m_spinner.asWidget()); } } @Override public void showEmptyContent() { this.insertSafeHtml(""); } private void setStatusHtml(String text, boolean forLoading) { m_statusPanel.setHtml(text); } @Override public void clearLoading() { if( m_spinner.asWidget().getParent() != null ) { this.m_statusPanel.setContent(null); } } }
package com.aol.cyclops; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.stream.Stream; import org.junit.Test; import com.aol.cyclops.control.LazyReact; import com.aol.cyclops.control.ReactiveSeq; import com.aol.cyclops.control.StreamUtils; import com.aol.cyclops.data.async.Queue; import com.aol.cyclops.data.async.QueueFactories; public class Javaone { private String unreliableMethod(String in){ return ""; } private String load(int i){ return ""; } public String loadStr(String load){ return ""; } private void expensiveOp(int i){ } private void save(String in){ } /** public void optional(){ String prefix = "file"; List<String> data; for(int i=0;i<100;i++){ String nextFile = prefix+i; data.add(loadStr(nextFile)); } Stream.iterate(0,i->i+1) .limit(100) .map(i->"prefix"+i) .map(this::loadStr) .collect(Collectors.toList()); new LazyReact().of(1,2,3,4) .map(this::load) .forEach(this::save); ReactiveSeq.of(1,2,3) .schedule("* * * * * ?", Executors.newScheduledThreadPool(1)) .connect() .debounce(1, TimeUnit.SECONDS) .forEach(System.out::println); ReactiveSeq.of(1,2,3,4) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(this::expensiveOp); Subscription s = ReactiveSeq.of(1,2,3,4) .forEachXEvents(2, System.out::println, System.err::println, ()->System.out.println("complete")); s.request(2); SeqSubscriber<Integer> sub = SeqSubscriber.subscriber(); Flux.just(1,2,3,4) .map(i->i*2) .subscribe(sub); ReactiveSeq<Integer> connected = sub.stream(); ReactiveSeq.of(1,2,3) .map(this::load) .recover(e->"default value") .retry(this::unreliableMethod); CompletableFuture f; f.then Seq.of("a","b","c","d") .map(String::toUpperCase) .zipWithIndex() .filter(t->t.v2%2==0) .sliding(3) .duplicate(); Optional<Integer> input; Optional<Integer> times2 = input.map(i->i*2); QueueFactories.<Data>boundedQueue(100) .build() .futureStream() .map(this::process) .run(); } public void stream(){ Stream<Integer> input; Stream<Integer> times2 = input.map(i->i*2); } public void future(){ CompletableFuture<Integer> input; CompletableFuture<Integer> times2 = input.thenApply(i->i*2); } public void dateTime(){ LocalDate date = LocalDate.of(2016, 9, 18); boolean later = LocalDate.now().isAfter(date); } Seq.of(1, 2, 4) .rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b); ReactiveSeq.of(6,5,2,1) .map(e->e*100) .filter(e->e<551) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(e-> { System.out.println("Element " + e + " on thread " + Thread.currentThread().getId()); }); **/ public int loadData(int size){ List<String> list = new ArrayList<>(); for(int i=0;i<size;i++) list.add(""+size); return list.size(); } /** * new LazyReact(Executors.newFixedThreadPool(4)).of(6,5,2,1) .map(this::loadData) .map(List::size) .peek(e->{ System.out.println("data size is " + e + " on thread " + Thread.currentThread().getId()); }) .map(e->e*100) .filter(e->e<551) .forEach(System.out::println); */ public String supplyData(){ try{ Thread.sleep(500); }catch(Exception e){ } return "data"; } public String process(String in){ return "produced on " + Thread.currentThread().getId(); } public void queue(){ Queue<String> transferQueue = QueueFactories.<String>boundedQueue(4) .build(); new LazyReact(Executors.newFixedThreadPool(4)).generate(()->"data") .map(d->"produced on " + Thread.currentThread().getId()) .peek(System.out::println) .peek(d->transferQueue.offer(d)) .run(); transferQueue.stream() .map(e->"Consumed on " + Thread.currentThread().getId()) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(System.out::println); while(true){ // System.out.println(inputQueue.size()); } } public void queue2(){ Queue<String> inputQueue = QueueFactories.<String>boundedQueue(4) .build(); new LazyReact(Executors.newFixedThreadPool(4)).generate(this::supplyData) .map(e->"Produced on " + Thread.currentThread().getId()) .peek(System.out::println) .peek(d->inputQueue.offer(d)) .run(); inputQueue.stream() .map(e->"Consumed on " + Thread.currentThread().getId()) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(System.out::println); while(true){ // System.out.println(inputQueue.size()); } } public void streamException(){ try { Stream.generate(() -> "next") .map(s -> { throw new RuntimeException(); }) .forEach(System.out::println); } catch (Exception e) { e.printStackTrace(); } } public void reactiveSeqException(){ ReactiveSeq.iterate(0,i->i+1) .map(i -> { if( i%3==0) throw new RuntimeException("" + i); return "success " + i; }) .recover(e->"failed " + e.getMessage()) .peek(System.out::println) .scheduleFixedDelay(1_000, Executors.newScheduledThreadPool(1)); while(true); } public void streamEmission(){ StreamUtils.scheduleFixedDelay(Stream.iterate(0,i->i+1) .peek(System.out::println), 1_000, Executors.newScheduledThreadPool(1)); while(true); } public void futureStream(){ new LazyReact(Executors.newFixedThreadPool(4)).of(6,5,2,1) .map(this::loadData) .map(e->e*100) .filter(e->e<551) .peek(e->{ System.out.println("e is " + e + " on thread " + Thread.currentThread().getId()); }) .runOnCurrent(); } public void reactiveSeq(){ ReactiveSeq.of(6,5,2,1) .map(e->e*100) .filter(e->e<551) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(e->{ System.out.println("Element " + e + " on thread " + Thread.currentThread().getId()); }); } public static void main(String[] args){ for (int i = 0; i < 4; i++) { ReactiveSeq.of(6, 5, 2, 1) .map(e -> e * 100) .filter(e -> e < 551) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(e -> { System.out.println("Element " + e + " on thread " + Thread.currentThread() .getId()); }); } for(int i=0;i<4;i++){ ReactiveSeq.of(6,5,2,1) .map(e->e*100) .filter(e->e<551) .futureOperations(Executors.newFixedThreadPool(1)) .forEach(e->{ System.out.println("Element " + e + " on thread " + Thread.currentThread().getId()); }); } } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import seedu.taskmanager.commons.core.Messages; import seedu.taskmanager.logic.commands.AddCommand; import seedu.taskmanager.logic.parser.DateTimeUtil; import seedu.taskmanager.testutil.TestTask; import seedu.taskmanager.testutil.TestUtil; public class AddCommandTest extends TaskManagerGuiTest { // @@author A0130277L @Test public void add() { TestTask[] currentList = td.getTypicalTasks(); // add an event task TestTask taskToAdd = td.event3; assertAddSuccess(taskToAdd, currentList); assertResultMessage(AddCommand.MESSAGE_SUCCESS); currentList = TestUtil.addTasksToList(currentList, taskToAdd); // add a deadline task taskToAdd = td.ddl3; assertAddSuccess(taskToAdd, currentList); assertResultMessage(AddCommand.MESSAGE_SUCCESS); currentList = TestUtil.addTasksToList(currentList, taskToAdd); // add a floating task taskToAdd = td.flt3; assertAddSuccess(taskToAdd, currentList); assertResultMessage(AddCommand.MESSAGE_SUCCESS); currentList = TestUtil.addTasksToList(currentList, taskToAdd); // add duplicate task commandBox.runCommand(td.event2.getAddCommand()); assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK); assertTrue(taskListPanel.isListMatching(currentList)); // add to empty list commandBox.runCommand("clear"); assertAddSuccess(td.event1); // add conflicting event which is in conflict with event1 commandBox.runCommand(td.eventConflicting.getAddCommand()); String expectedResultMessage = AddCommand.MESSAGE_SUCCESS + AddCommand.NEWLINE_STRING + AddCommand.MESSAGE_CONFLICT + AddCommand.NEWLINE_STRING + td.event1.getAsText() + AddCommand.NEWLINE_STRING; assertResultMessage(expectedResultMessage); // invalid command commandBox.runCommand("adds meeting"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); // invalid date-time format commandBox.runCommand("add invalide time format s/ 1-1-2020 e/ @ assertResultMessage(DateTimeUtil.INVALID_DATE_FORMAT); // end date before start date commandBox.runCommand("add end before start from 1/1/2019 to 1/1/2018"); assertResultMessage(Messages.MESSAGE_START_AFTER_END); } // @@author private void assertAddSuccess(TestTask taskToAdd, TestTask... currentList) { commandBox.runCommand(taskToAdd.getAddCommand()); // confirm the new card contains the right data TaskCardHandle addedCard = taskListPanel.navigateToTask(taskToAdd.getName().fullName); assertMatching(taskToAdd, addedCard); // confirm the list now contains all previous tasks plus the new task TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd); assertTrue(taskListPanel.isListMatching(expectedList)); } }
package us.kbase.common.utils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import us.kbase.auth.AuthToken; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CondorUtils { private static File createCondorSubmitFile(String ujsJobId, AuthToken token, AuthToken adminToken, String clientGroups, String kbaseEndpoint, String baseDir) throws IOException { String clientGroupsNew = clientGroupsToRequirements(clientGroups); kbaseEndpoint = cleanCondorInputs(kbaseEndpoint); String executable = "/kb/deployment/misc/sdklocalmethodrunner.sh"; String[] args = {ujsJobId, kbaseEndpoint}; String arguments = String.join(" ", args); List<String> csf = new ArrayList<String>(); csf.add("universe = vanilla"); csf.add(String.format("accounting_group = %s", token.getUserName())); csf.add("+Owner = \"condor_pool\""); csf.add("universe = vanilla"); csf.add("executable = " + executable); csf.add("ShouldTransferFiles = YES"); csf.add("when_to_transfer_output = ON_EXIT"); csf.add("request_cpus = 1"); csf.add("request_memory = 5MB"); csf.add("request_disk = 1MB"); csf.add("log = logfile.txt"); csf.add("output = outfile.txt"); csf.add("error = errors.txt"); csf.add("getenv = true"); csf.add("requirements = " + clientGroupsNew); csf.add(String.format("environment = \"KB_AUTH_TOKEN=%s KB_ADMIN_AUTH_TOKEN=%s AWE_CLIENTGROUP=%s BASE_DIR=%s\"", token.getToken(), adminToken.getToken(), clientGroups, baseDir)); csf.add("arguments = " + arguments); csf.add("batch_name = " + ujsJobId); csf.add("queue 1"); File submitFile = new File(String.format("%s.sub", ujsJobId)); FileUtils.writeLines(submitFile, "UTF-8", csf); submitFile.setExecutable(true); return submitFile; } public static CondorResponse runProcess(String[] condorCommand) throws IOException { /** * Run the condor command and return * @param condorCommand command to run * @return CondorResponse with STDIN and STDOUT */ //TODO DELETE PRINT STATEMENT System.out.println("Running command: [" + String.join(" ", condorCommand) + "]"); final Process process = Runtime.getRuntime().exec(condorCommand); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } List<String> stdOutMessage = IOUtils.readLines(process.getInputStream(), "UTF-8"); List<String> stdErrMessage = IOUtils.readLines(process.getErrorStream(), "UTF-8"); if (process.exitValue() != 0) { System.err.println("STDOUT:"); for (String s : stdOutMessage) { System.err.println(s); } System.out.println("STDERR:"); for (String s : stdOutMessage) { System.err.println(stdErrMessage); } return null; //throw new IOException("Error running condorCommand:" + String.join(" ", condorCommand)); } return new CondorResponse(stdOutMessage, stdErrMessage); } public static String clientGroupsToRequirements(String clientGroups) { /** * Remove spaces and maybe perform other logic * @param clientGroups to run the job with * @return String modified client groups */ //TODO REMOVE THIS OR UPDATE METHODS if (clientGroups.equals("ci")) { clientGroups = "njs"; } List<String> requirementsStatement = new ArrayList<String>(); for (String cg : clientGroups.split(",")) { cg = cleanCondorInputs(cg); requirementsStatement.add(String.format("(CLIENTGROUP == \"%s\")", cg)); } return "(" + String.join(" || ", requirementsStatement) + ")"; } public static String cleanCondorInputs(String input) { return input.replace(" ", "") .replace("'", "") .replace("\"", ""); } public static String submitToCondorCLI(String ujsJobId, AuthToken token, String clientGroups, String kbaseEndpoint, String baseDir, AuthToken adminToken) throws Exception { /** * Call condor_submit with the ujsJobId as batch job name * @param jobID ujsJobId to name the batch job with * @param token token to place into the shell script * @return String condor job id */ File condorSubmitFile = createCondorSubmitFile(ujsJobId, token, adminToken, clientGroups, kbaseEndpoint, baseDir); String[] cmdScript = {"condor_submit", "-spool", "-terse", condorSubmitFile.getAbsolutePath()}; String jobID = null; int retries = 10; while (jobID == null && retries > 0) { jobID = runProcess(cmdScript).stdout.get(0); retries } if (jobID == null) { throw new IOException("Error running condorCommand:" + String.join(" ", cmdScript)); } condorSubmitFile.delete(); return jobID; } public static String condorQ(String ujsJobId, String attribute) throws IOException, InterruptedException { /** * Call condor_q with the ujsJobId a string target to filter condor_q * @param jobID ujsJobId to get job JobPrio for * @param attribute attribute to search condorQ for * @return String condor job attribute or NULL */ int retries = 3; String result = null; String[] cmdScript = new String[]{"/kb/deployment/misc/condor_q.sh", ujsJobId, attribute}; while (result == null && retries > 0) { Thread.sleep(5000); result = String.join("\n", runProcess(cmdScript).stdout); // convert JSON string to Map There has to be a better way than this if (result.contains(attribute)) { try { ObjectMapper mapper = new ObjectMapper(); List<Map<String, Object>> myObjects = mapper.readValue(result, new TypeReference<List<Map<String, Object>>>() { }); result = myObjects.get(0).get(attribute).toString(); } catch (com.fasterxml.jackson.databind.JsonMappingException e) { result = null; } } else { result = null; } retries } return result; } public static String getJobState(String ujsJobId) throws Exception { /** * Get job state from condor_q with the LastJobStatus param * @param jobID ujsJobId to get job state for * @return String condor job state or NULL */ return condorQ(ujsJobId, "LastJobStatus"); } public static String getJobPriority(String ujsJobId) throws Exception { /** * Get job priority from condor_q with the JobPrio param * @param jobID ujsJobId to get job JobPrio for * @return String condor job priority or NULL */ return condorQ(ujsJobId, "JobPrio"); } public static String condorRemoveJobRange(String ujsJobID) throws Exception { /** * Remove condor jobs with a given batch name * @param jobID ujsJobId for the job batch name * @return Result of the condor_rm command */ String[] cmdScript = new String[]{"/kb/deployment/misc/condor_rm.sh", ujsJobID}; String processResult = runProcess(cmdScript).stdout.get(0); return processResult; //TODO : CALL NJS and CANCEL THE JOB } } // class CondorUtils
//Liangrui Lu //1366461 //This class shows the view of a certain item(expense) package com.example.traveltracker; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Itemview extends Activity{ private static final String FILENAME = "save.sav"; private Claimlist datafile; //private Item item; private TextView itemname; private String itemnamestr; private TextView itemdate; private String itemdatestr; private TextView itemcategory; private String itemcategorystr; private TextView itemamount; private String itemamountstr; private TextView itemunit; private String itemunitstr; private TextView itemdescription; private String itemdescriptionstr; //get information from datafile and put them on the text view @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.itemview); datafile = loadFromFile(); Intent intent = getIntent(); final int claimID = intent.getIntExtra("claimID", 0); final int itemID = intent.getIntExtra("itemID",0); itemnamestr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getItem().toString(); itemname= (TextView) findViewById(R.id.itemnameview); itemname.setText(itemnamestr); itemdatestr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getDate().toString(); itemdate= (TextView) findViewById(R.id.itemdateview); itemdate.setText(itemdatestr); itemcategorystr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getCategory().toString(); itemcategory= (TextView) findViewById(R.id.itemcategoryview); itemcategory.setText(itemcategorystr); itemunitstr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getUnit().toString(); itemunit= (TextView) findViewById(R.id.itemunitview); itemunit.setText(itemunitstr); itemamountstr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getAmount().toString(); itemamount= (TextView) findViewById(R.id.itemamountview); itemamount.setText(itemamountstr); itemdescriptionstr = datafile.getClaimlist().get(claimID).getItemlist().get(itemID).getDescription().toString(); itemdescription= (TextView) findViewById(R.id.itemdescriptionview); itemdescription.setText(itemdescriptionstr); //connect to edit item(expense) Button editclaim = (Button) findViewById(R.id.itemedit); editclaim.setOnClickListener(new View.OnClickListener() { public void onClick(View fa1) { Intent intent = new Intent(Itemview.this,Edititemactivity.class); intent.putExtra("claimID", claimID); intent.putExtra("itemID", itemID); startActivity(intent); } }); } //Load and save private Claimlist loadFromFile(){ Gson gson = new Gson(); datafile = new Claimlist(); try{ FileInputStream fis = openFileInput(FILENAME); InputStreamReader in = new InputStreamReader(fis); Type typeOfT = new TypeToken<Claimlist>(){}.getType(); datafile = gson.fromJson(in, typeOfT); fis.close(); } catch(FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return datafile; } private void saveInFile(){ Gson gson = new Gson(); try{ FileOutputStream fos = openFileOutput(FILENAME,0); OutputStreamWriter osw = new OutputStreamWriter(fos); gson.toJson(datafile,osw); osw.flush(); fos.close(); } catch(FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }
package hu.mentlerd.hybrid.asm; import hu.mentlerd.hybrid.CallFrame; import hu.mentlerd.hybrid.LuaTable; import hu.mentlerd.hybrid.asm.OverloadResolver.OverloadRule; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import static org.objectweb.asm.Opcodes.*; import static org.objectweb.asm.Type.*; public class CoercionAdapter extends GeneratorAdapter{ protected static final String TABLE = AsmHelper.getAsmName( LuaTable.class ); protected static final String FRAME = AsmHelper.getAsmName( CallFrame.class ); protected static final Type OBJ_BOOLEAN = Type.getType( Boolean.class ); protected static final Type OBJ_DOUBLE = Type.getType( Double.class ); protected static final Type OBJ_TABLE = Type.getType( LuaTable.class ); protected static final Type OBJ_OBJECT = Type.getType( Object.class ); protected static final Type EXCEPTION = Type.getType( IllegalArgumentException.class ); protected static Map<String, Type> numberCoercionMap = new HashMap<String, Type>(); static{ numberCoercionMap.put("java/lang/Byte", BYTE_TYPE); numberCoercionMap.put("java/lang/Short", SHORT_TYPE); numberCoercionMap.put("java/lang/Integer", INT_TYPE); numberCoercionMap.put("java/lang/Float", FLOAT_TYPE); numberCoercionMap.put("java/lang/Long", LONG_TYPE); } //This method is here for nested tables: [[I -> [I private static Type getEntryType( Type array ){ return Type.getType( array.getInternalName().substring(1) ); } /** * Tells if a null value can be coerced into the target class * * (Only returns true on non boxed objects, apart from Boolean, * that is evaluated like the Lua standard) * * @param into The target class * @return Whether it is possible to coerce a null value to the target class */ public static boolean canCoerceNull( Type into ){ if ( into.getSort() == Type.OBJECT ){ String clazz = into.getInternalName(); if ( numberCoercionMap.containsKey(clazz) ) return false; if ( clazz.equals(CHAR) ) return false; return true; } return false; } /** * Returns the type required to be on the stack to coerce it into the target type. * * @param type The target type * @return The type required on the stack */ public static Type getCoercedType( Type type ){ switch( type.getSort() ){ //Primitives case Type.BOOLEAN: return OBJ_BOOLEAN; //Java numbers are coerced from Double objects case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: case Type.FLOAT: case Type.LONG: case Type.DOUBLE: return OBJ_DOUBLE; case Type.OBJECT: String clazzName = type.getInternalName(); //Non primitive numbers object are coerced from Double objects if ( numberCoercionMap.containsKey(clazzName) ) return OBJ_DOUBLE; return type; //Arrays are coerced from LuaTables case Type.ARRAY: return OBJ_TABLE; default: throw new IllegalArgumentException(); } } /** * Tells whether the method passes is a valid @LuaMethod * * (Its return type is int, and only the last parameter is a CallFrame) * @param method * @return */ public static final boolean isMethodSpecial( Method method ){ if ( !method.isAnnotationPresent( LuaMethod.class ) || method.isVarArgs() ) return false; Type[] rTypes = Type.getArgumentTypes(method); Type rType = Type.getReturnType(method); //Check for integer return type if ( rType != Type.INT_TYPE ) return false; //Check for CallFrame parameter int params = rTypes.length; if ( params == 0 ) return false; Type last = rTypes[params -1]; if ( last.getSort() != Type.OBJECT || !last.getInternalName().equals(FRAME) ) return false; return true; } //Instance protected int frameArgIndex = -1; public CoercionAdapter(MethodVisitor mv, int access, String name, String desc) { super(mv, access, name, desc); } public CoercionAdapter(ClassVisitor cw, int access, String name, String desc){ super(cw.visitMethod(access, name, desc, null, null), access, name, desc); } //Utility public void push0(){ visitInsn(ICONST_0); } public void push1(){ visitInsn(ICONST_1); } private void visitIfValid(Label label) { if ( label != null ) visitLabel(label); } //Java calls public void callJava( Type clazz, Method method ){ boolean isStatic = AsmHelper.isStatic(method); boolean isSpecial = isMethodSpecial(method); boolean isVararg = method.isVarArgs(); int callType = INVOKESTATIC; String owner = clazz.getInternalName(); Type pTypes[] = Type.getArgumentTypes(method); //Non static calls require an instance, and INVOKEVIRTUAL if ( !isStatic ){ pushSelfArg(clazz); callType = INVOKEVIRTUAL; if ( AsmHelper.isInterfaceMethod(method) ) callType = INVOKEINTERFACE; } //Extract parameters to the stack int params = pTypes.length; int off = 1; if ( isVararg || isSpecial ) //Last parameter is handled differently params -= 1; if ( isStatic ) //No instance required for static methods off -= 1; //Extract parameters for ( int index = 0; index < params; index++ ) coerceFrameArg(index + off, pTypes[index]); //Extract varargs if ( isVararg ) coerceFrameVarargs(params, pTypes[params]); //Push the callframe if ( isSpecial ) loadArg(frameArgIndex); //Call visitMethodInsn(callType, owner, method.getName(), Type.getMethodDescriptor(method)); if ( isSpecial ) //Special methods manage returning themselves return; //Check if there are arguments to return Type rType = Type.getReturnType(method); if ( rType != Type.VOID_TYPE ) { varToLua(rType); //Coerce return, and push on CallFrame popToFrame(); push1(); } else { push0(); } } public void callOverload( Type clazz, List<Method> methods ){ List<OverloadRule> rules = OverloadResolver.resolve(methods); OverloadRule lastRule = rules.get( rules.size() -1 ); boolean isStatic = AsmHelper.isStatic( lastRule.method ); //Start processing rules, and storing variables int lastParamCount = -1; Label nextArgBranch = null; Label nextValueBranch = null; Label finish = new Label(); //Extract parameter count int argCount = newLocal(Type.INT_TYPE); //Extract frame.getArgCount pushFrameArgCount(); if ( !isStatic ){ push1(); math(SUB, INT_TYPE); } storeLocal(argCount); //Create branches based off rules for ( OverloadRule rule : rules ){ int paramCount = rule.paramCount; if ( lastParamCount != paramCount ){ //Argument count mismatch, new branch visitIfValid(nextArgBranch); nextArgBranch = new Label(); //Check argument count, on failure jump to next count check push(paramCount); loadLocal(argCount); ifICmp(LT, nextArgBranch); } if ( rule.paramType != null ){ //Check argument class visitIfValid(nextValueBranch); nextValueBranch = new Label(); pushFrameArg(rule.paramIndex + (isStatic ? 0 : 1), OBJ_OBJECT, true); //Check instance, if invalid jump to next type check instanceOf(getCoercedType(rule.paramType)); ifZCmp(IFEQ, nextValueBranch); } //Everything passed. Extract parameters from locals, and the frame callJava(clazz, rule.method); goTo(finish); //Prepare next rule lastParamCount = paramCount; } //Fail branch visitIfValid(nextArgBranch); visitIfValid(nextValueBranch); throwException(EXCEPTION, "Unable to resolve overloaded call"); //Finish visitLabel(finish); } //Frame access public void pushSelfArg( Type clazz ){ loadArg(frameArgIndex); push0(); //Fancy error messages push(clazz); push("self"); visitMethodInsn(INVOKEVIRTUAL, FRAME, "getNamedArg", "(ILjava/lang/Class;Ljava/lang/String;)Ljava/lang/Object;"); checkCast(clazz); } public void pushFrameArg( int index, Type type, boolean allowNull ){ loadArg(frameArgIndex); push(index); pushFrameArg(type, allowNull); } public void pushFrameArgCount(){ loadArg(frameArgIndex); visitMethodInsn(INVOKEVIRTUAL, FRAME, "getArgCount", "()I"); } public void popToFrame(){ loadArg(frameArgIndex); swap(); visitMethodInsn(INVOKEVIRTUAL, FRAME, "push", "(Ljava/lang/Object;)V"); } //Internals private void pushFrameArg( Type type, boolean allowNull ){ push(type); String method = allowNull ? "getArgNull" : "getArg"; visitMethodInsn(INVOKEVIRTUAL, FRAME, method, "(ILjava/lang/Class;)Ljava/lang/Object;"); } //Frame utils public void coerceFrameArg( int index, Type type ){ Type coerced = getCoercedType(type); //Pull the parameter on the stack pushFrameArg(index, coerced, canCoerceNull(type)); luaToVar(type); } public void coerceFrameVarargs( int from, Type arrayType ){ Type entry = getEntryType(arrayType); int array = newLocal(arrayType); int limit = newLocal(Type.INT_TYPE); int counter = newLocal(Type.INT_TYPE); /* * in frame * * limit = frame.getArgCount() - params * array = new array[limit] * * for ( int i = 0; i < limit; i++ ) * array[i] = coerceFrameArg( i + params, clazz ) * * push array */ Label loopBody = new Label(); Label loopEnd = new Label(); //Loop init pushFrameArgCount(); push(from); math(SUB, INT_TYPE); dup(); //frame.getArgCount() - params storeLocal(limit); newArray(entry); //new array[limit] storeLocal(array); push0(); storeLocal(counter); goTo(loopEnd); //Loop body visitLabel(loopBody); //Prepare array loadLocal(array); loadLocal(counter); //Pull argument from the stack loadArg(frameArgIndex); loadLocal(counter); push(from); math(ADD, INT_TYPE); pushFrameArg(getCoercedType(entry), canCoerceNull(entry)); //Store arrayStore(entry); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(limit); ifICmp(LT, loopBody); //'Return' loadLocal(array); } //Coercion public void luaToVar( Type type ){ switch( type.getSort() ){ case Type.BOOLEAN: case Type.DOUBLE: unbox(type); break; case Type.BYTE: case Type.SHORT: case Type.INT: unbox(INT_TYPE); cast(INT_TYPE, type); break; case Type.FLOAT: case Type.LONG: unbox(type); break; case Type.CHAR: unbox(INT_TYPE); //Double.intValue cast(INT_TYPE, CHAR_TYPE); //int -> char break; case Type.OBJECT: String clazz = type.getInternalName(); Type primitive = numberCoercionMap.get(clazz); if ( primitive != null ){ unbox(primitive); //Number.[int|double|float]Value valueOf(primitive); //[Int|Double|Float|...].valueOf } else if ( clazz.equals(CHAR) ){ unbox(INT_TYPE); cast(INT_TYPE, CHAR_TYPE); valueOf(CHAR_TYPE); } else { checkCast(type); } break; case Type.ARRAY: tableToArray(type); break; } } public void varToLua( Type type ){ switch( type.getSort() ){ case Type.BOOLEAN: case Type.DOUBLE: valueOf(type); break; case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: case Type.FLOAT: case Type.LONG: cast(type, DOUBLE_TYPE); valueOf(DOUBLE_TYPE); break; case Type.OBJECT: String clazz = type.getInternalName(); if ( numberCoercionMap.containsKey(clazz) ){ unbox(DOUBLE_TYPE); //Number.doubleValue valueOf(DOUBLE_TYPE); //Double.valueOf } if ( clazz.equals(CHAR) ){ unbox(CHAR_TYPE); //Character -> char varToLua(CHAR_TYPE); //char -> Double } break; case Type.ARRAY: arrayToTable(type); break; } } public void tableToArray( Type type ){ checkCast(OBJ_TABLE); int array = newLocal(type); int table = newLocal(OBJ_TABLE); int limit = newLocal(INT_TYPE); int counter = newLocal(INT_TYPE); Type entry = getEntryType(type); Type cast = getCoercedType(entry); if ( type.getDimensions() > 1 ) cast = OBJ_TABLE; //Nested arrays require a LuaTable to get coerced /* * in table * * limit = table.maxN() * array = array[limit] * * for ( int i = 0; i < limit; i++ ) * array[i] = luaToVar( table.rawget( i +1 ) ) * * return array */ Label loopBody = new Label(); Label loopEnd = new Label(); Label valid = new Label(); //Loop init dup(); storeLocal(table); visitMethodInsn(INVOKEVIRTUAL, TABLE, "maxN", "()I"); dup(); storeLocal(limit); newArray(entry); // new array[maxN()] storeLocal(array); push0(); storeLocal(counter); goTo(loopEnd); //Loop body visitLabel(loopBody); // array[i] = luaToVar( table.rawget( i +1 ) ) loadLocal(array); loadLocal(counter); loadLocal(table); loadLocal(counter); push(1); math(ADD, INT_TYPE); visitMethodInsn(INVOKEVIRTUAL, TABLE, "rawget", "(I)Ljava/lang/Object;"); //Check validity dup(); instanceOf(cast); ifZCmp(IFNE, valid); throwException(EXCEPTION, "Unable to coerce to array. Value could not be coerced to descriptor: " + entry ); visitLabel(valid); //Coerce, store luaToVar(entry); arrayStore(entry); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(limit); ifICmp(LT, loopBody); //'Return' loadLocal(array); } public void arrayToTable( Type type ){ int array = newLocal(type); int table = newLocal(OBJ_TABLE); int limit = newLocal(INT_TYPE); int counter = newLocal(INT_TYPE); Type entry = getEntryType(type); /* * in array * * table = new table * for ( int i = 0; i < array.length; i++ ) * table.rawset( i +1, varToLua( array[i] ) ) * * return table */ Label loopBody = new Label(); Label loopEnd = new Label(); //Loop init dup(); storeLocal(array); arrayLength(); storeLocal(limit); push0(); storeLocal(counter); newInstance(OBJ_TABLE); dup(); visitMethodInsn(INVOKESPECIAL, TABLE, "<init>", "()V"); storeLocal(table); goTo(loopEnd); //Loop body visitLabel(loopBody); // table.rawset( counter +1, varToLua( array[counter] ) ) loadLocal(table); loadLocal(counter); push1(); math(ADD, INT_TYPE); loadLocal(array); loadLocal(counter); arrayLoad(entry); varToLua(entry); visitMethodInsn(INVOKEVIRTUAL, TABLE, "rawset", "(ILjava/lang/Object;)V"); iinc(counter, 1); //Loop end visitLabel(loopEnd); loadLocal(counter); loadLocal(array); arrayLength(); ifICmp(LT, loopBody); //'Return' loadLocal(table); } }
import java.util.*; public class ArgumentTypes { public int handler_count = 41; /* Primitive types (8) */ public void byte1(byte i) { System.out.println(i); } public void short1(short i) { System.out.println(i); } public void integer1(int i) { System.out.println(i); } public void long1(long i) { System.out.println(i); } public void float1(float f) { System.out.println(f); } public void double1(double d) { System.out.println(d); } public void boolean1(boolean b) { if (b) System.out.println("Oh Yes!!"); else System.out.println("Oh No!!"); } public void char1(char c) { System.out.println(c); } /* java.lang types (10) */ public void byte2(Byte i) { System.out.println(i); } public void short2(Short i) { System.out.println(i); } public void integer2(Integer i) { System.out.println(i); } public void long2(Long i) { System.out.println(i); } public void float2(Float f) { System.out.println(f); } public void double2(Double d) { System.out.println(d); } public void boolean2(Boolean b) { if (b.booleanValue()) System.out.println("Oh Yes!!"); else System.out.println("Oh No!!"); } public void char2(Character c) { System.out.println(c); } public void string(String s) { System.out.println(s); } public void object(Object o) { try { System.out.println(o.toString()); } catch (NullPointerException n) { System.out.println("null"); } } /* Primitive arrays (8) */ public void byte1_array(byte[] ia) { for (int i=0; i<ia.length; i++) { this.byte1(ia[i]); } } public void short1_array(short[] ia) { for (int i=0; i<ia.length; i++) { this.short1(ia[i]); } } public void integer1_array(int[] ia) { for (int i=0; i<ia.length; i++) { this.integer1(ia[i]); } } public void long1_array(long[] ia) { for (int i=0; i<ia.length; i++) { this.long1(ia[i]); } } public void float1_array(float[] fa) { for (int i=0; i<fa.length; i++) { this.float1(fa[i]); } } public void double1_array(double[] da) { for (int i=0; i<da.length; i++) { this.double1(da[i]); } } public void boolean1_array(boolean[] ba) { for (int i=0; i<ba.length; i++) { this.boolean1(ba[i]); } } public void char1_array(char[] ca) { for (int i=0; i<ca.length; i++) { this.char1(ca[i]); } } /* java.lang arrays (10) */ public void byte2_array(Byte[] ia) { for (int i=0; i<ia.length; i++) { this.byte2(ia[i]); } } public void short2_array(Short[] ia) { for (int i=0; i<ia.length; i++) { this.short2(ia[i]); } } public void integer2_array(Integer[] ia) { for (int i=0; i<ia.length; i++) { this.integer2(ia[i]); } } public void long2_array(Long[] ia) { for (int i=0; i<ia.length; i++) { this.long2(ia[i]); } } public void float2_array(Float[] fa) { for (int i=0; i<fa.length; i++) { this.float2(fa[i]); } } public void double2_array(Double[] da) { for (int i=0; i<da.length; i++) { this.double2(da[i]); } } public void boolean2_array(Boolean[] ba) { for (int i=0; i<ba.length; i++) { this.boolean2(ba[i]); } } public void char2_array(Character[] ca) { for (int i=0; i<ca.length; i++) { this.char2(ca[i]); } } public void string_array(String[] sa) { for (int i=0; i<sa.length; i++) { this.string(sa[i]); } } public void object_array(Object[] oa) { for (int i=0; i<oa.length; i++) { this.object(oa[i]); } } /* Lists (5) - No element type cast on coercion! */ public void integer_list(List<Integer> il) { for (int i : il) { this.integer1(i); } } public void double_list(List<Double> dl) { for (double d : dl) { this.double1(d); } } public void boolean_list(List<Boolean> bl) { for (boolean b : bl) { this.boolean1(b); } } public void string_list(List<String> sl) { for (String s : sl) { this.string(s); } } public void object_list(List<Object> ol) { for (Object o : ol) { this.object(o); } } }
package org.xcolab.portlets.userprofile; import java.io.Serializable; import java.util.Date; import com.ext.portlet.NoSuchPlanItemException; import com.ext.portlet.model.PlanFan; import com.ext.portlet.model.PlanItem; import com.ext.portlet.service.PlanItemLocalServiceUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; public class SupportedPlanBean implements Serializable { private static final long serialVersionUID = 1L; private PlanFan supportedPlanInfo; private PlanItem supportedPlan; public SupportedPlanBean(PlanFan supportedPlanInfo) throws NoSuchPlanItemException, SystemException { this.supportedPlanInfo = supportedPlanInfo; supportedPlan = PlanItemLocalServiceUtil.getPlan(supportedPlanInfo.getPlanId()); } public String getPlanName() throws SystemException { return PlanItemLocalServiceUtil.getName(supportedPlan); } public Date getCreatedDate() { return supportedPlanInfo.getCreated(); } public Long getPlanId() { return supportedPlan.getPlanId(); } public Long getContestId() throws PortalException, SystemException { return PlanItemLocalServiceUtil.getContest(supportedPlan).getContestPK(); } }
package com.diamondq.common.reaction.engine; import com.diamondq.common.reaction.engine.definitions.JobDefinitionImpl; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; public class JobRequest { public final JobDefinitionImpl jobDefinition; public final @Nullable Object triggerObject; public final Map<String, String> variables; public JobRequest(JobDefinitionImpl pJobDefinition, @Nullable Object pTriggerObject) { this(pJobDefinition, pTriggerObject, Collections.emptyMap()); } public JobRequest(JobDefinitionImpl pJobDefinition, @Nullable Object pTriggerObject, Map<String, String> pVariableMap) { super(); jobDefinition = pJobDefinition; triggerObject = pTriggerObject; variables = ImmutableMap.copyOf(pVariableMap); } }
package com.ctrip.xpipe.redis.core.redis.operation.op; import com.ctrip.xpipe.api.codec.Codec; import com.ctrip.xpipe.redis.core.redis.operation.RedisOp; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.ctrip.xpipe.redis.core.protocal.RedisClientProtocol.ASTERISK_BYTE; import static com.ctrip.xpipe.redis.core.protocal.RedisClientProtocol.DOLLAR_BYTE; import static com.ctrip.xpipe.redis.core.protocal.RedisProtocol.CRLF; /** * @author lishanglin * date 2022/2/17 */ public abstract class AbstractRedisOp implements RedisOp { private String gtid; private Long timestamp; private String gid; private byte[][] rawArgs; public AbstractRedisOp() {} public AbstractRedisOp(byte[][] rawArgs) { this(rawArgs, null, null, null); } public AbstractRedisOp(byte[][] rawArgs, String gtid) { this(rawArgs, gtid, null, null); } public AbstractRedisOp(byte[][] rawArgs, String gid, Long timestamp) { this(rawArgs, null, gid, timestamp); } public AbstractRedisOp(byte[][] rawArgs, String gtid, String gid, Long timestamp) { this.rawArgs = rawArgs; this.gtid = gtid; this.gid = gid; this.timestamp = timestamp; } @Override public String getOpGtid() { return gtid; } @Override public Long getTimestamp() { return timestamp; } @Override public String getGid() { return gid; } @Override public byte[][] buildRawOpArgs() { return rawArgs; } @Override public ByteBuf buildRESP() { byte[][] args = buildRawOpArgs(); CompositeByteBuf outByteBuf = Unpooled.compositeBuffer(args.length + 1); String arrayLength = String.format("%c%d%s", ASTERISK_BYTE, args.length, CRLF); outByteBuf.addComponent(true, Unpooled.wrappedBuffer(arrayLength.getBytes())); for (byte[] arg: args) outByteBuf.addComponent(true, buildArgRESP(arg)); return outByteBuf; } protected ByteBuf buildArgRESP(byte[] arg) { String argLength = String.format("%c%d%s", DOLLAR_BYTE, arg.length, CRLF); return Unpooled.wrappedBuffer(argLength.getBytes(), arg, CRLF.getBytes()); } protected void setRawArgs(byte[][] args) { this.rawArgs = args; } @Override public String toString() { byte[][] args = buildRawOpArgs(); List<String> rawStrs = Stream.of(args).map(bytes -> new String(bytes, Codec.defaultCharset)).collect(Collectors.toList()); return String.join(" ", rawStrs); } }
package org.voovan.tools; import org.voovan.db.CallType; import org.voovan.db.DataBaseType; import org.voovan.db.JdbcOperate; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; import java.util.Map.Entry; import java.util.regex.Pattern; public class TSQL { /** * SQL , SQL * @param sqlStr sql (select * from table where x=::x and y=::y) * @return sql ([:x,:y]) */ public static List<String> getSqlParamNames(String sqlStr){ String[] params = TString.searchByRegex(sqlStr, "::\\w+\\b"); ArrayList<String> sqlParamNames = new ArrayList<String>(); for(String param : params){ sqlParamNames.add(param); } return sqlParamNames; } /** * preparedStatement sql (?) * @param sqlStr sql (select * from table where x=:x and y=::y) * @return :? (select * from table where x=? and y=?) */ public static String preparedSql(String sqlStr){ return TString.fastReplaceAll(sqlStr, "::\\w+\\b", "?"); } /** * preparedStatement * * @param preparedStatement preparedStatement * @param sqlParamNames sql * @param params Map * @throws SQLException SQL */ public static void setPreparedParams(PreparedStatement preparedStatement,List<String> sqlParamNames,Map<String, ?> params) throws SQLException{ for(int i=0;i<sqlParamNames.size();i++){ String paramName = sqlParamNames.get(i); paramName = paramName.substring(2,paramName.length()); Object data = params.get(paramName); if(data==null){ preparedStatement.setObject(i + 1, null); } else if(TReflect.isBasicType(data.getClass())) { preparedStatement.setObject(i + 1, params.get(paramName)); } else{ //,, JSON preparedStatement.setObject(i + 1, JSON.toJSON(params.get(paramName))); } } } /** * PreparedStatement * @param conn * @param sqlStr sql * @param params Map * @return PreparedStatement * @throws SQLException SQL */ public static PreparedStatement createPreparedStatement(Connection conn,String sqlStr,Map<String, Object> params) throws SQLException{ sqlStr = TSQL.removeEmptyCondiction(sqlStr, params); List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr); if(Logger.isLogLevel("DEBUG")) { Logger.fremawork("[SQL_Executed]: " + assembleSQLWithMap(sqlStr, params)); } //preparedStatement SQL String preparedSql = TSQL.preparedSql(sqlStr); PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(preparedSql); //params, if(params==null){ params = new Hashtable<String, Object>(); } //preparedStatement TSQL.setPreparedParams(preparedStatement, sqlParamNames, params); return preparedStatement; } /** * PreparedStatement * @param conn * @param sqlStr sql * @param params Map * @param callTypes * @return PreparedStatement * @throws SQLException SQL */ public static CallableStatement createCallableStatement(Connection conn,String sqlStr,Map<String, Object> params, CallType[] callTypes) throws SQLException{ Logger.fremawork("[SQL_Executed]: " + sqlStr); List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr); //preparedStatement SQL String preparedSql = TSQL.preparedSql(sqlStr); // jdbc statement CallableStatement callableStatement = (CallableStatement) conn.prepareCall(preparedSql); //params, if(params==null){ params = new Hashtable<String, Object>(); } //callableStatement TSQL.setPreparedParams(callableStatement,sqlParamNames,params); //, OUT ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData(); for(int i=0;i<parameterMetaData.getParameterCount();i++){ int paramMode = parameterMetaData.getParameterMode(i+1); if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut) { callableStatement.registerOutParameter(i + 1, parameterMetaData.getParameterType(i + 1)); } } return callableStatement; } /** * * @param callableStatement callableStatement * @return * @throws SQLException SQL */ public static List<Object> getCallableStatementResult(CallableStatement callableStatement) throws SQLException{ ArrayList<Object> result = new ArrayList<Object>(); ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData(); for(int i=0;i<parameterMetaData.getParameterCount();i++){ int paramMode = parameterMetaData.getParameterMode(i+1); // out , if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut){ String methodName = getDataMethod(parameterMetaData.getParameterType(i+1)); Object value; try { // int Method method = TReflect.findMethod(CallableStatement.class,methodName,new Class[]{int.class}); value = TReflect.invokeMethod(callableStatement, method,i+1); result.add(value); } catch (ReflectiveOperationException e) { e.printStackTrace(); } } } return result; } /** * SQL * @param sqlStr SQL * @param args * @return SQL */ public static String assembleSQLWithArray(String sqlStr,Object[] args){ // [, ] Map Map<String,Object> argMap = TObject.arrayToMap(args); return assembleSQLWithMap(sqlStr,argMap); } /** * argObjectjSQL * @param sqlStr SQL * @param argObjectj * @return SQL * @throws ReflectiveOperationException */ public static String assembleSQLWithObject(String sqlStr,Object argObjectj) throws ReflectiveOperationException{ // [-] Map Map<String,Object> argMap = TReflect.getMapfromObject(argObjectj); return assembleSQLWithMap(sqlStr,argMap); } /** * argMapKVSQL * SQL: * @param sqlStr SQL * @param argMap Map * @return */ public static String assembleSQLWithMap(String sqlStr,Map<String ,Object> argMap) { if(argMap!=null) { for (Entry<String, Object> arg : argMap.entrySet()) { sqlStr = TString.fastReplaceAll(sqlStr+" ", "::" + arg.getKey()+"\\b", getSQLString(argMap.get(arg.getKey()))+" "); } } return sqlStr.trim(); } /** * resultSetMap * @param resultset * @return Map * @throws SQLException SQL * @throws ReflectiveOperationException */ public static Map<String, Object> getOneRowWithMap(ResultSet resultset) throws SQLException, ReflectiveOperationException { HashMap<String, Object> resultMap = new HashMap<String,Object>(); HashMap<String,Integer> columns = new HashMap<String,Integer>(); int columnCount = resultset.getMetaData().getColumnCount(); for(int i=1;i<=columnCount;i++){ columns.put(resultset.getMetaData().getColumnLabel(i),resultset.getMetaData().getColumnType(i)); } //Map for(Entry<String, Integer> columnEntry : columns.entrySet()) { String methodName =getDataMethod(columnEntry.getValue()); Object value = TReflect.invokeMethod(resultset, methodName, columnEntry.getKey()); resultMap.put(columnEntry.getKey(), value); } return resultMap; } /** * resultSet * @param clazz * @param resultset * @return * @throws ReflectiveOperationException * @throws SQLException SQL * @throws ParseException */ public static Object getOneRowWithObject(Class<?> clazz,ResultSet resultset) throws SQLException, ReflectiveOperationException, ParseException { Map<String,Object>rowMap = getOneRowWithMap(resultset); return TReflect.getObjectFromMap(clazz, rowMap, true); } /** * resultSetList,Map * @param resultSet * @return List[Map] * @throws ReflectiveOperationException * @throws SQLException SQL */ public static List<Map<String,Object>> getAllRowWithMapList(ResultSet resultSet) throws SQLException, ReflectiveOperationException { List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>(); while(resultSet!=null && resultSet.next()){ resultList.add(getOneRowWithMap(resultSet)); } return resultList; } /** * resultSetList, * @param clazz * @param resultSet * @return * @throws ParseException * @throws ReflectiveOperationException * @throws SQLException SQL */ public static List<Object> getAllRowWithObjectList(Class<?> clazz,ResultSet resultSet) throws SQLException, ReflectiveOperationException, ParseException { List<Object> resultList = new ArrayList<Object>(); while(resultSet!=null && resultSet.next()){ resultList.add(getOneRowWithObject(clazz,resultSet)); } return resultList; } private static String EQUAL_CONDICTION = " 1=1"; private static String NOT_EQUAL_CONDICTION = " 1!=1"; /** * SQL , * @param sqlText SQL * @param params * @return */ public static String removeEmptyCondiction(String sqlText, Map<String, Object> params){ //params, if(params==null){ params = new Hashtable<String, Object>(); } List<String[]> condictionList = parseSQLCondiction(sqlText); for(String[] condictionArr : condictionList){ String orginCondiction = condictionArr[0]; String beforeCondictionMethod = condictionArr[1]; String condictionName = condictionArr[2]; String operatorChar = condictionArr[3]; String originCondictionParams = condictionArr[4]; String afterCondictionMethod = condictionArr[5]; String replaceCondiction = orginCondiction; String condictionParams = originCondictionParams; if(originCondictionParams!=null && originCondictionParams.contains("::")) { String[] condictions = TString.searchByRegex(originCondictionParams, "::\\w+\\b"); if(condictions.length > 0) { for (String condictionParam : condictions){ if (!params.containsKey(condictionParam.replace("::", ""))) { if(operatorChar.equals("in") || operatorChar.equals("not in")) { condictionParams = TString.fastReplaceAll(condictionParams, condictionParam+"\\s*,?", ""); } else { replaceCondiction = EQUAL_CONDICTION; if ("or".equals(beforeCondictionMethod) || "or".equals(afterCondictionMethod)) { replaceCondiction = NOT_EQUAL_CONDICTION; } String targetCondiction = condictionName + "\\s*" + operatorChar + "\\s*" + originCondictionParams; targetCondiction = targetCondiction.replaceAll("\\(", "\\\\("); targetCondiction = targetCondiction.replaceAll("\\)", "\\\\)"); targetCondiction = targetCondiction.replaceAll("\\[", "\\\\["); targetCondiction = targetCondiction.replaceAll("\\]", "\\\\]"); replaceCondiction = TString.fastReplaceAll(orginCondiction, targetCondiction , replaceCondiction); } } } //in not in , , if(operatorChar.equals("in") || operatorChar.equals("not in")) { condictionParams = condictionParams.trim(); if(condictionParams.endsWith(",")){ condictionParams = TString.removeSuffix(condictionParams); } replaceCondiction = TString.fastReplaceAll(replaceCondiction, originCondictionParams, condictionParams); } sqlText = sqlText.replace(orginCondiction, replaceCondiction); } } } return sqlText; } /** * SQL * @param sqlText SQL * @return SQL */ public static List<String[]> parseSQLCondiction(String sqlText) { ArrayList<String[]> condictionList = new ArrayList<String[]>(); String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\sand\\s)|(\\sor\\s)|(\\sgroup by\\s)|(\\sorder\\s)|(\\slimit\\s)|$)"; String[] sqlCondictions = TString.searchByRegex(sqlText,sqlRegx, Pattern.CASE_INSENSITIVE); for(int i=0;i<sqlCondictions.length;i++){ String condiction = sqlCondictions[i]; // ) , , 1=1) m2, gggg m3 if(TString.regexMatch(condiction, "\\(") < TString.regexMatch(condiction, "\\)") && TString.searchByRegex(condiction, "[\\\"`'].*?\\).*?[\\\"`']").length == 0) { int indexClosePair = condiction.lastIndexOf(")"); if (indexClosePair != -1) { condiction = condiction.substring(0, indexClosePair + 1); } } //between if(TString.regexMatch(condiction,"\\sbetween\\s")>0){ i = i+1; condiction = condiction + sqlCondictions[i]; } String originCondiction = condiction; condiction = condiction.trim(); String concateMethod = condiction.substring(0,condiction.indexOf(" ")+1).trim(); condiction = condiction.substring(condiction.indexOf(" ")+1,condiction.length()).trim(); String[] splitedCondicction = TString.searchByRegex(condiction, "(\\sbetween\\s+)|(\\sis\\s+)|(\\slike\\s+)|(\\s(not\\s)?in\\s+)|(\\!=)|(>=)|(<=)|[=<>]"); if(splitedCondicction.length == 1) { String operatorChar = splitedCondicction[0].trim(); String[] condictionArr = condiction.split("(\\sbetween\\s+)|(\\sis\\s+)|(\\slike\\s+)|(\\s(not\\s)?in\\s+)|(\\!=)|(>=)|(<=)|[=<>]"); condictionArr[0] = condictionArr[0].trim(); if(condictionArr[0].startsWith("(")){ condictionArr[0] = TString.removePrefix(condictionArr[0]); } condictionArr[1] = condictionArr[1].trim(); if(condictionArr.length>1){ if((condictionArr[1].trim().startsWith("'") && condictionArr[1].trim().endsWith("'")) || (condictionArr[1].trim().startsWith("\"") && condictionArr[1].trim().endsWith("\""))|| (condictionArr[1].trim().startsWith("`") && condictionArr[1].trim().endsWith("`"))|| (condictionArr[1].trim().startsWith("(") && condictionArr[1].trim().endsWith(")")) ){ condictionArr[1] = condictionArr[1].substring(1,condictionArr[1].length()-1); } if(operatorChar.contains("in")){ condictionArr[1] = condictionArr[1].replace("'", ""); } if(condictionArr[0].startsWith("(") && TString.regexMatch(condictionArr[1], "\\(") > TString.regexMatch(condictionArr[1], "\\)")){ condictionArr[0] = TString.removePrefix(condictionArr[0]); } if(condictionArr[1].endsWith(")") && TString.regexMatch(condictionArr[1], "\\(") < TString.regexMatch(condictionArr[1], "\\)")){ condictionArr[1] = TString.removeSuffix(condictionArr[1]); } condictionList.add(new String[]{originCondiction.trim(), concateMethod, condictionArr[0].trim(), operatorChar, condictionArr[1].trim(), null}); }else{ Logger.error("Parse SQL condiction error"); } } else { condictionList.add(new String[]{originCondiction, null, null, null, null, null}); } } for(int i=condictionList.size()-2; i>=0; i condictionList.get(i)[5] = condictionList.get(i+1)[1]; } return condictionList; } /** * SQL, JAVA SQL * :String 'chs' * @param argObj * @return */ public static String getSQLString(Object argObj) { if(argObj==null){ return "null"; } if(argObj instanceof List) { Object[] objects =((List<?>)argObj).toArray(); StringBuilder listValueStr= new StringBuilder("("); for(Object obj : objects) { String sqlValue = getSQLString(obj); if(sqlValue!=null) { listValueStr.append(sqlValue); listValueStr.append(","); } } return TString.removeSuffix(listValueStr.toString())+")"; } //String else if(argObj instanceof String){ return "\'"+argObj.toString()+"\'"; } //Boolean else if(argObj instanceof Boolean){ if((Boolean)argObj) return "true"; else return "false"; } //Date else if(argObj instanceof Date){ SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE); return "'"+dateFormat.format(argObj)+"'"; } //String else { return argObj.toString(); } } /** * SQL Result * @param databaseType * @return */ public static String getDataMethod(int databaseType){ switch(databaseType){ case Types.CHAR : return "getString"; case Types.VARCHAR : return "getString"; case Types.LONGVARCHAR : return "getString"; case Types.NCHAR : return "getString"; case Types.LONGNVARCHAR : return "getString"; case Types.NUMERIC : return "getBigDecimal"; case Types.DECIMAL : return "getBigDecimal"; case Types.BIT : return "getBoolean"; case Types.BOOLEAN : return "getBoolean"; case Types.TINYINT : return "getByte"; case Types.SMALLINT : return "getShort"; case Types.INTEGER : return "getInt"; case Types.BIGINT : return "getLong"; case Types.REAL : return "getFloat"; case Types.FLOAT : return "getFloat"; case Types.DOUBLE : return "getDouble"; case Types.BINARY : return "getBytes"; case Types.VARBINARY : return "getBytes"; case Types.LONGVARBINARY : return "getBytes"; case Types.DATE : return "getDate"; case Types.TIME : return "getTime"; case Types.TIMESTAMP : return "getTimestamp"; case Types.CLOB : return "getClob"; case Types.BLOB : return "getBlob"; case Types.ARRAY : return "getArray"; default: return "getString"; } } /** * JAVA SQL * @param obj * @return */ public static int getSqlTypes(Object obj){ Class<?> objectClass = obj.getClass(); if(char.class == objectClass){ return Types.CHAR; }else if(String.class == objectClass){ return Types.VARCHAR ; }else if(BigDecimal.class == objectClass){ return Types.NUMERIC; }else if(Boolean.class == objectClass){ return Types.BIT; }else if(Byte.class == objectClass){ return Types.TINYINT; }else if(Short.class == objectClass){ return Types.SMALLINT; }else if(Integer.class == objectClass){ return Types.INTEGER; }else if(Long.class == objectClass){ return Types.BIGINT; }else if(Float.class == objectClass){ return Types.FLOAT; }else if(Double.class == objectClass){ return Types.DOUBLE; }else if(Byte[].class == objectClass){ return Types.BINARY; }else if(Date.class == objectClass){ return Types.DATE; }else if(Time.class == objectClass){ return Types.TIME; }else if(Timestamp.class == objectClass){ return Types.TIMESTAMP; }else if(Clob.class == objectClass){ return Types.CLOB; }else if(Blob.class == objectClass){ return Types.BLOB; }else if(Object[].class == objectClass){ return Types.ARRAY; } return 0; } /** * * * @param connection * @return */ public static DataBaseType getDataBaseType(Connection connection) { try { //driverName if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MYSQL") != -1) { return DataBaseType.MySql; } if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MARIADB") != -1) { return DataBaseType.Mariadb; } else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("POSTAGE") != -1) { return DataBaseType.Postage; } else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("ORACLE") != -1) { return DataBaseType.Oracle; } return DataBaseType.UNKNOW; } catch (SQLException e) { return DataBaseType.UNKNOW; } } /** * SQL * @param jdbcOperate jdbcOperate * @param sqlField sql * @return sql */ public static String wrapSqlField(JdbcOperate jdbcOperate, String sqlField){ try { Connection connection = jdbcOperate.getConnection(); DataBaseType dataBaseType = TSQL.getDataBaseType(connection); if (dataBaseType.equals(DataBaseType.Mariadb) || dataBaseType.equals(DataBaseType.MySql)) { return "`"+sqlField+"`"; } else if (dataBaseType.equals(DataBaseType.Oracle)) { return "\""+sqlField+"\""; } else if (dataBaseType.equals(DataBaseType.Postage)) { return "`"+sqlField+"`"; } else { return sqlField; } } catch (SQLException e) { Logger.error("wrap sql field error", e); return sqlField; } } /** * Mysql sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genMysqlPageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; if(pageSize<0 || pageNumber<0) { return sql; } return sql + " limit " + pageStart + ", " + pageSize; } /** * Postage sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genPostagePageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; if(pageSize<0 || pageNumber<0) { return sql; } return sql + " limit " + pageSize + " offset " + pageStart; } /** * Oracle sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genOraclePageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; int pageEnd = pageStart + pageSize; if(pageSize<0 || pageNumber<0) { return sql; } sql = sql.replaceFirst("select", "select rownum rn,"); sql = "select pageSql.* from (" + sql + " ) pageSql where rn between " + pageStart + " and " + pageEnd; return sql; } }
package org.fusesource.restygwt.rebind; import java.beans.Introspector; import java.util.Collection; import java.util.List; import junit.framework.TestCase; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import org.fusesource.restygwt.rebind.JsonEncoderDecoderClassCreator.Subtype; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JClassType; import static org.fusesource.restygwt.rebind.JsonEncoderDecoderClassCreator.getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance; @RunWith(JUnit4.class) public class JsonEncoderDecoderClassCreatorTestCase extends TestCase { @Rule public ExpectedException exception = ExpectedException.none(); private static class MyPossibleTypesVisitor extends PossibleTypesVisitor { boolean hasEnteredGetPossibleTypesForClass; boolean hasEnteredGetPossibleTypesForOther; public MyPossibleTypesVisitor(GeneratorContext context, JClassType classType, boolean isLeaf, TreeLogger logger, Collection<JsonSubTypes.Type> types) { super(context, classType, isLeaf, logger, types); } @Override protected List<Subtype> getPossibleTypesForClass(GeneratorContext context, JClassType classType, Id id, boolean isLeaf, TreeLogger logger, Collection<JsonSubTypes.Type> types) throws UnableToCompleteException { hasEnteredGetPossibleTypesForClass = true; return null; } @Override protected List<Subtype> getPossibleTypesForOther(GeneratorContext context, JClassType classType, boolean isLeaf, TreeLogger logger, Collection<JsonSubTypes.Type> types) throws UnableToCompleteException { hasEnteredGetPossibleTypesForOther = true; return null; } } @Test public void testGetPossibleTypesForClass() throws Throwable { check(Id.CLASS, true, false); check(Id.MINIMAL_CLASS, true, false); check(Id.CUSTOM, false, true); check(Id.NAME, false, true); } @Test(expected=UnableToCompleteException.class) public void testGetPossibleTypesForClass2() throws Throwable { check(Id.NONE, false, true); } private void check(final Id id, final boolean classMethodVisited, final boolean otherMethodVisited) throws Throwable { MyPossibleTypesVisitor v = new MyPossibleTypesVisitor(null, null, true, new TreeLogger(){ @Override public void log(Type type, String msg, Throwable caught, HelpInfo helpInfo){ } @Override public boolean isLoggable(Type type){ return false; } @Override public TreeLogger branch(Type type, String msg, Throwable caught, HelpInfo helpInfo){ return null; } }, null); v.visit(id); assertEquals(v.hasEnteredGetPossibleTypesForClass, classMethodVisited); assertEquals(v.hasEnteredGetPossibleTypesForOther, otherMethodVisited); } @Test public void testNamingConventions() { String name = "a"; assertEquals("A", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); name = "foo"; assertEquals("Foo", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); name = "URL"; assertEquals("URL", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); name = "xValue"; assertEquals("xValue", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); name = "myValue"; assertEquals("MyValue", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); name = "MYTestValue"; assertEquals("MYTestValue", getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name)); assertEquals(name, Introspector.decapitalize(getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(name))); } }
package mx.udlap.settheory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class SetTheoryOperations { public static List<String> Union (List<List<String>> param) { //didn't use List.addall to prevent repeated values, something that doesn't happen in sets List<String> toReturn=new ArrayList<String>(); HashSet<String> hs=new HashSet<String>(); for (List<String> set : param) { hs.addAll(set); /*for(String value : set) { if(!toReturn.contains(value)) { toReturn.add(value); } }*/ } toReturn.addAll(hs); return toReturn; } public static List<String> Diference (List<String> minuend, List<String> subtrahend ) { minuend.removeAll(subtrahend); return minuend; } public static List<String> Intersection (List<List<String>> param) { List<String> toReturn=new ArrayList<String>(); toReturn.addAll(param.get(0)); // adds initial values to the result set for (List<String> set : param) { toReturn.retainAll(set); } return toReturn; } public static List<String> Complement (List<String> universe, List<String> a) { return SetTheoryOperations.Diference(universe, a); } }
package org.sagebionetworks.repo.web.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.search.SearchConstants.FIELD_ID; import static org.sagebionetworks.search.SearchConstants.FIELD_PATH; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.search.SearchDocumentDriver; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.search.Hit; import org.sagebionetworks.repo.model.search.SearchResults; import org.sagebionetworks.repo.model.search.query.KeyValue; import org.sagebionetworks.repo.model.search.query.SearchQuery; import org.sagebionetworks.search.SearchDao; /** * Test for SearchServiceImpl * @author John * */ public class SearchServiceImplTest { private SearchDao mockSearchDao; private UserManager mockUserManager; private SearchDocumentDriver mockSearchDocumentDriver; private SearchServiceImpl service; private UserInfo userInfo; private String searchQuery; @Before public void before(){ mockSearchDao = Mockito.mock(SearchDao.class); mockUserManager = Mockito.mock(UserManager.class); mockSearchDocumentDriver = Mockito.mock(SearchDocumentDriver.class); service= new SearchServiceImpl(mockSearchDao, mockUserManager, mockSearchDocumentDriver); userInfo = new UserInfo(false, 990L); searchQuery = "q.parser=structured&q=(and 'RIP' 'Harambe')&return=id,freeze,mage,fun&interactive=deck"; Set<Long> userGroups = new HashSet<Long>(); userGroups.add(123L); userGroups.add(8008135L); userInfo.setGroups(userGroups); } @Test public void testProxySearchPath() throws Exception { // Prepare mock results SearchResults sample = new SearchResults(); sample.setHits(new LinkedList<Hit>()); Hit hit = new Hit(); hit.setId("syn123"); sample.getHits().add(hit); when(mockSearchDao.executeSearch(any(String.class))).thenReturn(sample); // make sure the path is returned from the document driver when(mockSearchDocumentDriver.getEntityPath("syn123")).thenReturn(new EntityPath()); SearchQuery query = new SearchQuery(); query.setBooleanQuery(new LinkedList<KeyValue>()); KeyValue kv = new KeyValue(); kv.setKey(FIELD_ID); kv.setValue("syn123"); query.getBooleanQuery().add(kv); // Setup the expected query String serchQueryString = service.createQueryString(userInfo, query); // Path should not get passed along to the search index as it is not there anymore. query.setReturnFields(new LinkedList<String>()); query.getReturnFields().add(FIELD_PATH); // Make the call SearchResults results = service.proxySearch(userInfo, query); assertNotNull(results); assertNotNull(results.getHits()); assertNotNull(results.getHits().size() == 1); Hit returnedHit = results.getHits().get(0); // Path should get filled in since we asked for it. assertNotNull(returnedHit.getPath()); // Validate that path was not passed along to the search index as it is not there. verify(mockSearchDao, times(1)).executeSearch(serchQueryString); } @Test public void testProxySearchNoPath() throws Exception { // Prepare mock results SearchResults sample = new SearchResults(); sample.setHits(new LinkedList<Hit>()); Hit hit = new Hit(); hit.setId("syn123"); sample.getHits().add(hit); when(mockSearchDao.executeSearch(any(String.class))).thenReturn(sample); SearchQuery query = new SearchQuery(); query.setBooleanQuery(new LinkedList<KeyValue>()); KeyValue kv = new KeyValue(); kv.setKey(FIELD_ID); kv.setValue("syn123"); query.getBooleanQuery().add(kv); // Setup the expected query String serchQueryString = service.createQueryString(userInfo, query); // Make the call SearchResults results = service.proxySearch(userInfo, query); assertNotNull(results); assertNotNull(results.getHits()); assertNotNull(results.getHits().size() == 1); Hit returnedHit = results.getHits().get(0); // The path should not be returned unless requested. assertNull(returnedHit.getPath()); verify(mockSearchDao, times(1)).executeSearch(serchQueryString); } @Test(expected = IllegalArgumentException.class) public void testFilterSeachForAuthorizationUserIsNull(){ SearchServiceImpl.filterSeachForAuthorization(null, searchQuery); } @Test public void testFilterSeachForAuthorizationUserIsAdmin(){ UserInfo adminUser = new UserInfo(true, 420L); assertEquals(searchQuery, SearchServiceImpl.filterSeachForAuthorization(adminUser, searchQuery)); } @Test public void testFilterSearchForAuthorizationUserIsNotAdmin(){ assertEquals("q.parser=structured&q=( and (and 'RIP' 'Harambe') (or acl:'8008135' acl:'123'))&return=id,freeze,mage,fun&interactive=deck" , SearchServiceImpl.filterSeachForAuthorization(userInfo, searchQuery)); } @Test public void testFilterSearchForAuthorizationUserIsNotAdminNoOtherParameters(){ searchQuery = "q.parser=structured&q=(and 'ayy' 'lmao' 'XD')"; assertEquals("q.parser=structured&q=( and (and 'ayy' 'lmao' 'XD') (or acl:'8008135' acl:'123'))", SearchServiceImpl.filterSeachForAuthorization(userInfo, searchQuery)); } }
package solutions.digamma.damas.rs.content; import solutions.digamma.damas.common.WorkspaceException; import solutions.digamma.damas.content.Document; import solutions.digamma.damas.content.DocumentManager; import solutions.digamma.damas.rs.common.Authenticated; import solutions.digamma.damas.rs.common.CrudResource; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.InputStream; import java.util.Optional; /** * Document REST endpoint. * * @label Document * @author Ahmad Shahwan */ @Path("documents") public class DocumentResource extends CrudResource<Document, DocumentSerialization> { @Inject protected DocumentManager manager; /** * Provide detailed description of folder. */ @QueryParam("full") private boolean full; @Override protected DocumentManager getManager() { return this.manager; } /** * Upload content of an existing document, erase the old content if any. * * @param id document ID * @param content content's input stream * @throws WorkspaceException */ @PUT @Path("/{id}/upload") @Authenticated public void upload( @PathParam("id") String id, InputStream content) throws WorkspaceException { this.manager.upload(id, content); } @GET @Path("/{id}/download") @Authenticated public Response download( @PathParam("id") String id, InputStream content) throws WorkspaceException { Document document = this.manager.retrieve(id); InputStream is = this.manager.download(id).getStream(); String type = Optional.ofNullable(document.getMimeType()) .orElse(MediaType.APPLICATION_OCTET_STREAM); return Response.ok(is, type).build(); } @Override protected DocumentSerialization wrap(Document entity) { return DocumentSerialization.from(entity, this.full); } }
package com.jetbrains.python.documentation; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.LineTokenizer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyCallExpressionHelper; import com.jetbrains.python.psi.resolve.QualifiedResolveResult; import com.jetbrains.python.psi.resolve.ResolveImportUtil; import com.jetbrains.python.psi.resolve.RootVisitor; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.toolbox.ChainIterable; import com.jetbrains.python.toolbox.Maybe; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.jetbrains.python.documentation.DocumentationBuilderKit.*; import static com.jetbrains.python.documentation.DocumentationBuilderKit.combUp; class DocumentationBuilder { private final PsiElement myElement; private final PsiElement myOriginalElement; private ChainIterable<String> myResult; private ChainIterable<String> myProlog; // sequence for reassignment info, etc private ChainIterable<String> myBody; // sequence for doc string private ChainIterable<String> myEpilog; // sequence for doc "copied from" notices and such private static final Pattern ourSpacesPattern = Pattern.compile("^\\s+"); public DocumentationBuilder(PsiElement element, PsiElement originalElement) { myElement = element; myOriginalElement = originalElement; myResult = new ChainIterable<String>(); myProlog = new ChainIterable<String>(); myBody = new ChainIterable<String>(); myEpilog = new ChainIterable<String>(); myResult.add(myProlog).addWith(TagCode, myBody).add(myEpilog); // pre-assemble; then add stuff to individual cats as needed myResult = wrapInTag("html", wrapInTag("body", myResult)); } public String build() { final ChainIterable<String> reassign_cat = new ChainIterable<String>(); // sequence for reassignment info, etc PsiElement followed = resolveToDocStringOwner(reassign_cat); // check if we got a property ref. // if so, element is an accessor, and originalElement if an identifier // TODO: use messages from resources! PyClass cls; PsiElement outer = null; boolean is_property = false; String accessor_kind = "None"; if (myOriginalElement != null) { String element_name = myOriginalElement.getText(); if (PyUtil.isPythonIdentifier(element_name)) { outer = myOriginalElement.getParent(); if (outer instanceof PyQualifiedExpression) { PyExpression qual = ((PyQualifiedExpression)outer).getQualifier(); if (qual != null) { PyType type = qual.getType(TypeEvalContext.fast()); if (type instanceof PyClassType) { cls = ((PyClassType)type).getPyClass(); if (cls != null) { Property property = cls.findProperty(element_name); if (property != null) { is_property = true; final AccessDirection dir = AccessDirection.of((PyElement)outer); Maybe<PyFunction> accessor = property.getByDirection(dir); myProlog .add("property ").addWith(TagBold, $().addWith(TagCode, $(element_name))) .add(" of ").add(PythonDocumentationProvider.describeClass(cls, TagCode, true, true)) ; if (accessor.isDefined() && property.getDoc() != null) { myBody.add(": ").add(property.getDoc()).add(BR); } else { final PyFunction getter = property.getGetter().valueOrNull(); if (getter != null && getter != myElement) { // not in getter, getter's doc comment may be useful PyStringLiteralExpression docstring = getter.getDocStringExpression(); if (docstring != null) { myProlog .add(BR).addWith(TagItalic, $("Copied from getter:")).add(BR) .add(docstring.getStringValue()) ; } } myBody.add(BR); } myBody.add(BR); if (accessor.isDefined() && accessor.value() == null) followed = null; if (dir == AccessDirection.READ) accessor_kind = "Getter"; else if (dir == AccessDirection.WRITE) accessor_kind = "Setter"; else accessor_kind = "Deleter"; if (followed != null) myEpilog.addWith(TagSmall, $(BR, BR, accessor_kind, " of property")).add(BR); } } } } } } } if (myProlog.isEmpty() && ! is_property) myProlog.add(reassign_cat); // now followed may contain a doc string if (followed instanceof PyDocStringOwner) { String docString = null; PyStringLiteralExpression doc_expr = ((PyDocStringOwner) followed).getDocStringExpression(); if (doc_expr != null) docString = doc_expr.getStringValue(); // doc of what? if (followed instanceof PyClass) { cls = (PyClass)followed; myBody.add(PythonDocumentationProvider.describeDecorators(cls, TagItalic, BR, LCombUp)); myBody.add(PythonDocumentationProvider.describeClass(cls, TagBold, true, false)); } else if (followed instanceof PyFunction) { PyFunction fun = (PyFunction)followed; if (! is_property) { cls = fun.getContainingClass(); if (cls != null) { myBody.addWith(TagSmall, PythonDocumentationProvider.describeClass(cls, TagCode, true, true)).add(BR).add(BR); } } else cls = null; myBody .add(PythonDocumentationProvider.describeDecorators(fun, TagItalic, BR, LCombUp)) .add(PythonDocumentationProvider.describeFunction(fun, TagBold, LCombUp)); if (docString == null) { addInheritedDocString(fun, cls); } } else if (followed instanceof PyFile) { addModulePath((PyFile) followed); } if (docString != null) { myBody.add(BR); addFormattedDocString(myElement, docString, myBody, myEpilog); } } else if (is_property) { // if it was a normal accessor, ti would be a function, handled by previous branch String accessor_message; if (followed != null) accessor_message = "Declaration: "; else accessor_message = accessor_kind + " is not defined."; myBody.addWith(TagItalic, $(accessor_message)).add(BR); if (followed != null) myBody.add(combUp(PyUtil.getReadableRepr(followed, false))); } else if (followed != null && outer instanceof PyReferenceExpression) { Class[] uninteresting_classes = {PyTargetExpression.class, PyAugAssignmentStatement.class}; boolean is_interesting = myElement != null && ! PyUtil.instanceOf(myElement, uninteresting_classes); if (is_interesting) { PsiElement old_parent = myElement.getParent(); is_interesting = ! PyUtil.instanceOf(old_parent, uninteresting_classes); } if (is_interesting) { myBody.add(combUp(PyUtil.getReadableRepr(followed, false))); } } if (followed instanceof PyNamedParameter) { addParameterDoc((PyNamedParameter) followed); } if (myBody.isEmpty() && myEpilog.isEmpty()) return null; // got nothing substantial to say! else return myResult.toString(); } @Nullable private PsiElement resolveToDocStringOwner(ChainIterable<String> prolog_cat) { // here the ^Q target is already resolved; the resolved element may point to intermediate assignments if (myElement instanceof PyTargetExpression) { final String target_name = myElement.getText(); //prolog_cat.add(TagSmall.apply($("Assigned to ", element.getText(), BR))); prolog_cat.addWith(TagSmall, $(PyBundle.message("QDOC.assigned.to.$0", target_name)).add(BR)); return ((PyTargetExpression)myElement).findAssignedValue(); } if (myElement instanceof PyReferenceExpression) { //prolog_cat.add(TagSmall.apply($("Assigned to ", element.getText(), BR))); prolog_cat.addWith(TagSmall, $(PyBundle.message("QDOC.assigned.to.$0", myElement.getText())).add(BR)); final QualifiedResolveResult resolveResult = ((PyReferenceExpression)myElement).followAssignmentsChain(TypeEvalContext.fast()); return resolveResult.isImplicit() ? null : resolveResult.getElement(); } // it may be a call to a standard wrapper if (myElement instanceof PyCallExpression) { final PyCallExpression call = (PyCallExpression)myElement; Pair<String, PyFunction> wrap_info = PyCallExpressionHelper.interpretAsStaticmethodOrClassmethodWrappingCall(call, myOriginalElement); if (wrap_info != null) { String wrapper_name = wrap_info.getFirst(); PyFunction wrapped_func = wrap_info.getSecond(); //prolog_cat.addWith(TagSmall, $("Wrapped in ").addWith(TagCode, $(wrapper_name)).add(BR)); prolog_cat.addWith(TagSmall, $(PyBundle.message("QDOC.wrapped.in.$0", wrapper_name)).add(BR)); return wrapped_func; } } return myElement; } private void addInheritedDocString(PyFunction fun, PyClass cls) { boolean not_found = true; String meth_name = fun.getName(); if (cls != null && meth_name != null) { final boolean is_constructor = PyNames.INIT.equals(meth_name); // look for inherited and its doc Iterable<PyClass> classes = cls.iterateAncestorClasses(); if (is_constructor) { // look at our own class again and maybe inherit class's doc classes = new ChainIterable<PyClass>(cls).add(classes); } for (PyClass ancestor : classes) { PyStringLiteralExpression doc_elt = null; PyFunction inherited = null; boolean is_from_class = false; if (is_constructor) doc_elt = cls.getDocStringExpression(); if (doc_elt != null) is_from_class = true; else inherited = ancestor.findMethodByName(meth_name, false); if (inherited != null) { doc_elt = inherited.getDocStringExpression(); } if (doc_elt != null) { String inherited_doc = doc_elt.getStringValue(); if (inherited_doc.length() > 1) { myEpilog.add(BR).add(BR); String ancestor_name = ancestor.getName(); String marker = (cls == ancestor)? PythonDocumentationProvider.LINK_TYPE_CLASS : PythonDocumentationProvider.LINK_TYPE_PARENT; final String ancestor_link = $().addWith(new DocumentationBuilderKit.LinkWrapper(marker + ancestor_name), $(ancestor_name)).toString(); if (is_from_class) myEpilog.add(PyBundle.message("QDOC.copied.from.class.$0", ancestor_link)); else { myEpilog.add(PyBundle.message("QDOC.copied.from.$0.$1", ancestor_link, meth_name)); } myEpilog.add(BR).add(BR); ChainIterable<String> formatted = new ChainIterable<String>(); ChainIterable<String> unformatted = new ChainIterable<String>(); addFormattedDocString(fun, inherited_doc, formatted, unformatted); myEpilog.addWith(TagCode, formatted).add(unformatted); not_found = false; break; } } } if (not_found) { // above could have not worked because inheritance is not searched down to 'object'. // for well-known methods, copy built-in doc string. // TODO: also handle predefined __xxx__ that are not part of 'object'. if (PyNames.UnderscoredAttributes.contains(meth_name)) { addPredefinedMethodDoc(fun, meth_name); } } } } private void addPredefinedMethodDoc(PyFunction fun, String meth_name) { PyClassType objtype = PyBuiltinCache.getInstance(fun).getObjectType(); // old- and new-style classes share the __xxx__ stuff if (objtype != null) { PyClass objcls = objtype.getPyClass(); if (objcls != null) { PyFunction obj_underscored = objcls.findMethodByName(meth_name, false); if (obj_underscored != null) { PyStringLiteralExpression predefined_doc_expr = obj_underscored.getDocStringExpression(); String predefined_doc = predefined_doc_expr != null? predefined_doc_expr.getStringValue() : null; if (predefined_doc != null && predefined_doc.length() > 1) { // only a real-looking doc string counts addFormattedDocString(fun, predefined_doc, myBody, myBody); myEpilog.add(BR).add(BR).add(PyBundle.message("QDOC.copied.from.builtin")); } } } } } private static void addFormattedDocString(PsiElement element, @NotNull String docstring, ChainIterable<String> formattedOutput, ChainIterable<String> unformattedOutput) { Project project = element.getProject(); PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(project); List<String> result = new ArrayList<String>(); if (documentationSettings.isEpydocFormat(element.getContainingFile())) { final EpydocString epydocString = new EpydocString(docstring); Module module = ModuleUtil.findModuleForPsiElement(element); String formatted = null; if (module != null) { formatted = EpydocRunner.formatDocstring(module, docstring); } if (formatted == null) { formatted = epydocString.getDescription(); } result.add(formatted); result.add(formatStructuredDocString(epydocString)); unformattedOutput.add(result); return; } else if (documentationSettings.isReSTFormat(element.getContainingFile())) { Module module = ModuleUtil.findModuleForPsiElement(element); String formatted = null; if (module != null) { String[] lines = removeCommonIndentation(docstring); formatted = ReSTRunner.formatDocstring(module, StringUtil.join(lines, "\n")); } if (formatted == null) { formatted = new SphinxDocString(docstring).getDescription(); } result.add(formatted); unformattedOutput.add(result); return; } String[] lines = removeCommonIndentation(docstring); boolean is_first; // reconstruct back, dropping first empty fragment as needed is_first = true; int tabSize = CodeStyleSettingsManager.getSettings(project).getTabSize(PythonFileType.INSTANCE); for (String line : lines) { if (is_first && ourSpacesPattern.matcher(line).matches()) continue; // ignore all initial whitespace if (is_first) is_first = false; else result.add(BR); int leadingTabs = 0; while (leadingTabs < line.length() && line.charAt(leadingTabs) == '\t') { leadingTabs++; } if (leadingTabs > 0) { line = StringUtil.repeatSymbol(' ', tabSize * leadingTabs) + line.substring(leadingTabs); } result.add(combUp(line)); } formattedOutput.add(result); } private void addParameterDoc(PyNamedParameter followed) { PyFunction function = PsiTreeUtil.getParentOfType(followed, PyFunction.class); if (function != null) { final String docString = PyUtil.strValue(function.getDocStringExpression()); StructuredDocString structuredDocString = StructuredDocString.parse(docString); if (structuredDocString != null) { final String name = followed.getName(); final String type = structuredDocString.getParamType(name); if (type != null) { myBody.add(": ").add(type); } final String desc = structuredDocString.getParamDescription(name); if (desc != null) { myEpilog.add(BR).add(desc); } } } } private static String[] removeCommonIndentation(String docstring) { // detect common indentation String[] lines = LineTokenizer.tokenize(docstring, false); boolean is_first = true; int cut_width = Integer.MAX_VALUE; int firstIndentedLine = 0; for (String frag : lines) { if (frag.length() == 0) continue; int pad_width = 0; final Matcher matcher = ourSpacesPattern.matcher(frag); if (matcher.find()) { pad_width = matcher.end(); } if (is_first) { is_first = false; if (pad_width == 0) { // first line may have zero padding firstIndentedLine = 1; continue; } } if (pad_width < cut_width) cut_width = pad_width; } // remove common indentation if (cut_width > 0 && cut_width < Integer.MAX_VALUE) { for (int i = firstIndentedLine; i < lines.length; i+= 1) { if (lines[i].length() > 0) lines[i] = lines[i].substring(cut_width); } } return lines; } private static String formatStructuredDocString(StructuredDocString docString) { StringBuilder result = new StringBuilder(); formatParameterDescriptions(docString, result, false); formatParameterDescriptions(docString, result, true); final String returnDescription = docString.getReturnDescription(); final String returnType = docString.getReturnType(); if (returnDescription != null || returnType != null) { result.append("<br><b>Return value:</b><br>"); if (returnDescription != null) { result.append(returnDescription); } if (returnType != null) { result.append(" <i>Type: ").append(returnType).append("</i>"); } } final List<String> raisedException = docString.getRaisedExceptions(); if (raisedException.size() > 0) { result.append("<br><b>Raises:</b><br>"); for (String s : raisedException) { result.append("<b>").append(s).append("</b> - ").append(docString.getRaisedExceptionDescription(s)).append("<br>"); } } return result.toString(); } private static void formatParameterDescriptions(StructuredDocString docString, StringBuilder result, boolean keyword) { List<String> parameters = keyword ? docString.getKeywordArguments() : docString.getParameters(); if (parameters.size() > 0) { result.append("<br><b>").append(keyword ? "Keyword arguments:" : "Parameters").append("</b><br>"); for (String parameter : parameters) { final String description = keyword ? docString.getKeywordArgumentDescription(parameter) : docString.getParamDescription(parameter); result.append("<b>").append(parameter).append("</b>: ").append(description); final String paramType = docString.getParamType(parameter); if (paramType != null) { result.append(" <i>Type: ").append(paramType).append("</i>"); } result.append("<br>"); } } } private void addModulePath(PyFile followed) { // what to prepend to a module description? String path = VfsUtil.urlToPath(followed.getUrl()); if ("".equals(path)) { myProlog.addWith(TagSmall, $(PyBundle.message("QDOC.module.path.unknown"))); } else { RootFinder finder = new RootFinder(path); ResolveImportUtil.visitRoots(followed, finder); final String root_path = finder.getResult(); if (root_path != null) { String after_part = path.substring(root_path.length()); myProlog.addWith(TagSmall, $(root_path).addWith(TagBold, $(after_part))); } else myProlog.addWith(TagSmall, $(path)); } } private static class RootFinder implements RootVisitor { private String myResult; private String myPath; private RootFinder(String path) { myPath = path; } public boolean visitRoot(VirtualFile root) { String vpath = VfsUtil.urlToPath(root.getUrl()); if (myPath.startsWith(vpath)) { myResult = vpath; return false; } else return true; } String getResult() { return myResult; } } }
package net.finmath.montecarlo.interestrate.models; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import net.finmath.exception.CalculationException; import net.finmath.functions.AnalyticFormulas; import net.finmath.marketdata.model.AnalyticModel; import net.finmath.marketdata.model.curves.DiscountCurve; import net.finmath.marketdata.model.curves.DiscountCurveFromForwardCurve; import net.finmath.marketdata.model.curves.ForwardCurve; import net.finmath.marketdata.model.volatilities.AbstractSwaptionMarketData; import net.finmath.marketdata.products.Swap; import net.finmath.marketdata.products.SwapAnnuity; import net.finmath.montecarlo.AbstractRandomVariableFactory; import net.finmath.montecarlo.RandomVariableFactory; import net.finmath.montecarlo.interestrate.CalibrationProduct; import net.finmath.montecarlo.interestrate.LIBORMarketModel; import net.finmath.montecarlo.interestrate.models.covariance.AbstractLIBORCovarianceModelParametric; import net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModel; import net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModelCalibrateable; import net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct; import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation; import net.finmath.montecarlo.interestrate.products.SwaptionSimple; import net.finmath.montecarlo.model.AbstractProcessModel; import net.finmath.montecarlo.process.MonteCarloProcess; import net.finmath.stochastic.RandomVariable; import net.finmath.time.RegularSchedule; import net.finmath.time.Schedule; import net.finmath.time.TimeDiscretization; import net.finmath.time.TimeDiscretizationFromArray; /** * Implements a (generalized) LIBOR market model with generic covariance structure (lognormal, normal, displaced or stochastic volatility) * with some drift approximation methods. * <br><br> * In its default case the class specifies a multi-factor LIBOR market model in its log-normal formulation, that is * <i>L<sub>j</sub> = exp(Y<sub>j</sub>) </i> where * \[ * dY_{j} = \mu_{j} dt + \lambda_{1,j} dW_{1} + \ldots + \lambda_{m,j} dW_{m} * \] * <br> * The model uses an {@link net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModel} for the specification of * <i>(&lambda;<sub>1,j</sub>,...,&lambda;<sub>m,j</sub>)</i> as a covariance model. * See {@link net.finmath.montecarlo.model.ProcessModel} for details on the implemented interface * <br><br> * However, the class is more general: * <ul> * <li> * The model may be log-normal or normal specification with a given local volatility. * </li> * <li> * The class implements different measure(drift) / numeraire pairs: terminal measure and spot measure. * </li> * <li> * The class allows to configure a discounting curve (e.g.&nbsp;for "OIS discounting") using a simple deterministic zero spread. * In this case, the numeraire \( N(t) \) is adjusted by \( \exp( \int_0^t -\lambda(\tau) d\tau ) \). * </li> * </ul> * * <br> * The class specifies a LIBOR market model, that is * <i>L<sub>j</sub> = f(Y<sub>j</sub>) </i> where * <ul> * <li> * <i>f</i> is <i>f(x) = exp(x)</i> (default, log-normal LIBOR Market Model) or * </li> * <li> * <i>f</i> is <i>f(x) = x</i> (normal model, used if <code>property.set("stateSpace","NORMAL"))</code> * </li> * </ul> * and * <br> * <i>dY<sub>j</sub> = &mu;<sub>j</sub> dt + &lambda;<sub>1,j</sub> dW<sub>1</sub> + ... + &lambda;<sub>m,j</sub> dW<sub>m</sub></i> <br> * <br> * see {@link net.finmath.montecarlo.model.ProcessModel} for details on the implemented interface. * <br> * The model uses an <code>AbstractLIBORCovarianceModel</code> as a covariance model. * If the covariance model is of type <code>AbstractLIBORCovarianceModelParametric</code> * a calibration to swaptions can be performed. * <br> * Note that &lambda; may still depend on <i>L</i>, hence generating a log-normal dynamic for <i>L</i> even * if the stateSpace property has been set to NORMAL. * <br> * * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code>: Simulate under spot measure. In this case, the single curve numeraire * is \( N(T_{i}) = \prod_{j=0}^{i-1} (1 + L(T_{j},T_{j+1};T_{j}) (T_{j+1}-T_{j})) \). * </li> * <li> * <code>TERMINAL</code>: Simulate under terminal measure. In this case, the single curve numeraire * is \( N(T_{i}) = P(T_{n};T_{i}) = \prod_{j=i}^{n-1} (1 + L(T_{j},T_{j+1};T_{i}) (T_{j+1}-T_{j}))^{-1} \). * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code>: The state space transform is set to exp, i.e., <i>L = exp(Y)</i>. When the covariance model is deterministic, then this is the classical lognormal LIBOR market model. Note that the covariance model may still provide a local volatility function. * </li> * <li> * <code>NORMAL</code>: The state space transform is set to identity, i.e., <i>L = Y</i>. When the covariance model is deterministic, then this is a normal LIBOR market model. Note that the covariance model may still provide a local volatility function. * </li> * </ul> * </li> * <li> * <code>liborCap</code>: An optional <code>Double</code> value applied as a cap to the LIBOR rates. * May be used to limit the simulated valued to prevent values attaining POSITIVE_INFINITY and * numerical problems. To disable the cap, set <code>liborCap</code> to <code>Double.POSITIVE_INFINITY</code>. * </li> * </ul> * <br> * The main task of this class is to calculate the risk-neutral drift and the * corresponding numeraire given the covariance model. * * The calibration of the covariance structure is not part of this class. For the calibration * of parametric models of the instantaneous covariance see * {@link net.finmath.montecarlo.interestrate.models.covariance.AbstractLIBORCovarianceModelParametric#getCloneCalibrated(LIBORMarketModel, CalibrationProduct[], Map)}. * * @author Christian Fries * @version 1.2 * @see net.finmath.montecarlo.process.MonteCarloProcess The interface for numerical schemes. * @see net.finmath.montecarlo.model.ProcessModel The interface for models provinding parameters to numerical schemes. * @see net.finmath.montecarlo.interestrate.models.covariance.AbstractLIBORCovarianceModel The abstract covariance model plug ins. * @see net.finmath.montecarlo.interestrate.models.covariance.AbstractLIBORCovarianceModelParametric A parametic covariance model including a generic calibration algorithm. */ public class LIBORMarketModelFromCovarianceModel extends AbstractProcessModel implements LIBORMarketModel, Serializable { private static final long serialVersionUID = 4166077559001066615L; public enum Measure { SPOT, TERMINAL } public enum StateSpace { NORMAL, LOGNORMAL } public enum Driftapproximation { EULER, LINE_INTEGRAL, PREDICTOR_CORRECTOR } public enum InterpolationMethod { LINEAR, LOG_LINEAR_UNCORRECTED, LOG_LINEAR_CORRECTED } private final TimeDiscretization liborPeriodDiscretization; private String forwardCurveName; private AnalyticModel curveModel; private ForwardCurve forwardRateCurve; private DiscountCurve discountCurve; private final AbstractRandomVariableFactory randomVariableFactory; private LIBORCovarianceModel covarianceModel; private AbstractSwaptionMarketData swaptionMarketData; private Driftapproximation driftApproximationMethod = Driftapproximation.EULER; private Measure measure = Measure.SPOT; private StateSpace stateSpace = StateSpace.LOGNORMAL; private InterpolationMethod interpolationMethod = InterpolationMethod.LOG_LINEAR_UNCORRECTED; private double liborCap = 1E5; // This is a cache of the integrated covariance. private double[][][] integratedLIBORCovariance; private transient Object integratedLIBORCovarianceLazyInitLock = new Object(); // Cache for the numeraires, needs to be invalidated if process changes - move out of the object (to process?) private transient MonteCarloProcess numerairesProcess = null; private transient ConcurrentHashMap<Integer, RandomVariable> numeraires = new ConcurrentHashMap<>(); private transient ConcurrentHashMap<Double, RandomVariable> numeraireDiscountFactorForwardRates = new ConcurrentHashMap<>(); private transient ConcurrentHashMap<Double, RandomVariable> numeraireDiscountFactors = new ConcurrentHashMap<>(); private transient Vector<RandomVariable> interpolationDriftAdjustmentsTerminal = new Vector<RandomVariable>(); /** * Creates a LIBOR Market Model for given covariance. * * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code> (<code>String</code>): Simulate under spot measure. * </li> * <li> * <code>TERMINAL</code> (<code>String</code>): Simulate under terminal measure. * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code> (<code>String</code>): Simulate <i>L = exp(Y)</i>. * </li> * <li> * <code>NORMAL</code> (<code>String</code>): Simulate <i>L = Y</i>. * </li> * </ul> * </li> * <li> * <code>liborCap</code>: An optional <code>Double</code> value applied as a cap to the LIBOR rates. * May be used to limit the simulated valued to prevent values attaining POSITIVE_INFINITY and * numerical problems. To disable the cap, set <code>liborCap</code> to <code>Double.POSITIVE_INFINITY</code>. * </li> * <li> * <code>calibrationParameters</code>: Possible values: * <ul> * <li> * <code>Map&lt;String,Object&gt;</code> a parameter map with the following key/value pairs: * <ul> * <li> * <code>accuracy</code>: <code>Double</code> specifying the required solver accuracy. * </li> * <li> * <code>maxIterations</code>: <code>Integer</code> specifying the maximum iterations for the solver. * </li> * </ul> * </li> * </ul> * </li> * </ul> * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param analyticModel The associated analytic model of this model (containing the associated market data objects like curve). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param randomVariableFactory The random variable factory used to create the inital values of the model. * @param covarianceModel The covariance model to use. * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, AnalyticModel analyticModel, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, AbstractRandomVariableFactory randomVariableFactory, LIBORCovarianceModel covarianceModel, Map<String, ?> properties ) throws CalculationException { // Set some properties if(properties != null && properties.containsKey("measure")) { measure = Measure.valueOf(((String)properties.get("measure")).toUpperCase()); } if(properties != null && properties.containsKey("stateSpace")) { stateSpace = StateSpace.valueOf(((String)properties.get("stateSpace")).toUpperCase()); } if(properties != null && properties.containsKey("interpolationMethod")) { interpolationMethod = InterpolationMethod.valueOf(((String)properties.get("interpolationMethod")).toUpperCase()); } if(properties != null && properties.containsKey("liborCap")) { liborCap = (Double)properties.get("liborCap"); } Map<String,Object> calibrationParameters = null; if(properties != null && properties.containsKey("calibrationParameters")) { calibrationParameters = (Map<String,Object>)properties.get("calibrationParameters"); } this.liborPeriodDiscretization = liborPeriodDiscretization; curveModel = analyticModel; this.forwardRateCurve = forwardRateCurve; this.discountCurve = discountCurve; this.randomVariableFactory = randomVariableFactory; this.covarianceModel = covarianceModel; } /** * Creates a LIBOR Market Model for given covariance with a calibration (if calibration items are given). * <br> * If calibrationItems in non-empty and the covariance model is a parametric model, * the covariance will be replaced by a calibrate version of the same model, i.e., * the LIBOR Market Model will be calibrated. Note: Calibration is not lazy. * <br> * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code> (<code>String</code>): Simulate under spot measure. * </li> * <li> * <code>TERMINAL</code> (<code>String</code>): Simulate under terminal measure. * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code> (<code>String</code>): Simulate <i>L = exp(Y)</i>. * </li> * <li> * <code>NORMAL</code> (<code>String</code>): Simulate <i>L = Y</i>. * </li> * </ul> * </li> * <li> * <code>liborCap</code>: An optional <code>Double</code> value applied as a cap to the LIBOR rates. * May be used to limit the simulated valued to prevent values attaining POSITIVE_INFINITY and * numerical problems. To disable the cap, set <code>liborCap</code> to <code>Double.POSITIVE_INFINITY</code>. * </li> * <li> * <code>calibrationParameters</code>: Possible values: * <ul> * <li> * <code>Map&lt;String,Object&gt;</code> a parameter map with the following key/value pairs: * <ul> * <li> * <code>accuracy</code>: <code>Double</code> specifying the required solver accuracy. * </li> * <li> * <code>maxIterations</code>: <code>Integer</code> specifying the maximum iterations for the solver. * </li> * </ul> * </li> * </ul> * </li> * </ul> * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param analyticModel The associated analytic model of this model (containing the associated market data objects like curve). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param randomVariableFactory The random variable factory used to create the inital values of the model. * @param covarianceModel The covariance model to use. * @param calibrationProducts The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i). * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @return A new instance of LIBORMarketModelFromCovarianceModel, possibly calibrated. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public static LIBORMarketModelFromCovarianceModel of( TimeDiscretization liborPeriodDiscretization, AnalyticModel analyticModel, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, AbstractRandomVariableFactory randomVariableFactory, LIBORCovarianceModel covarianceModel, CalibrationProduct[] calibrationProducts, Map<String, ?> properties ) throws CalculationException { LIBORMarketModelFromCovarianceModel model = new LIBORMarketModelFromCovarianceModel(liborPeriodDiscretization, analyticModel, forwardRateCurve, discountCurve, randomVariableFactory, covarianceModel, properties); // Perform calibration, if data is given if(calibrationProducts != null && calibrationProducts.length > 0) { Map<String,Object> calibrationParameters = null; if(properties != null && properties.containsKey("calibrationParameters")) { calibrationParameters = (Map<String,Object>)properties.get("calibrationParameters"); } LIBORCovarianceModelCalibrateable covarianceModelParametric = null; try { covarianceModelParametric = (LIBORCovarianceModelCalibrateable)covarianceModel; } catch(Exception e) { throw new ClassCastException("Calibration restricted to covariance models implementing LIBORCovarianceModelCalibrateable."); } LIBORCovarianceModel covarianceModelCalibrated = covarianceModelParametric.getCloneCalibrated(model, calibrationProducts, calibrationParameters); LIBORMarketModelFromCovarianceModel modelCalibrated = model.getCloneWithModifiedCovarianceModel(covarianceModelCalibrated); return modelCalibrated; } else { return model; } } /** * Creates a LIBOR Market Model for given covariance. * <br> * If calibrationItems in non-empty and the covariance model is a parametric model, * the covariance will be replaced by a calibrate version of the same model, i.e., * the LIBOR Market Model will be calibrated. * <br> * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code> (<code>String</code>): Simulate under spot measure. * </li> * <li> * <code>TERMINAL</code> (<code>String</code>): Simulate under terminal measure. * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code> (<code>String</code>): Simulate <i>L = exp(Y)</i>. * </li> * <li> * <code>NORMAL</code> (<code>String</code>): Simulate <i>L = Y</i>. * </li> * </ul> * </li> * <li> * <code>liborCap</code>: An optional <code>Double</code> value applied as a cap to the LIBOR rates. * May be used to limit the simulated valued to prevent values attaining POSITIVE_INFINITY and * numerical problems. To disable the cap, set <code>liborCap</code> to <code>Double.POSITIVE_INFINITY</code>. * </li> * <li> * <code>calibrationParameters</code>: Possible values: * <ul> * <li> * <code>Map&lt;String,Object&gt;</code> a parameter map with the following key/value pairs: * <ul> * <li> * <code>accuracy</code>: <code>Double</code> specifying the required solver accuracy. * </li> * <li> * <code>maxIterations</code>: <code>Integer</code> specifying the maximum iterations for the solver. * </li> * </ul> * </li> * </ul> * </li> * </ul> * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param analyticModel The associated analytic model of this model (containing the associated market data objects like curve). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param randomVariableFactory The random variable factory used to create the inital values of the model. * @param covarianceModel The covariance model to use. * @param calibrationProducts The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i). * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. * @deprecated Use LIBORMarketModelFromCovarianceModel.of() instead. */ @Deprecated public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, AnalyticModel analyticModel, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, AbstractRandomVariableFactory randomVariableFactory, LIBORCovarianceModel covarianceModel, CalibrationProduct[] calibrationProducts, Map<String, ?> properties ) throws CalculationException { // Set some properties if(properties != null && properties.containsKey("measure")) { measure = Measure.valueOf(((String)properties.get("measure")).toUpperCase()); } if(properties != null && properties.containsKey("stateSpace")) { stateSpace = StateSpace.valueOf(((String)properties.get("stateSpace")).toUpperCase()); } if(properties != null && properties.containsKey("interpolationMethod")) { interpolationMethod = InterpolationMethod.valueOf(((String)properties.get("interpolationMethod")).toUpperCase()); } if(properties != null && properties.containsKey("liborCap")) { liborCap = (Double)properties.get("liborCap"); } Map<String,Object> calibrationParameters = null; if(properties != null && properties.containsKey("calibrationParameters")) { calibrationParameters = (Map<String,Object>)properties.get("calibrationParameters"); } this.liborPeriodDiscretization = liborPeriodDiscretization; curveModel = analyticModel; this.forwardRateCurve = forwardRateCurve; this.discountCurve = discountCurve; this.randomVariableFactory = randomVariableFactory; // Perform calibration, if data is given if(calibrationProducts != null && calibrationProducts.length > 0) { LIBORCovarianceModelCalibrateable covarianceModelParametric = null; try { covarianceModelParametric = (LIBORCovarianceModelCalibrateable)covarianceModel; } catch(Exception e) { throw new ClassCastException("Calibration restricted to covariance models implementing LIBORCovarianceModelCalibrateable."); } this.covarianceModel = covarianceModelParametric.getCloneCalibrated(this, calibrationProducts, calibrationParameters); } else { this.covarianceModel = covarianceModel; } } /** * Creates a LIBOR Market Model for given covariance. * <br> * If calibrationItems in non-empty and the covariance model is a parametric model, * the covariance will be replaced by a calibrate version of the same model, i.e., * the LIBOR Market Model will be calibrated. * <br> * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code> (<code>String</code>): Simulate under spot measure. * </li> * <li> * <code>TERMINAL</code> (<code>String</code>): Simulate under terminal measure. * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code> (<code>String</code>): Simulate <i>L = exp(Y)</i>. * </li> * <li> * <code>NORMAL</code> (<code>String</code>): Simulate <i>L = Y</i>. * </li> * </ul> * </li> * <li> * <code>liborCap</code>: An optional <code>Double</code> value applied as a cap to the LIBOR rates. * May be used to limit the simulated valued to prevent values attaining POSITIVE_INFINITY and * numerical problems. To disable the cap, set <code>liborCap</code> to <code>Double.POSITIVE_INFINITY</code>. * </li> * <li> * <code>calibrationParameters</code>: Possible values: * <ul> * <li> * <code>Map&lt;String,Object&gt;</code> a parameter map with the following key/value pairs: * <ul> * <li> * <code>accuracy</code>: <code>Double</code> specifying the required solver accuracy. * </li> * <li> * <code>maxIterations</code>: <code>Integer</code> specifying the maximum iterations for the solver. * </li> * </ul> * </li> * </ul> * </li> * </ul> * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param analyticModel The associated analytic model of this model (containing the associated market data objects like curve). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param covarianceModel The covariance model to use. * @param calibrationItems The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i). * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. * @deprecated Use LIBORMarketModelFromCovarianceModel.of() instead. */ @Deprecated public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, AnalyticModel analyticModel, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, LIBORCovarianceModel covarianceModel, CalibrationProduct[] calibrationItems, Map<String, ?> properties ) throws CalculationException { this(liborPeriodDiscretization, analyticModel, forwardRateCurve, discountCurve, new RandomVariableFactory(), covarianceModel, calibrationItems, properties); } /** * Creates a LIBOR Market Model for given covariance. * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param covarianceModel The covariance model to use. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, LIBORCovarianceModel covarianceModel ) throws CalculationException { this(liborPeriodDiscretization, forwardRateCurve, new DiscountCurveFromForwardCurve(forwardRateCurve), covarianceModel, new CalibrationProduct[0], null); } /** * Creates a LIBOR Market Model for given covariance. * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param covarianceModel The covariance model to use. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, LIBORCovarianceModel covarianceModel ) throws CalculationException { this(liborPeriodDiscretization, forwardRateCurve, discountCurve, covarianceModel, new CalibrationProduct[0], null); } /** * Creates a LIBOR Market Model using a given covariance model and calibrating this model * to given swaption volatility data. * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param covarianceModel The covariance model to use. * @param swaptionMarketData The set of swaption values to calibrate to. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, LIBORCovarianceModel covarianceModel, AbstractSwaptionMarketData swaptionMarketData ) throws CalculationException { this(liborPeriodDiscretization, forwardRateCurve, new DiscountCurveFromForwardCurve(forwardRateCurve), covarianceModel, swaptionMarketData, null); } /** * Creates a LIBOR Market Model for given covariance. * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param covarianceModel The covariance model to use. * @param swaptionMarketData The set of swaption values to calibrate to. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, LIBORCovarianceModel covarianceModel, AbstractSwaptionMarketData swaptionMarketData ) throws CalculationException { this(liborPeriodDiscretization, forwardRateCurve, discountCurve, covarianceModel, swaptionMarketData, null); } /** * Creates a LIBOR Market Model for given covariance. * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param covarianceModel The covariance model to use. * @param swaptionMarketData The set of swaption values to calibrate to. * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, LIBORCovarianceModel covarianceModel, AbstractSwaptionMarketData swaptionMarketData, Map<String, ?> properties ) throws CalculationException { this( liborPeriodDiscretization, forwardRateCurve, discountCurve, covarianceModel, getCalibrationItems( liborPeriodDiscretization, forwardRateCurve, swaptionMarketData, // Condition under which we use analytic approximation (properties == null || properties.get("stateSpace") == null || ((String)properties.get("stateSpace")).toUpperCase().equals(StateSpace.LOGNORMAL.name())) && AbstractLIBORCovarianceModelParametric.class.isAssignableFrom(covarianceModel.getClass()) ), properties ); } /** * Creates a LIBOR Market Model for given covariance. * <br> * If calibrationItems in non-empty and the covariance model is a parametric model, * the covariance will be replaced by a calibrate version of the same model, i.e., * the LIBOR Market Model will be calibrated. * <br> * The map <code>properties</code> allows to configure the model. The following keys may be used: * <ul> * <li> * <code>measure</code>: Possible values: * <ul> * <li> * <code>SPOT</code> (<code>String</code>): Simulate under spot measure. * </li> * <li> * <code>TERMINAL</code> (<code>String</code>): Simulate under terminal measure. * </li> * </ul> * </li> * <li> * <code>stateSpace</code>: Possible values: * <ul> * <li> * <code>LOGNORMAL</code> (<code>String</code>): Simulate <i>L = exp(Y)</i>. * </li> * <li> * <code>NORMAL</code> (<code>String</code>): Simulate <i>L = Y</i>. * </li> * </ul> * </li> * <li> * <code>calibrationParameters</code>: Possible values: * <ul> * <li> * <code>Map&lt;String,Object&gt;</code> a parameter map with the following key/value pairs: * <ul> * <li> * <code>accuracy</code>: <code>Double</code> specifying the required solver accuracy. * </li> * <li> * <code>maxIterations</code>: <code>Integer</code> specifying the maximum iterations for the solver. * </li> * </ul> * </li> * </ul> * </li> * </ul> * * @param liborPeriodDiscretization The discretization of the interest rate curve into forward rates (tenor structure). * @param forwardRateCurve The initial values for the forward rates. * @param discountCurve The discount curve to use. This will create an LMM model with a deterministic zero-spread discounting adjustment. * @param covarianceModel The covariance model to use. * @param calibrationItems The vector of calibration items (a union of a product, target value and weight) for the objective function sum weight(i) * (modelValue(i)-targetValue(i). * @param properties Key value map specifying properties like <code>measure</code> and <code>stateSpace</code>. * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. * @deprecated Use LIBORMarketModelFromCovarianceModel.of() instead. */ @Deprecated public LIBORMarketModelFromCovarianceModel( TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, LIBORCovarianceModel covarianceModel, CalibrationProduct[] calibrationItems, Map<String, ?> properties ) throws CalculationException { this(liborPeriodDiscretization, null, forwardRateCurve, discountCurve, covarianceModel, calibrationItems, properties); } private static CalibrationProduct[] getCalibrationItems(TimeDiscretization liborPeriodDiscretization, ForwardCurve forwardCurve, AbstractSwaptionMarketData swaptionMarketData, boolean isUseAnalyticApproximation) { if(swaptionMarketData == null) { return null; } TimeDiscretization optionMaturities = swaptionMarketData.getOptionMaturities(); TimeDiscretization tenor = swaptionMarketData.getTenor(); double swapPeriodLength = swaptionMarketData.getSwapPeriodLength(); ArrayList<CalibrationProduct> calibrationProducts = new ArrayList<>(); for(int exerciseIndex=0; exerciseIndex<=optionMaturities.getNumberOfTimeSteps(); exerciseIndex++) { for(int tenorIndex=0; tenorIndex<=tenor.getNumberOfTimeSteps()-exerciseIndex; tenorIndex++) { // Create a swaption double exerciseDate = optionMaturities.getTime(exerciseIndex); double swapLength = tenor.getTime(tenorIndex); if(liborPeriodDiscretization.getTimeIndex(exerciseDate) < 0) { continue; } if(liborPeriodDiscretization.getTimeIndex(exerciseDate+swapLength) <= liborPeriodDiscretization.getTimeIndex(exerciseDate)) { continue; } int numberOfPeriods = (int)(swapLength / swapPeriodLength); double[] fixingDates = new double[numberOfPeriods]; double[] paymentDates = new double[numberOfPeriods]; double[] swapTenorTimes = new double[numberOfPeriods+1]; for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) { fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength; paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex+1) * swapPeriodLength; swapTenorTimes[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength; } swapTenorTimes[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength; // Swaptions swap rate Schedule swapTenor = new RegularSchedule(new TimeDiscretizationFromArray(swapTenorTimes)); double swaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve, null); // Set swap rates for each period double[] swaprates = new double[numberOfPeriods]; for(int periodStartIndex=0; periodStartIndex<numberOfPeriods; periodStartIndex++) { swaprates[periodStartIndex] = swaprate; } if(isUseAnalyticApproximation) { AbstractLIBORMonteCarloProduct swaption = new SwaptionAnalyticApproximation(swaprate, swapTenorTimes, SwaptionAnalyticApproximation.ValueUnit.VOLATILITYLOGNORMAL); double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate); calibrationProducts.add(new CalibrationProduct(swaption, impliedVolatility, 1.0)); } else { AbstractLIBORMonteCarloProduct swaption = new SwaptionSimple(swaprate, swapTenorTimes, SwaptionSimple.ValueUnit.VALUE); double forwardSwaprate = Swap.getForwardSwapRate(swapTenor, swapTenor, forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(swapTenor, forwardCurve); double impliedVolatility = swaptionMarketData.getVolatility(exerciseDate, swapLength, swaptionMarketData.getSwapPeriodLength(), swaprate); double targetValue = AnalyticFormulas.blackModelSwaptionValue(forwardSwaprate, impliedVolatility, exerciseDate, swaprate, swapAnnuity); calibrationProducts.add(new CalibrationProduct(swaption, targetValue, 1.0)); } } } return calibrationProducts.toArray(new CalibrationProduct[calibrationProducts.size()]); } @Override public LocalDateTime getReferenceDate() { return forwardRateCurve.getReferenceDate() != null ? forwardRateCurve.getReferenceDate().atStartOfDay() : null; } /** * Return the numeraire at a given time. * * The numeraire is provided for interpolated points. If requested on points which are not * part of the tenor discretization, the numeraire uses a linear interpolation of the reciprocal * value. See ISBN 0470047224 for details. * * @param time Time time <i>t</i> for which the numeraire should be returned <i>N(t)</i>. * @return The numeraire at the specified time as <code>RandomVariable</code> * @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. */ @Override public RandomVariable getNumeraire(double time) throws CalculationException { if(time < 0) { return randomVariableFactory.createRandomVariable(discountCurve.getDiscountFactor(curveModel, time)); } RandomVariable numeraire = getNumerairetUnAdjusted(time); /* * Adjust for discounting, i.e. funding or collateralization */ if (discountCurve != null) { RandomVariable deterministicNumeraireAdjustment = getNumeraireAdjustment(time); numeraire = numeraire.mult(numeraire.invert().getAverage()).div(deterministicNumeraireAdjustment); } return numeraire; } private RandomVariable getNumeraireAdjustment(double time) { boolean isInterpolateDiscountFactorsOnLiborPeriodDiscretization = true; TimeDiscretization timeDiscretizationForCurves = isInterpolateDiscountFactorsOnLiborPeriodDiscretization ? liborPeriodDiscretization : getProcess().getTimeDiscretization(); int timeIndex = timeDiscretizationForCurves.getTimeIndex(time); if(timeIndex >= 0) { return getNumeraireAdjustment(timeIndex); } else { // Interpolation int timeIndexPrev = Math.min(-timeIndex-2, getLiborPeriodDiscretization().getNumberOfTimes()-2); int timeIndexNext = timeIndexPrev+1; double timePrev = timeDiscretizationForCurves.getTime(timeIndexPrev); double timeNext = timeDiscretizationForCurves.getTime(timeIndexNext); RandomVariable numeraireAdjustmentPrev = getNumeraireAdjustment(timeIndexPrev); RandomVariable numeraireAdjustmentNext = getNumeraireAdjustment(timeIndexNext); return numeraireAdjustmentPrev.mult(numeraireAdjustmentNext.div(numeraireAdjustmentPrev).pow((time-timePrev)/(timeNext-timePrev))); } } private RandomVariable getNumeraireAdjustment(int timeIndex) { boolean isInterpolateDiscountFactorsOnLiborPeriodDiscretization = true; TimeDiscretization timeDiscretizationForCurves = isInterpolateDiscountFactorsOnLiborPeriodDiscretization ? liborPeriodDiscretization : getProcess().getTimeDiscretization(); double time = timeDiscretizationForCurves.getTime(timeIndex); synchronized(numeraireDiscountFactorForwardRates) { ensureCacheConsistency(); RandomVariable deterministicNumeraireAdjustment = numeraireDiscountFactors.get(time); if(deterministicNumeraireAdjustment == null) { double dfInitial = discountCurve.getDiscountFactor(curveModel, timeDiscretizationForCurves.getTime(0)); deterministicNumeraireAdjustment = randomVariableFactory.createRandomVariable(dfInitial); numeraireDiscountFactors.put(timeDiscretizationForCurves.getTime(0), deterministicNumeraireAdjustment); for(int i=0; i<timeDiscretizationForCurves.getNumberOfTimeSteps(); i++) { double dfPrev = discountCurve.getDiscountFactor(curveModel, timeDiscretizationForCurves.getTime(i)); double dfNext = discountCurve.getDiscountFactor(curveModel, timeDiscretizationForCurves.getTime(i+1)); double timeStep = timeDiscretizationForCurves.getTimeStep(i); double timeNext = timeDiscretizationForCurves.getTime(i+1); RandomVariable forwardRate = randomVariableFactory.createRandomVariable((dfPrev / dfNext - 1.0) / timeStep); numeraireDiscountFactorForwardRates.put(timeDiscretizationForCurves.getTime(i), forwardRate); deterministicNumeraireAdjustment = deterministicNumeraireAdjustment.discount(forwardRate, timeStep); numeraireDiscountFactors.put(timeNext, deterministicNumeraireAdjustment); } deterministicNumeraireAdjustment = numeraireDiscountFactors.get(time); } return deterministicNumeraireAdjustment; } } @Override public RandomVariable getForwardDiscountBond(double time, double maturity) throws CalculationException { RandomVariable inverseForwardBondAsOfTime = getLIBOR(time, time, maturity).mult(maturity-time).add(1.0); RandomVariable inverseForwardBondAsOfZero = getLIBOR(0.0, time, maturity).mult(maturity-time).add(1.0); RandomVariable forwardDiscountBondAsOfZero = getNumeraireAdjustment(maturity).div(getNumeraireAdjustment(time)); return forwardDiscountBondAsOfZero.mult(inverseForwardBondAsOfZero).div(inverseForwardBondAsOfTime); } private void ensureCacheConsistency() { /* * Check if caches are valid (i.e. process did not change) */ if (getProcess() != numerairesProcess) { // Clear caches numeraires.clear(); numeraireDiscountFactorForwardRates.clear(); numeraireDiscountFactors.clear(); numerairesProcess = getProcess(); interpolationDriftAdjustmentsTerminal.clear(); } } protected RandomVariable getNumerairetUnAdjusted(double time) throws CalculationException { /* * Check if numeraire is on LIBOR time grid */ int liborTimeIndex = getLiborPeriodIndex(time); RandomVariable numeraireUnadjusted; if (liborTimeIndex < 0) { /* * Interpolation of Numeraire: use already interpolated short Libor */ int upperIndex = -liborTimeIndex - 1; int lowerIndex = upperIndex - 1; if (lowerIndex < 0) { throw new IllegalArgumentException("Numeraire requested for time " + time + ". Unsupported"); } if (measure == Measure.TERMINAL) { /* * Due to time < T_{timeIndex+1} loop is needed. */ numeraireUnadjusted = getRandomVariableForConstant(1.0); for (int liborIndex = upperIndex; liborIndex <= liborPeriodDiscretization.getNumberOfTimeSteps() - 1; liborIndex++) { RandomVariable libor = getLIBOR(getTimeIndex(Math.min(time, liborPeriodDiscretization.getTime(liborIndex))), liborIndex); double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex); numeraireUnadjusted = numeraireUnadjusted.discount(libor, periodLength); } } else if (measure == Measure.SPOT) { numeraireUnadjusted = getNumerairetUnAdjusted(getLiborPeriod(upperIndex)); } else { throw new CalculationException("Numeraire not implemented for specified measure."); } /* * Multiply with short period bond */ numeraireUnadjusted = numeraireUnadjusted.discount(getLIBOR(time, time, getLiborPeriod(upperIndex)), getLiborPeriod(upperIndex) - time); return numeraireUnadjusted; } else { /* * Calculate the numeraire, when time is part of liborPeriodDiscretization */ return getNumerairetUnAdjustedAtLIBORIndex(liborTimeIndex); } } protected RandomVariable getNumerairetUnAdjustedAtLIBORIndex(int liborTimeIndex) throws CalculationException { /* * synchronize lazy init cache */ synchronized(numeraires) { /* * Check if numeraire cache is valid (i.e. process did not change) */ ensureCacheConsistency(); /* * Check if numeraire is part of the cache */ RandomVariable numeraireUnadjusted = numeraires.get(liborTimeIndex); if (numeraireUnadjusted == null) { if (measure == Measure.TERMINAL) { int timeIndex = getTimeIndex(liborPeriodDiscretization.getTime(liborTimeIndex)); if(timeIndex < 0) { timeIndex = -timeIndex -1; } // Initialize to 1.0 numeraireUnadjusted = getRandomVariableForConstant(1.0); /* * Due to time < T_{timeIndex+1} loop is needed. */ for (int liborIndex = liborTimeIndex; liborIndex <= liborPeriodDiscretization.getNumberOfTimeSteps() - 1; liborIndex++) { RandomVariable libor = getLIBOR(timeIndex, liborIndex); double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex); numeraireUnadjusted = numeraireUnadjusted.discount(libor, periodLength); } } else if (measure == Measure.SPOT) { /* * If numeraire is not N(0), multiply (1 + L(Ti-1)*dt) on N(Ti-1) */ if (liborTimeIndex != 0) { int timeIndex = getTimeIndex(liborPeriodDiscretization.getTime(liborTimeIndex-1)); if(timeIndex < 0) { timeIndex = -timeIndex -1; } double periodLength = liborPeriodDiscretization.getTimeStep(liborTimeIndex - 1); RandomVariable libor = getLIBOR(timeIndex, liborTimeIndex - 1); numeraireUnadjusted = getNumerairetUnAdjustedAtLIBORIndex(liborTimeIndex - 1).accrue(libor, periodLength); } else { numeraireUnadjusted = getRandomVariableForConstant(1.0); } } else { throw new CalculationException("Numeraire not implemented for specified measure."); } numeraires.put(liborTimeIndex, numeraireUnadjusted); } return numeraireUnadjusted; } } public Map<Double, RandomVariable> getNumeraireAdjustments() { return Collections.unmodifiableMap(numeraireDiscountFactorForwardRates); } @Override public RandomVariable[] getInitialState() { double[] liborInitialStates = new double[liborPeriodDiscretization.getNumberOfTimeSteps()]; for(int timeIndex=0; timeIndex<liborPeriodDiscretization.getNumberOfTimeSteps(); timeIndex++) { double rate = forwardRateCurve.getForward(curveModel, liborPeriodDiscretization.getTime(timeIndex), liborPeriodDiscretization.getTimeStep(timeIndex)); liborInitialStates[timeIndex] = (stateSpace == StateSpace.LOGNORMAL) ? Math.log(Math.max(rate,0)) : rate; } RandomVariable[] initialStateRandomVariable = new RandomVariable[getNumberOfComponents()]; for(int componentIndex=0; componentIndex<getNumberOfComponents(); componentIndex++) { initialStateRandomVariable[componentIndex] = getRandomVariableForConstant(liborInitialStates[componentIndex]); } return initialStateRandomVariable; } /** * Return the complete vector of the drift for the time index timeIndex, given that current state is realizationAtTimeIndex. * The drift will be zero for rates being already fixed. * * The method currently provides the drift for either <code>Measure.SPOT</code> or <code>Measure.TERMINAL</code> - depending how the * model object was constructed. For <code>Measure.TERMINAL</code> the j-th entry of the return value is the random variable * \[ * \mu_{j}^{\mathbb{Q}^{P(T_{n})}}(t) \ = \ - \mathop{\sum_{l\geq j+1}}_{l\leq n-1} \frac{\delta_{l}}{1+\delta_{l} L_{l}(t)} (\lambda_{j}(t) \cdot \lambda_{l}(t)) * \] * and for <code>Measure.SPOT</code> the j-th entry of the return value is the random variable * \[ * \mu_{j}^{\mathbb{Q}^{N}}(t) \ = \ \sum_{m(t) &lt; l\leq j} \frac{\delta_{l}}{1+\delta_{l} L_{l}(t)} (\lambda_{j}(t) \cdot \lambda_{l}(t)) * \] * where \( \lambda_{j} \) is the vector for factor loadings for the j-th component of the stochastic process (that is, the diffusion part is * \( \sum_{k=1}^m \lambda_{j,k} \mathrm{d}W_{k} \)). * * Note: The scalar product of the factor loadings determines the instantaneous covariance. If the model is written in log-coordinates (using exp as a state space transform), we find * \(\lambda_{j} \cdot \lambda_{l} = \sum_{k=1}^m \lambda_{j,k} \lambda_{l,k} = \sigma_{j} \sigma_{l} \rho_{j,l} \). * If the model is written without a state space transformation (in its orignial coordinates) then \(\lambda_{j} \cdot \lambda_{l} = \sum_{k=1}^m \lambda_{j,k} \lambda_{l,k} = L_{j} L_{l} \sigma_{j} \sigma_{l} \rho_{j,l} \). * * * @see net.finmath.montecarlo.interestrate.models.LIBORMarketModelFromCovarianceModel#getNumeraire(double) The calculation of the drift is consistent with the calculation of the numeraire in <code>getNumeraire</code>. * @see net.finmath.montecarlo.interestrate.models.LIBORMarketModelFromCovarianceModel#getFactorLoading(int, int, RandomVariable[]) The factor loading \( \lambda_{j,k} \). * * @param timeIndex Time index <i>i</i> for which the drift should be returned <i>&mu;(t<sub>i</sub>)</i>. * @param realizationAtTimeIndex Time current forward rate vector at time index <i>i</i> which should be used in the calculation. * @return The drift vector &mu;(t<sub>i</sub>) as <code>RandomVariableFromDoubleArray[]</code> */ @Override public RandomVariable[] getDrift(int timeIndex, RandomVariable[] realizationAtTimeIndex, RandomVariable[] realizationPredictor) { double time = getTime(timeIndex); int firstLiborIndex = this.getLiborPeriodIndex(time)+1; if(firstLiborIndex<0) { firstLiborIndex = -firstLiborIndex-1 + 1; } RandomVariable zero = getRandomVariableForConstant(0.0); // Allocate drift vector and initialize to zero (will be used to sum up drift components) RandomVariable[] drift = new RandomVariable[getNumberOfComponents()]; for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) { drift[componentIndex] = zero; } RandomVariable[] covarianceFactorSums = new RandomVariable[getNumberOfFactors()]; for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) { covarianceFactorSums[factorIndex] = zero; } if(measure == Measure.SPOT) { // Calculate drift for the component componentIndex (starting at firstLiborIndex, others are zero) for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) { double periodLength = liborPeriodDiscretization.getTimeStep(componentIndex); RandomVariable libor = realizationAtTimeIndex[componentIndex]; RandomVariable oneStepMeasureTransform = getRandomVariableForConstant(periodLength).discount(libor, periodLength); if(stateSpace == StateSpace.LOGNORMAL) { // The drift has an additional forward rate factor oneStepMeasureTransform = oneStepMeasureTransform.mult(libor); } RandomVariable[] factorLoading = getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex); for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) { covarianceFactorSums[factorIndex] = covarianceFactorSums[factorIndex].add(oneStepMeasureTransform.mult(factorLoading[factorIndex])); drift[componentIndex] = drift[componentIndex].addProduct(covarianceFactorSums[factorIndex], factorLoading[factorIndex]); } } } else if(measure == Measure.TERMINAL) { // Calculate drift for the component componentIndex (starting at firstLiborIndex, others are zero) for(int componentIndex=getNumberOfComponents()-1; componentIndex>=firstLiborIndex; componentIndex double periodLength = liborPeriodDiscretization.getTimeStep(componentIndex); RandomVariable libor = realizationAtTimeIndex[componentIndex]; RandomVariable oneStepMeasureTransform = getRandomVariableForConstant(periodLength).discount(libor, periodLength); if(stateSpace == StateSpace.LOGNORMAL) { oneStepMeasureTransform = oneStepMeasureTransform.mult(libor); } RandomVariable[] factorLoading = getFactorLoading(timeIndex, componentIndex, realizationAtTimeIndex); for(int factorIndex=0; factorIndex<getNumberOfFactors(); factorIndex++) { drift[componentIndex] = drift[componentIndex].addProduct(covarianceFactorSums[factorIndex], factorLoading[factorIndex]); covarianceFactorSums[factorIndex] = covarianceFactorSums[factorIndex].sub(oneStepMeasureTransform.mult(factorLoading[factorIndex])); } } } if(stateSpace == StateSpace.LOGNORMAL) { // Drift adjustment for log-coordinate in each component for(int componentIndex=firstLiborIndex; componentIndex<getNumberOfComponents(); componentIndex++) { RandomVariable variance = covarianceModel.getCovariance(getTime(timeIndex), componentIndex, componentIndex, realizationAtTimeIndex); drift[componentIndex] = drift[componentIndex].addProduct(variance, -0.5); } } return drift; } @Override public RandomVariable[] getFactorLoading(int timeIndex, int componentIndex, RandomVariable[] realizationAtTimeIndex) { return covarianceModel.getFactorLoading(getTime(timeIndex), getLiborPeriod(componentIndex), realizationAtTimeIndex); } @Override public RandomVariable applyStateSpaceTransform(int componentIndex, RandomVariable randomVariable) { RandomVariable value = randomVariable; if(stateSpace == StateSpace.LOGNORMAL) { value = value.exp(); } if(!Double.isInfinite(liborCap)) { value = value.cap(liborCap); } return value; } @Override public RandomVariable applyStateSpaceTransformInverse(int componentIndex, RandomVariable randomVariable) { RandomVariable value = randomVariable; if(stateSpace == StateSpace.LOGNORMAL) { value = value.log(); } return value; } /* (non-Javadoc) * @see net.finmath.montecarlo.model.ProcessModel#getRandomVariableForConstant(double) */ @Override public RandomVariable getRandomVariableForConstant(double value) { return randomVariableFactory.createRandomVariable(value); } /** * @return Returns the driftApproximationMethod. */ public Driftapproximation getDriftApproximationMethod() { return driftApproximationMethod; } @Override public RandomVariable getLIBOR(double time, double periodStart, double periodEnd) throws CalculationException { int periodStartIndex = getLiborPeriodIndex(periodStart); int periodEndIndex = getLiborPeriodIndex(periodEnd); // If time is beyond fixing, use the fixing time. time = Math.min(time, periodStart); int timeIndex = getTimeIndex(time); // If time is not part of the discretization, use the nearest available point. if(timeIndex < 0) { timeIndex = -timeIndex-2; if(time-getTime(timeIndex) > getTime(timeIndex+1)-time) { timeIndex++; } } // The forward rates are provided on fractional tenor discretization points using linear interpolation. See ISBN 0470047224. // Interpolation on tenor using interpolationMethod if(periodEndIndex < 0) { int previousEndIndex = (-periodEndIndex-1)-1; double nextEndTime = getLiborPeriod(previousEndIndex+1); // Interpolate libor from periodStart to periodEnd on periodEnd RandomVariable onePlusLongLIBORdt = getLIBOR(time, periodStart, nextEndTime).mult(nextEndTime - periodStart).add(1.0); RandomVariable onePlusInterpolatedLIBORDt = getOnePlusInterpolatedLIBORDt(timeIndex, periodEnd, previousEndIndex); return onePlusLongLIBORdt.div(onePlusInterpolatedLIBORDt).sub(1.0).div(periodEnd - periodStart); } // Interpolation on tenor using interpolationMethod if(periodStartIndex < 0) { int previousStartIndex = (-periodStartIndex-1)-1; double prevStartTime = getLiborPeriod(previousStartIndex); double nextStartTime = getLiborPeriod(previousStartIndex+1); if(nextStartTime > periodEnd) { throw new AssertionError("Interpolation not possible."); } if(nextStartTime == periodEnd) { return getOnePlusInterpolatedLIBORDt(timeIndex, periodStart, previousStartIndex).sub(1.0).div(periodEnd - periodStart); } // RandomVariable onePlusLongLIBORdt = getLIBOR(Math.min(prevStartTime, time), nextStartTime, periodEnd).mult(periodEnd - nextStartTime).add(1.0); RandomVariable onePlusLongLIBORdt = getLIBOR(time, nextStartTime, periodEnd).mult(periodEnd - nextStartTime).add(1.0); RandomVariable onePlusInterpolatedLIBORDt = getOnePlusInterpolatedLIBORDt(timeIndex, periodStart, previousStartIndex); return onePlusLongLIBORdt.mult(onePlusInterpolatedLIBORDt).sub(1.0).div(periodEnd - periodStart); } if(periodStartIndex < 0 || periodEndIndex < 0) { throw new AssertionError("LIBOR requested outside libor discretization points and interpolation was not performed."); } // If this is a model primitive then return it if(periodStartIndex+1==periodEndIndex) { return getLIBOR(timeIndex, periodStartIndex); } // The requested LIBOR is not a model primitive. We need to calculate it (slow!) RandomVariable accrualAccount = randomVariableFactory.createRandomVariable(1.0); // Calculate the value of the forward bond for(int periodIndex = periodStartIndex; periodIndex<periodEndIndex; periodIndex++) { double subPeriodLength = getLiborPeriod(periodIndex+1) - getLiborPeriod(periodIndex); RandomVariable liborOverSubPeriod = getLIBOR(timeIndex, periodIndex); accrualAccount = accrualAccount == null ? liborOverSubPeriod.mult(subPeriodLength).add(1.0) : accrualAccount.accrue(liborOverSubPeriod, subPeriodLength); } RandomVariable libor = accrualAccount.sub(1.0).div(periodEnd - periodStart); return libor; } @Override public RandomVariable getLIBOR(int timeIndex, int liborIndex) throws CalculationException { // This method is just a synonym - call getProcessValue of super class return getProcessValue(timeIndex, liborIndex); } /** * Implement the interpolation of the forward rate in tenor time. * The method provides the forward rate \( F(t_{i}, S, T_{j+1}) \) where \( S \in [T_{j}, T_{j+1}] \). * * @param timeIndex The time index associated with the simulation time. The index i in \( t_{i} \). * @param periodStartTime The period start time S (on which we interpolate). * @param liborPeriodIndex The period index j for which \( S \in [T_{j}, T_{j+1}] \) (to avoid another lookup). * @return The interpolated forward rate. * @throws CalculationException Thrown if valuation failed. */ private RandomVariable getOnePlusInterpolatedLIBORDt(int timeIndex, double periodStartTime, int liborPeriodIndex) throws CalculationException { double tenorPeriodStartTime = getLiborPeriod(liborPeriodIndex); double tenorPeriodEndTime = getLiborPeriod(liborPeriodIndex + 1); double tenorDt = tenorPeriodEndTime - tenorPeriodStartTime; if(tenorPeriodStartTime < getTime(timeIndex)) { // Fixed at Long LIBOR period Start. timeIndex = Math.min(timeIndex, getTimeIndex(tenorPeriodStartTime)); if(timeIndex < 0) { // timeIndex = -timeIndex-2; // mapping to last known fixing. throw new IllegalArgumentException("Tenor discretization not part of time discretization."); } } RandomVariable onePlusLongLIBORDt = getLIBOR(timeIndex , liborPeriodIndex).mult(tenorDt).add(1.0); double smallDt = tenorPeriodEndTime - periodStartTime; double alpha = smallDt / tenorDt; RandomVariable onePlusInterpolatedLIBORDt; switch(interpolationMethod) { case LINEAR: onePlusInterpolatedLIBORDt = onePlusLongLIBORDt.mult(alpha).add(1 - alpha); break; case LOG_LINEAR_UNCORRECTED: onePlusInterpolatedLIBORDt = onePlusLongLIBORDt.log().mult(alpha).exp(); break; case LOG_LINEAR_CORRECTED: double adjustmentCoefficient = 0.5 * smallDt * (tenorPeriodStartTime - periodStartTime); RandomVariable adjustment = getInterpolationDriftAdjustment(timeIndex, liborPeriodIndex); adjustment = adjustment.mult(adjustmentCoefficient); onePlusInterpolatedLIBORDt = onePlusLongLIBORDt.log().mult(alpha).sub(adjustment).exp(); break; default: throw new IllegalArgumentException("Method for enum " + interpolationMethod.name() + " not implemented!"); } // Analytic adjustment for the interpolation // @TODO reference to AnalyticModelFromCuvesAndVols must not be null // @TODO This adjustment only applies if the corresponding adjustment in getNumeraire is enabled double analyticOnePlusLongLIBORDt = 1 + getForwardRateCurve().getForward(getAnalyticModel(), tenorPeriodStartTime, tenorDt) * tenorDt; double analyticOnePlusShortLIBORDt = 1 + getForwardRateCurve().getForward(getAnalyticModel(), periodStartTime, smallDt) * smallDt; double analyticOnePlusInterpolatedLIBORDt; switch(interpolationMethod) { case LINEAR: analyticOnePlusInterpolatedLIBORDt = analyticOnePlusLongLIBORDt * alpha + (1-alpha); break; case LOG_LINEAR_UNCORRECTED: case LOG_LINEAR_CORRECTED: analyticOnePlusInterpolatedLIBORDt = Math.exp(Math.log(analyticOnePlusLongLIBORDt) * alpha); break; default: throw new IllegalArgumentException("Method for enum " + interpolationMethod.name() + " not implemented!"); } onePlusInterpolatedLIBORDt = onePlusInterpolatedLIBORDt.mult(analyticOnePlusShortLIBORDt / analyticOnePlusInterpolatedLIBORDt); return onePlusInterpolatedLIBORDt; } /** * * @param evaluationTimeIndex * @param liborIndex * @return * @throws CalculationException */ private RandomVariable getInterpolationDriftAdjustment(int evaluationTimeIndex, int liborIndex) throws CalculationException { switch(interpolationMethod) { case LINEAR: case LOG_LINEAR_UNCORRECTED: return null; case LOG_LINEAR_CORRECTED: double tenorPeriodStartTime = getLiborPeriod(liborIndex); int tenorPeriodStartIndex = getTimeIndex(tenorPeriodStartTime); if(tenorPeriodStartIndex < 0) { tenorPeriodStartIndex = - tenorPeriodStartIndex - 2; } // Lazy init of interpolationDriftAdjustmentsTerminal if(evaluationTimeIndex == tenorPeriodStartIndex) { synchronized(interpolationDriftAdjustmentsTerminal) { // Invalidate cache if process has changed ensureCacheConsistency(); // Check if value is cached if(interpolationDriftAdjustmentsTerminal.size() <= liborIndex) { interpolationDriftAdjustmentsTerminal.setSize(getNumberOfLibors()); } RandomVariable interpolationDriftAdjustment = interpolationDriftAdjustmentsTerminal.get(liborIndex); if(interpolationDriftAdjustment == null) { interpolationDriftAdjustment = getInterpolationDriftAdjustmentEvaluated(evaluationTimeIndex, liborIndex); interpolationDriftAdjustmentsTerminal.set(liborIndex, interpolationDriftAdjustment); } return interpolationDriftAdjustment; } } else { return getInterpolationDriftAdjustmentEvaluated(evaluationTimeIndex, liborIndex); } default: throw new IllegalArgumentException("Method for enum " + interpolationMethod.name() + " not implemented!"); } } private RandomVariable getInterpolationDriftAdjustmentEvaluated(int evaluationTimeIndex, int liborIndex) throws CalculationException { double tenorPeriodStartTime = getLiborPeriod(liborIndex); double tenorPeriodEndTime = getLiborPeriod(liborIndex + 1); double tenorDt = tenorPeriodEndTime - tenorPeriodStartTime; RandomVariable driftAdjustment = getRandomVariableForConstant(0.0); /* * Integral approximation with trapezoid method. */ RandomVariable previousIntegrand = getRandomVariableForConstant(0.0); /* * Value in 0 */ RandomVariable[] realizationsAtZero = new RandomVariable[getNumberOfLibors()]; for(int liborIndexForRealization = 0; liborIndexForRealization < getNumberOfLibors(); liborIndexForRealization++) { realizationsAtZero[liborIndexForRealization] = getLIBOR(0, liborIndexForRealization); } RandomVariable[] factorLoading = getFactorLoading(0, liborIndex, realizationsAtZero); //o_{Li}(t) for(RandomVariable oneFactor : factorLoading) { previousIntegrand = previousIntegrand.add(oneFactor.squared()); } previousIntegrand = previousIntegrand.div( (realizationsAtZero[liborIndex].mult(tenorDt).add(1.0)).squared() ); if(stateSpace == StateSpace.LOGNORMAL) { previousIntegrand = previousIntegrand.mult( realizationsAtZero[liborIndex].squared() ); } /* * Integration */ for(int sumTimeIndex = 1; sumTimeIndex <= evaluationTimeIndex; sumTimeIndex++) { RandomVariable[] realizationsAtTimeIndex = new RandomVariable[getNumberOfLibors()]; for(int liborIndexForRealization = 0; liborIndexForRealization < getNumberOfLibors(); liborIndexForRealization++) { int evaluationTimeIndexForRealizations = Math.min(sumTimeIndex, getTimeIndex(getLiborPeriod(liborIndexForRealization))); if(evaluationTimeIndexForRealizations < 0) { evaluationTimeIndexForRealizations = - evaluationTimeIndexForRealizations - 2; } realizationsAtTimeIndex[liborIndexForRealization] = getLIBOR(evaluationTimeIndexForRealizations, liborIndexForRealization); } RandomVariable[] factorLoadingAtTimeIndex = getFactorLoading(sumTimeIndex, liborIndex, realizationsAtTimeIndex); //o_{Li}(t) RandomVariable integrand = getRandomVariableForConstant(0.0); for ( RandomVariable oneFactor: factorLoadingAtTimeIndex) { integrand = integrand.add(oneFactor.squared()); } integrand = integrand.div( (realizationsAtTimeIndex[liborIndex].mult(tenorDt).add(1.0)).squared() ); if(stateSpace == StateSpace.LOGNORMAL) { integrand = integrand.mult( realizationsAtTimeIndex[liborIndex].squared() ); } double integralDt = 0.5 * (getTime(sumTimeIndex) - getTime(sumTimeIndex - 1)); driftAdjustment = driftAdjustment.add( (integrand.add(previousIntegrand)).mult(integralDt) ); previousIntegrand = integrand; } return driftAdjustment; } @Override public int getNumberOfComponents() { return liborPeriodDiscretization.getNumberOfTimeSteps(); } @Override public int getNumberOfLibors() { // This is just a synonym to number of components return getNumberOfComponents(); } @Override public double getLiborPeriod(int timeIndex) { if(timeIndex >= liborPeriodDiscretization.getNumberOfTimes() || timeIndex < 0) { throw new ArrayIndexOutOfBoundsException("Index for LIBOR period discretization out of bounds: " + timeIndex + "."); } return liborPeriodDiscretization.getTime(timeIndex); } @Override public int getLiborPeriodIndex(double time) { return liborPeriodDiscretization.getTimeIndex(time); } @Override public TimeDiscretization getLiborPeriodDiscretization() { return liborPeriodDiscretization; } /** * @return Returns the LIBOR rates interpolation method. See {@link InterpolationMethod}. */ public InterpolationMethod getInterpolationMethod() { return interpolationMethod; } /** * @return Returns the measure. See {@link Measure}. */ public Measure getMeasure() { return measure; } @Override public double[][][] getIntegratedLIBORCovariance() { synchronized (integratedLIBORCovarianceLazyInitLock) { if(integratedLIBORCovariance == null) { TimeDiscretization liborPeriodDiscretization = getLiborPeriodDiscretization(); TimeDiscretization simulationTimeDiscretization = getTimeDiscretization(); integratedLIBORCovariance = new double[simulationTimeDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()][liborPeriodDiscretization.getNumberOfTimeSteps()]; for(int timeIndex = 0; timeIndex < simulationTimeDiscretization.getNumberOfTimeSteps(); timeIndex++) { double dt = simulationTimeDiscretization.getTime(timeIndex+1) - simulationTimeDiscretization.getTime(timeIndex); RandomVariable[][] factorLoadings = new RandomVariable[liborPeriodDiscretization.getNumberOfTimeSteps()][]; // Prefetch factor loadings for(int componentIndex = 0; componentIndex < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex++) { factorLoadings[componentIndex] = getFactorLoading(timeIndex, componentIndex, null); } for(int componentIndex1 = 0; componentIndex1 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex1++) { RandomVariable[] factorLoadingOfComponent1 = factorLoadings[componentIndex1]; // Sum the libor cross terms (use symmetry) for(int componentIndex2 = componentIndex1; componentIndex2 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex2++) { double integratedLIBORCovarianceValue = 0.0; if(getLiborPeriod(componentIndex1) > getTime(timeIndex)) { RandomVariable[] factorLoadingOfComponent2 = factorLoadings[componentIndex2]; for(int factorIndex = 0; factorIndex < getNumberOfFactors(); factorIndex++) { integratedLIBORCovarianceValue += factorLoadingOfComponent1[factorIndex].get(0) * factorLoadingOfComponent2[factorIndex].get(0) * dt; } } integratedLIBORCovariance[timeIndex][componentIndex1][componentIndex2] = integratedLIBORCovarianceValue; } } } // Integrate over time (i.e. sum up). for(int timeIndex = 1; timeIndex < simulationTimeDiscretization.getNumberOfTimeSteps(); timeIndex++) { double[][] prevIntegratedLIBORCovariance = integratedLIBORCovariance[timeIndex-1]; double[][] thisIntegratedLIBORCovariance = integratedLIBORCovariance[timeIndex]; for(int componentIndex1 = 0; componentIndex1 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex1++) { for(int componentIndex2 = componentIndex1; componentIndex2 < liborPeriodDiscretization.getNumberOfTimeSteps(); componentIndex2++) { thisIntegratedLIBORCovariance[componentIndex1][componentIndex2] = prevIntegratedLIBORCovariance[componentIndex1][componentIndex2] + thisIntegratedLIBORCovariance[componentIndex1][componentIndex2]; thisIntegratedLIBORCovariance[componentIndex2][componentIndex1] = thisIntegratedLIBORCovariance[componentIndex1][componentIndex2]; } } } } } return integratedLIBORCovariance; } @Override public Object clone() { try { Map<String, Object> properties = new HashMap<>(); properties.put("measure", measure.name()); properties.put("stateSpace", stateSpace.name()); return new LIBORMarketModelFromCovarianceModel(getLiborPeriodDiscretization(), getAnalyticModel(), getForwardRateCurve(), getDiscountCurve(), randomVariableFactory, covarianceModel, new CalibrationProduct[0], properties); } catch (CalculationException e) { return null; } } @Override public AnalyticModel getAnalyticModel() { return curveModel; } @Override public DiscountCurve getDiscountCurve() { return discountCurve; } @Override public ForwardCurve getForwardRateCurve() { return forwardRateCurve; } /** * Return the swaption market data used for calibration (if any, may be null). * * @return The swaption market data used for calibration (if any, may be null). */ public AbstractSwaptionMarketData getSwaptionMarketData() { return swaptionMarketData; } @Override public LIBORCovarianceModel getCovarianceModel() { return covarianceModel; } /** * @param covarianceModel A covariance model * @return A new <code>LIBORMarketModelFromCovarianceModel</code> using the specified covariance model. */ @Override public LIBORMarketModelFromCovarianceModel getCloneWithModifiedCovarianceModel(LIBORCovarianceModel covarianceModel) { LIBORMarketModelFromCovarianceModel model = (LIBORMarketModelFromCovarianceModel)this.clone(); model.covarianceModel = covarianceModel; return model; } @Override public LIBORMarketModelFromCovarianceModel getCloneWithModifiedData(Map<String, Object> dataModified) throws CalculationException { AbstractRandomVariableFactory randomVariableFactory = this.randomVariableFactory; TimeDiscretization liborPeriodDiscretization = this.liborPeriodDiscretization; AnalyticModel analyticModel = curveModel; ForwardCurve forwardRateCurve = this.forwardRateCurve; DiscountCurve discountCurve = this.discountCurve; LIBORCovarianceModel covarianceModel = this.covarianceModel; Map<String, Object> properties = new HashMap<>(); properties.put("measure", measure.name()); properties.put("stateSpace", stateSpace.name()); properties.put("interpolationMethod", interpolationMethod.name()); properties.put("liborCap", liborCap); if(dataModified != null) { randomVariableFactory = (AbstractRandomVariableFactory)dataModified.getOrDefault("randomVariableFactory", randomVariableFactory); liborPeriodDiscretization = (TimeDiscretization)dataModified.getOrDefault("liborPeriodDiscretization", liborPeriodDiscretization); analyticModel = (AnalyticModel)dataModified.getOrDefault("analyticModel", analyticModel); forwardRateCurve = (ForwardCurve)dataModified.getOrDefault("forwardRateCurve", forwardRateCurve); discountCurve = (DiscountCurve)dataModified.getOrDefault("discountCurve", discountCurve); covarianceModel = (LIBORCovarianceModel)dataModified.getOrDefault("covarianceModel", covarianceModel); if(dataModified.containsKey("swaptionMarketData")) { throw new RuntimeException("Swaption market data as input for getCloneWithModifiedData not supported."); } if(dataModified.containsKey("forwardRateShift")) { throw new RuntimeException("Forward rate shift clone currently disabled."); } } LIBORMarketModelFromCovarianceModel newModel = LIBORMarketModelFromCovarianceModel.of(liborPeriodDiscretization, analyticModel, forwardRateCurve, discountCurve, randomVariableFactory, covarianceModel, null, properties); return newModel; } @Override public Map<String, RandomVariable> getModelParameters() { Map<String, RandomVariable> modelParameters = new TreeMap<>(); // Add initial values for(int liborIndex=0; liborIndex<getLiborPeriodDiscretization().getNumberOfTimeSteps(); liborIndex++) { RandomVariable forward = null; try { forward = getLIBOR(0, liborIndex); } catch (CalculationException e) {} modelParameters.put("FORWARD("+getLiborPeriod(liborIndex) + "," + getLiborPeriod(liborIndex+1) + ")", forward); } // Add volatilities if(covarianceModel instanceof AbstractLIBORCovarianceModelParametric) { RandomVariable[] covarianceModelParameters = ((AbstractLIBORCovarianceModelParametric) covarianceModel).getParameter(); for(int covarianceModelParameterIndex=0; covarianceModelParameterIndex<covarianceModelParameters.length; covarianceModelParameterIndex++) { modelParameters.put("COVARIANCEMODELPARAMETER("+ covarianceModelParameterIndex + ")", covarianceModelParameters[covarianceModelParameterIndex]); } } // Add numeraire adjustments // TODO: Trigger lazy init for(Entry<Double, RandomVariable> numeraireAdjustment : numeraireDiscountFactorForwardRates.entrySet()) { modelParameters.put("NUMERAIREADJUSTMENT("+ numeraireAdjustment.getKey() + ")", numeraireAdjustment.getValue()); } return modelParameters; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); /* * Init transient fields */ integratedLIBORCovarianceLazyInitLock = new Object(); numeraires = new ConcurrentHashMap<>(); numeraireDiscountFactorForwardRates = new ConcurrentHashMap<>(); numeraireDiscountFactors = new ConcurrentHashMap<>(); interpolationDriftAdjustmentsTerminal = new Vector<RandomVariable>(); } @Override public String toString() { return "LIBORMarketModelFromCovarianceModel [liborPeriodDiscretization=" + liborPeriodDiscretization + ", forwardCurveName=" + forwardCurveName + ", curveModel=" + curveModel + ", forwardRateCurve=" + forwardRateCurve + ", discountCurve=" + discountCurve + ", covarianceModel=" + covarianceModel + ", driftApproximationMethod=" + driftApproximationMethod + ", measure=" + measure + ", stateSpace=" + stateSpace + "]"; } }