i want to know where to put my java code in opendaylight project , load balancing routing - openflow

i am new to opendaylight i have installed mininet and connected to the controller successfully. I want to implement dynamic load balancing on the controller i have the java code with me the problem is I donot know where to put it
**
* #file
LbRoutingImplementation.java
*
*
* #brief
Implementation of a routing engine using
* lb_routing. Implementation of lb_routing
come from Jung2 library
*
*/
package org.opendaylight.controller.routing.lb_routing_implementation.internal;
import org.opendaylight.controller.sal.core.Bandwidth;
import org.opendaylight.controller.sal.core.ConstructionException;
import org.opendayli
ght.controller.sal.core.Edge;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.core.Path;
import org.opendaylight.controller.sal.core.Property;
import org.op
endaylight.controller.sal.core.UpdateType;
import org.opendaylight.controller.sal.reader.IReadService;
import org.opendaylight.controller.sal.routing.IListenRoutingUpdates;
import org.opendaylight.controller.sal.routing.IRouting;
import org.opendaylight.co
ntroller.sal.topology.TopoEdgeUpdate;
import org.opendaylight.controller.switchmanager.ISwitchManager;
import org.opendaylight.controller.topologymanager.ITopologyManager;
import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
import org
.opendaylight.controller.statisticsmanager.internal.StatisticsManager;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.
util.EdgeType;
import java.lang.Exception;
import java.lang.IllegalArgumentException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Map;
import java.util.concu
rrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.collections15.Transformer;
public class LbRoutingImp
lementation implements IRouting, ITopologyManagerAware {
private static Logger log = LoggerFactory
.getLogger(LbRoutingImplementation.class);
private ConcurrentMap<Short, Graph<Node, Edge>> topologyBWAware;
private ConcurrentMap<Sho
rt, DijkstraShortestPath<Node, Edge>> sptBWAware;
DijkstraShortestPath<Node, Edge> mtp; // Max Throughput Path
private Set<IListenRoutingUpdates> routingAware;
private ISwitchManager switchManager;
30
private ITopologyManager topologyManager;
private IReadService readService;
private static final long DEFAULT_LINK_SPEED = Bandwidth.BW1Gbps;
private StatisticsManager statMgr;
private Timer lbRoutingTimer;
private TimerTask lbRoutingTimerTask;
public void setListenR
outingUpdates(IListenRoutingUpdates i) {
if (this.routingAware == null) {
this.routingAware = new HashSet<IListenRoutingUpdates>();
}
if (this.routingAware != null) {
log.debug("Adding routingAware listener:
{}", i);
this.routingAware.add(i);
}
}
public void unsetListenRoutingUpdates(IListenRoutingUpdates i) {
if (this.routingAware == null) {
return;
}
log.debug("Removing routingAware listener");
this.routingAware.remove(i);
if (this.routingAware.isEmpty()) {
// We don't have any listener lets dereference
this.routingAware = null;
}
}
#Override
public synchronized void initMaxThroughput(
final Map<Edge, Number> EdgeWeightMap) {
if (mtp != null) {
log.error("Max Throughput Dijkstra is already enabled!");
return;
}
Transformer<Edge, ? extends Number> mtTransformer = null;
i
f (EdgeWeightMap == null) {
mtTransformer = new Transformer<Edge, Double>() {
public Double transform(Edge e) {
if (switchManager == null) {
log.error("switchManager is null");
return (double)
-
1;
}
NodeConnector srcNC = e.getTailNodeConnector();
NodeConnector dstNC = e.getHeadNodeConnector();
if ((srcNC == null) || (dstNC == null)) {
log.error("srcNC:{} or dstNC:{} is null", srcNC, dstNC);
return (double)
-
1;
}
Bandwidth bwSrc = (Bandwidth) switchManager
.getNodeConnecto
rProp(srcNC,
Bandwidth.BandwidthPropName);
Bandwidth bwDst = (Bandwidth) switchManager
.getNodeConnectorProp(dstNC,
Bandwidth.BandwidthP
ropName);
34
// If the src and dst vertex don't have incoming or
// outgoing links we can get ride of them
if (topo.containsVertex(src.getNode())
&& topo.inDegree(src.getNode()) == 0
&
& topo.outDegree(src.getNode()) == 0) {
log.debug("Removing vertex {}", src);
topo.removeVertex(src.getNode());
}
if (topo.containsVertex(dst.getNode())
&& top
o.inDegree(dst.getNode()) == 0
&& topo.outDegree(dst.getNode()) == 0) {
log.debug("Removing vertex {}", dst);
topo.removeVertex(dst.getNode());
}
}
spt.
reset();
if (bw.equals(baseBW)) {
clearMaxThroughput();
}
} else {
log.error("Cannot find topology for BW {} this is unexpected!", bw);
}
return edgePresentInGraph;
}
priv
ate boolean edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
String srcType = null;
String dstType = null;
if (e == null || type == null) {
log.error("Edge or Update type are null!");
return false;
} else {
srcType = e.getTailNodeConnector().getType();
dstType = e.getHeadNodeConnector().getType();
if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
log.debug("Skip updates f
or {}", e);
return false;
}
if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
log.debug("Skip updates for {}", e);
return false;
}
}
Ban
dwidth bw = new Bandwidth(0);
boolean newEdge = false;
if (props != null)
props.remove(bw);
if (log.isDebugEnabled()) {
log.debug("edgeUpdate: {} bw: {}", e, bw.getValue());
}
35
Short baseBW = S
hort.valueOf((short) 0);
boolean add = (type == UpdateType.ADDED) ? true : false;
// Update base topo
newEdge = !updateTopo(e, baseBW, add);
if (newEdge == true) {
if (bw.getValue() != baseBW) {
/
/ Update BW topo
updateTopo(e, (short) bw.getValue(), add);
}
}
return newEdge;
}
#Override
public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
boolean callListeners = false;
for (int i = 0; i < topoedgeupdateList.size(); i++) {
Edge e = topoedgeupdateList.get(i).getEdge();
Set<Property> p = topoedgeupdateList.get(i).getProperty();
UpdateType type = topoedgeupdateList.get(i).getUpdateTy
pe();
if ((edgeUpdate(e, type, p)) && (!callListeners)) {
callListeners = true;
}
}
if ((callListeners) && (this.routingAware != null)) {
/*Map<Edge, Number> edgeWeightMap = new
Map<Edge,
Number >();
Bandwidth bw = new Bandwidth(0);
Graph<Node, Edge> topo = this.topologyBWAware.get(bw);
Collection<Edge> edges = topo.getEdges();
Iterator<Edge> iterEdge;
Number i;
for(it
erEdge = edges.iterator(), i = 0;iterEdge.hasNext();){
Edge e = iterEdge.next();
edgeWeightMap.put(e,i);
i = i.intValue()+1;
}*/
clearMaxThroughput();
mtp =
null;
initMaxThroughput(null);
for (IListenRoutingUpdates ra : this.routingAware) {
try {
ra.recalculateDone();
} catch (Exception ex) {
log.error("
Exception on routingAware listener call", ex);
}
}
}
}
private void updateEdgeUtilization() {
log.debug("UpdateEdgeUtilization called");
clearMaxThroughput();
mtp = null;
init
MaxThroughput(null);
}
/**
* Function called by the dependency manager when all the required
36
* dependencies are satisfied
*
*/
#SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
log.debug("Rout
ing init() is called");
this.topologyBWAware = (ConcurrentMap<Short, Graph<Node, Edge>>) new ConcurrentHashMap();
this.sptBWAware = (ConcurrentMap<Short, DijkstraShortestPath<Node, Edge>>) new ConcurrentHashMap();
// Now create the
default topology, which doesn't consider the
// BW, also create the corresponding Dijkstra calculation
Graph<Node, Edge> g = new SparseMultigraph();
Short sZero = Short.valueOf((short) 0);
this.topologyBWAware.put(sZero, g);
this.sptBWAware.put(sZero, new DijkstraShortestPath(g));
// Topologies for other BW will be added on a needed base
this.statMgr = new StatisticsManager();
this.lbRoutingTimer = new Timer();
this.lbRoutingTimerTask =
new TimerTask() {
#Override
public void run() {
updateEdgeUtilization();
}
};
}
/**
* Function called by the dependency manager when at least one dependency
* become unsati
sfied or when the component is shutting down because for
* example bundle is being stopped.
*
*/
void destroy() {
log.debug("Routing destroy() is called");
}
/**
* Function called by dependency manager after "init
()" is called and after
* the services provided by the class are registered in the service registry
*
*/
void start() {
log.debug("Routing start() is called");
// build the routing database from the topology if it exists
.
Map<Edge, Set<Property>> edges = topologyManager.getEdges();
if (edges.isEmpty()) {
return;
}
List<TopoEdgeUpdate> topoedgeupdateList = new ArrayList<TopoEdgeUpdate>();
log.debug("Creating routing datab
ase from the topology");
for (Iterator<Map.Entry<Edge, Set<Property>>> i = edges.entrySet()
.iterator(); i.hasNext();) {
Map.Entry<Edge, Set<Property>> entry = i.next();
Edge e = entry.getKey();
Set<Property> props = entry.getValue();
TopoEdgeUpdate topoedgeupdate = new TopoEdgeUpdate(e, props,
UpdateType.ADDED);
topoedgeupdateList.add(topoedgeupdate);
37
}
edgeUpdate(topoedgeupdateL
ist);
// StatsTimer is set to 10s
lbRoutingTimer.scheduleAtFixedRate(lbRoutingTimerTask, 0, 10000);
}
/**
* Function called by the dependency manager before the services exported by
* the component are unregistered,
this will be followed by a "destroy ()"
* calls
*
*/
public void stop() {
log.debug("Routing stop() is called");
}
#Override
public void edgeOverUtilized(Edge edge) {
// TODO Auto
-
generated method stub
}
#Override
public void edgeUtilBackToNormal(Edge edge) {
// TODO Auto
-
generated method stub
}
public void setSwitchManager(ISwitchManager switchManager) {
this.switchManager = switchManager;
}
public void unsetS
witchManager(ISwitchManager switchManager) {
if (this.switchManager == switchManager) {
this.switchManager = null;
}
}
public void setReadService(IReadService readService) {
this.readService = readService;
}
public void unsetReadService(IReadService readService) {
if (this.readService == readService) {
this.readService = null;
}
}
public void setTopologyManager(ITopologyManager tm) {
this.topologyManager = tm;
}
public void unsetTopologyManager(ITopologyManager tm) {
if (this.topologyManager == tm) {
this.topologyManager = null;
}
}
}

Related

JavaFX: Linking variables correctly for EventHandler (Timeline)

I need to set up a simulation of a nuclear power plant in JavaFX. The GUI is working perfectly, but I've got problems with getting the simulation run. I have to use a Timeline (as EventHandler) for this, the handler updates the radiation value in each cell every single tick. The radiation is displayed as a circle on each cell. The higher the radiation, the bigger should the circle be. For this, I made an if-else-statement.
The problem is: The if-statement cannot access the variables from the EventHandler. But this is necessary to update the circle size each tick. I already tried to put the if-statements right into the EventHandler, but then, no circles have been shown anymore on my GUI.
These are the three classes so far:
EDIT: I put the if-statements into the Event Handler, new code below.
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class NuclearPowerPlant extends Application {
private static final int HEIGHT = 50;
private static final int WIDTH = 55;
private static final int CELL_SIZE = 40;
#Override
public void start(Stage stage) {
stage.setScene(new Scene(createContent()));
stage.show();
}
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize((WIDTH - 40) * CELL_SIZE, (HEIGHT - 40) * CELL_SIZE); // Size of displayed window
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
Cell cell = new Cell(x, y);
root.getChildren().add(cell);
}
}
return root;
}
public static void main(String[] args) {
launch(args);
}
}
Cell:
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Duration;
public class Cell extends StackPane {
private static final int CELL_SIZE = 40;
int x;
int y;
private Rectangle cell;
private Circle radiation; // Radiation is displayed as a circle
int circlesize; // Size of the circle (the higher the radiation, the bigger the circle)
double radiationvalue = 5000; // Initializing of the radiation value of all cells at the beginning (air in all cells)
private Text symbol; // For Explosion
double activity;
double reflection;
public Cell(int x, int y) { // Konstruktor fuer die Zelle
setTranslateX(x * CELL_SIZE);
setTranslateY(y * CELL_SIZE);
cell = new Rectangle(CELL_SIZE - 2, CELL_SIZE - 2, Color.BLUE);
cell.setStroke(Color.WHITE);
EventHandler<ActionEvent> handlerUpdateRadiationvalue = event -> {
double newradiationvalue = activity + reflection * 500;
// System.out.println(newradiationvalue);
if (newradiationvalue < 1000) {
this.circlesize = 2;
} else if (newradiationvalue >= 1000 && newradiationvalue < 3000) {
this.circlesize = 5;
} else if (newradiationvalue >= 3000 && newradiationvalue < 5000) {
this.circlesize = 8;
} else if (newradiationvalue >= 5000 && newradiationvalue < 7000) {
this.circlesize = 11;
} else if (newradiationvalue >= 7000 && newradiationvalue < 9000) {
this.circlesize = 14;
} else if (newradiationvalue >= 9000 && newradiationvalue < 10000) {
this.circlesize = 18;
}
// Explosion:
else if (newradiationvalue >= 10000) {
circlesize = 0;
cell.setFill(Color.RED);
symbol = new Text("X");
symbol.setFont(Font.font(38));
}
};
KeyFrame keyframe = new KeyFrame(Duration.seconds(0.02), handlerUpdateRadiationvalue);
Timeline tl = new Timeline();
tl.getKeyFrames().addAll(keyframe);
tl.setCycleCount(Timeline.INDEFINITE);
tl.play();
radiation = new Circle(circlesize, Color.BLACK);
getChildren().add(cell);
if (radiationvalue < 10000) {
getChildren().add(radiation);
} else {
getChildren().add(symbol);
}
// Context Menu for material change:
ContextMenu contextMenu = new ContextMenu();
MenuItem air = new MenuItem("Luft");
air.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.AIR.getActivity();
reflection = Material.AIR.getReflection();
cell.setFill(Color.BLUE);
}
});
MenuItem uranium = new MenuItem("Uran");
uranium.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.URANIUM.getActivity();
reflection = Material.URANIUM.getReflection();
cell.setFill(Color.GREEN);
}
});
MenuItem lead = new MenuItem("Blei");
lead.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.LEAD.getActivity();
reflection = Material.LEAD.getReflection();
cell.setFill(Color.GREY);
}
});
MenuItem ruleblock = new MenuItem("Regelblock");
ruleblock.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
activity = Material.RULEBLOCK.getActivity();
reflection = Material.RULEBLOCK.getReflection();
cell.setFill(Color.YELLOW);
}
});
contextMenu.getItems().addAll(air, uranium, lead, ruleblock);
cell.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
#Override
public void handle(ContextMenuEvent event) {
contextMenu.show(cell, event.getScreenX(), event.getScreenY());
}
});
}
ENUM:
public enum Material {
AIR (0, 0.99),
URANIUM (1, 1.12),
LEAD (0, 0.7),
RULEBLOCK (0, 0.99);
double activity;
double reflection;
private Material(double activity, double reflection) {
this.activity = activity;
this.reflection = reflection;
}
double getActivity() {
return activity;
}
public void setActivity(double activity) {
this.activity = activity;
}
double getReflection() {
return reflection;
}
public void setReflection(double reflection) {
this.reflection = reflection;
}
}
The if statement always links to the global variable "radiationvalue" instead of the updated value in the event handler. If I try to access the 'newradiationvalue' in the if statement, I get an error that no such variable can be found (because the one in the Event Handler is not visible from outside).
Maybe someone can tell me how to access the variables in the event handler from outside the event handler?! And if it's not possible: How do I need to change my program to make this work as I want?
Thanks very much in advance!

Generic BST having trouble getting constructor to work

I have been given some code from my instructor and i need to implement several functions. I have added the insert method but I can not figure out how or what the constructor is looking for, I don't understand why this call to construct a tree is not working. Not very strong in java but understand the logic of a BST
public class BinaryTreeDriver {
public static void main(String[] args){
BinaryTree<Integer> numbers = new BinaryTree<>();
I am getting compiler error cannot infer type arguments BinaryTree<>
Copying rest of code below
public class BinaryTree<T extends Comparable<T>> {
private BinaryTreeNode<T> root; // the root of the tree
private BinaryTreeNode<T> cursor; // the current node
/**
* Constructor for initializing a tree with node
* being set as the root of the tree.
* #param node
*/
public BinaryTree(BinaryTreeNode<T> node) {
root = node;
}
/**
* Moves the cursor to the root.
*/
public void toRoot() {
cursor = root;
}
/**
* Returns the cursor node.
* #return cursor
*/
public BinaryTreeNode<T> getCursor() {
return cursor;
}
/**
* Sets the root to the provided node.
* ONLY USE IN THE DELETE METHOD
* #param node
*/
public void setRoot(BinaryTreeNode<T> node) {
root = node;
}
/**
* Checks if the tree node has a left child node
* #return true if left child exists else false
*/
public boolean hasLeftChild() {
return cursor.getLeft() != null;
}
/**
* Checks if the tree node has a right child node
* #return true if right child exists else false
*/
public boolean hasRightChild() {
return cursor.getRight() != null;
}
/**
* Move the cursor to the left child
*/
public void toLeftChild() {
cursor = cursor.getLeft();
}
/**
* Move the cursor to the right child
*/
public void toRightChild() {
cursor = cursor.getRight();
}
/**
* #return height of the tree
*/
public int height() {
if (root != null) {
return root.height();
} else {
return 0;
}
}
**/**
* Tree-Insert
*/
public boolean insert(T elem)
{
return insert(root, elem);
}
public boolean insert(BinaryTreeNode start, T elem)
{
if (start == null)
{
root = new BinaryTreeNode<T>(elem, null, null);
return true;
}
int comparison = start.getData().compareTo(elem);
if (comparison > 0)
{
if (start.getLeft() == null)
{
start.setLeft(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getLeft(), elem);
}
else if (comparison < 0)
{
if (start.getRight() == null)
{
start.setRight(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getRight(), elem);
}
else
{
return false;
}**
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
public String toString() {
if (root != null) {
return root.toStringPreOrder(".");
} else {
return "";
}
}
}
public class BinaryTreeNode<T extends Comparable<T>> {
private BinaryTreeNode<T> left; // the left child
private BinaryTreeNode<T> right; // the right child
private T data; // the data in this node
public BinaryTreeNode() {
this(null, null, null);
}
public BinaryTreeNode(T theData) {
this(theData, null, null);
}
public BinaryTreeNode(T theData, BinaryTreeNode<T> leftChild,
BinaryTreeNode<T> rightChild) {
data = theData;
left = leftChild;
right = rightChild;
}
public T getData() {
return data;
}
public BinaryTreeNode<T> getLeft() {
return left;
}
public BinaryTreeNode<T> getRight() {
return right;
}
public void setLeft(BinaryTreeNode<T> newLeft) {
left = newLeft;
}
public void setRight(BinaryTreeNode<T> newRight) {
right = newRight;
}
public void setData(T newData) {
data = newData;
}
public void preOrder() {
System.out.println(data);
if (left != null) {
left.preOrder();
}
if (right != null) {
right.preOrder();
}
}
public int height() {
int leftHeight = 0; // Height of the left subtree
int rightHeight = 0; // Height of the right subtree
int height = 0; // The height of this subtree
// If we have a left subtree, determine its height
if (left != null) {
leftHeight = left.height();
}
// If we have a right subtree, determine its height
if (right != null) {
rightHeight = right.height();
}
// The height of the tree rooted at this node is one more than the
// height of the 'taller' of its children.
if (leftHeight > rightHeight) {
height = 1 + leftHeight;
} else {
height = 1 + rightHeight;
}
// Return the answer
return height;
}
/**
* #param pathString
* #return the tree nodes in pre-order traversal
*/
public String toStringPreOrder(String pathString) {
String treeString = pathString + " : " + data + "\n";
if (left != null) {
treeString += left.toStringPreOrder(pathString + "L");
}
if (right != null) {
treeString += right.toStringPreOrder(pathString + "R");
}
return treeString;
}
}

SCALA: executing complete .sql file

I have a .sql script files and need to execute complete .sql file at once, I have found many related answers, where programmer reads file and execute query one by one.
I require to run .sql file all at-once, like picking up the file and executing in within SCALA.
Currently I am doing it with following code, copied it from copied it from:https://gist.github.com/joe776/831762, my Lead ask me to do it in simple way, instead of executing script line by line, it should get executed as .SQL file
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+";
private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER";
private final Connection connection;
private final boolean stopOnError;
private final boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor.
*
* #param connection
* #param autoCommit
* #param stopOnError
*/
public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
/**
* #param delimiter
* #param fullLineDelimiter
*/
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property.
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property.
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter).
*
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != autoCommit) {
connection.setAutoCommit(autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the connection passed in.
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
// Ignore to workaround a bug in Jakarta DBCP
}
} else {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
logWriter.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
Why did you tag "scala"?
To execute a whole sql file at once:
sql < myFile.sql
Edit: as Cyrille Corpet pointed out, you can perform this command directly via scala
import sys.process._
"sql < myfile.sql" !

Bukkit EntityExplode physics and regeneration of blocks

I am having this issue with my code where when a tnt or creeper explodes, blocks will fly everywhere but when the blocks have landed everything should regenerate but it dosen't. Anyone who has a conclusion?
Here is my code:
#EventHandler
void onExplode1(EntityExplodeEvent event) {
for(Block block : event.blockList()) {
if(block.getType() != Material.TNT) {
float x = -0.4F + (float) (Math.random() * 0.9D);
float y = -1.2F + (float) (Math.random() * 1.9D);
float z = -0.9F + (float) (Math.random() * 1.4D);
FallingBlock falling = block.getWorld().spawnFallingBlock(block.getLocation(), block.getType(), block.getData());
falling.setVelocity(new Vector(x, y, z));
falling.setDropItem(true);
block.setType(Material.AIR);
}
if(block.getType() != Material.AIR) {
final BlockState state = block.getState();
int delay;
if(block.getType().hasGravity()) {
delay = 80;
} else {
delay = 80 + (int)(Math.random()*60);
}
// Set block to air so that no blocks drop
block.setType(Material.AIR);
// Regenerate all the blocks in a random order
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
state.update(true, false);
}
}, delay);
}
}
}
}
I think you will have to store the Entitys you created and then get back the Locations... Here is an example code... It doesn't have to work as well as others but it's a try.
package me.mcplayhd.testt;
import java.util.HashMap;
import java.util.Iterator;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
public class ExplodeBlocks extends JavaPlugin implements Listener {
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
}
HashMap<FallingBlock, Location> blocks = new HashMap<FallingBlock, Location>();
#SuppressWarnings("deprecation")
#EventHandler
void onEntityExplode(EntityExplodeEvent e) {
Iterator<Block> bi = e.blockList().iterator();
while(bi.hasNext()) {
Block b = bi.next();
if(b.getType() != Material.TNT) {
bi.remove();
Material m = b.getType();
byte d = b.getData();
b.setType(Material.AIR);
float x = -0.4F + (float) (Math.random() * 0.9D);
float y = -1.2F + (float) (Math.random() * 1.9D);
float z = -0.9F + (float) (Math.random() * 1.4D);
FallingBlock falling = b.getWorld().spawnFallingBlock(b.getLocation(), m, d);
falling.setVelocity(new Vector(x, y, z));
falling.setDropItem(false);
blocks.put(falling, b.getLocation());
}
}
}
#EventHandler
public void onEntityDamage(EntityDamageEvent e) {
if(e.getEntity() instanceof FallingBlock) {
FallingBlock fb = (FallingBlock) e.getEntity();
if(blocks.containsKey(fb)) {
e.setCancelled(true);
}
}
}
#SuppressWarnings("deprecation")
#EventHandler
public void onEneityDeath(EntityDeathEvent e) {
if(e.getEntity() instanceof FallingBlock) {
FallingBlock fb = (FallingBlock) e.getEntity();
if(blocks.containsKey(fb)) {
Location loc = blocks.get(fb);
loc.getBlock().setType(fb.getMaterial());
loc.getBlock().setData(fb.getBlockData());
blocks.remove(fb);
fb.remove();
}
}
}
#SuppressWarnings("deprecation")
#EventHandler
public void onEntityChangeBlock(EntityChangeBlockEvent e) {
if(e.getEntity() instanceof FallingBlock) {
FallingBlock fb = (FallingBlock) e.getEntity();
if(blocks.containsKey(fb)) {
e.setCancelled(true);
Location loc = blocks.get(fb);
loc.getBlock().setType(fb.getMaterial());
loc.getBlock().setData(fb.getBlockData());
blocks.remove(fb);
fb.remove();
}
}
}
}
The problem is it doesn't work 100% but most of the blocks will be restored. The others I don't know, but I think you will find the cause...
Sry if this doesn't help at all

KeyTyped being called twice in this code?

There is a bug somewhere here. For some reason, when I am sending the message to the server, every message is received twice for any single keystroke! for instance, i type "a", and the server receives "INSERT 0 1 a" "INSERT 0 1 a". I'm not sure why it happens twice do you know?
package client;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class JTextAreaListen extends JFrame implements KeyListener,
CaretListener {
private static final long serialVersionUID = 6950001634065526391L;
private JTextArea textArea;
protected final PrintWriter out;
protected final int id;
protected final BufferedReader in;
protected static int caretPos;
private static int cMark;
protected static boolean text_selected;
/*
* Connecting to server. (1337 is the port we are going to use).
*
* socket = new Socket(InetAddress.getByName("127.0.0.1"), 1337);
*
* (Open a new outStream, you can save this instead of opening on every time
* you want to send a message. If the connection is lost your should to
* out.close();
*
* out = new PrintWriter(socket.getOutputStream(), true);
*
* out.print("message"); to send something to the server.
*/
public JTextAreaListen(PrintWriter out, BufferedReader in, int id) {
super("JTextAreaListen");
this.id = id;
this.out = out;
this.in = in;
TextEditor.document.addCaretListener(this);
TextEditor.document.addKeyListener(this);
}
// Listener methods
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
#Override
public void keyPressed(KeyEvent arg0) {
System.out.print("KeyPressedd");
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent ev) {
System.out.println(ev.KEY_PRESSED);
System.out.println("Sth happening!");
System.out.println(ev.getKeyCode());
int evID = ev.getID();
String keyString;
int keyCode;
if (evID == KeyEvent.KEY_TYPED) {
if (ev.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
keyCode = ev.getKeyCode();
if (keyCode == 8) {
if (text_selected) {
if (caretPos > cMark) {
for (int i = caretPos; i >= cMark; i--) {
System.out.println("sm1");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
} else if (caretPos < cMark) {
for (int i = caretPos; i >= cMark; i++) {
System.out.println("sm2");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
}
} else {
System.out.println("sm3");
sendMessage("DELETE" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos + 1));
}
}
} else {
char c = ev.getKeyChar();
boolean capital = ev.isShiftDown();
String charString = String.valueOf(c);
if (capital) {
charString.toUpperCase();
}
if (text_selected) {
if (caretPos > cMark) {
for (int i = caretPos; i >= cMark; i--) {
System.out.println("sm4");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(cMark + 1));
}
System.out.println("sm5");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(cMark) + " " + charString);
} else if (caretPos < cMark) {
for (int i = caretPos; i >= cMark; i++) {
System.out.println("sm6");
sendMessage("DELETE" + " " + String.valueOf(id)
+ " " + String.valueOf(caretPos + 1));
}
System.out.println("sm7");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos) + " " + charString);
}
} else {
System.out.println("sm8");
sendMessage("INSERT" + " " + String.valueOf(id) + " "
+ String.valueOf(caretPos) + " " + charString);
}
}
}
}
public void sendMessage(String s) {
System.out.println("smReal");
out.println(s);
}
#Override
public void caretUpdate(CaretEvent cev) {
int dot = cev.getDot();
int mark = cev.getMark();
caretPos = dot;
cMark = mark;
if (dot == mark) {
text_selected = false;
} else if ((dot < mark) | (dot > mark)) {
text_selected = true;
}
}
}
Here is the code for the client containing the TextArea which calls this Listener.
package client;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.text.DefaultEditorKit;
public class TextEditor extends JFrame {
private static final long serialVersionUID = 5991470239888613993L;
protected static JTextArea document = new JTextArea(20, 120);
private JFileChooser dialog = new JFileChooser(
System.getProperty("user.dir"));
private String currentFile = "Untitled";
private boolean changed = false;
private int id;
private final BufferedReader in;
private final PrintWriter out;
public TextEditor(final PrintWriter out, final BufferedReader in, int id) {
this.out = out;
this.in = in;
this.id = id;
document.setFont(new Font("Monospaced", Font.PLAIN, 12));
JScrollPane scroll = new JScrollPane(document,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.add(scroll, BorderLayout.CENTER);
JMenuBar JMB = new JMenuBar();
this.setJMenuBar(JMB);
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMB.add(file);
JMB.add(edit);
file.add(Open);
file.add(Save);
file.add(Quit);
file.add(SaveAs);
file.addSeparator();
for (int i = 0; i < 4; i++)
file.getItem(i).setIcon(null);
edit.add("Cut");
edit.add("Copy");
edit.add("Paste");
edit.getItem(0).setText("Cut");
edit.getItem(1).setText("Copy");
edit.getItem(2).setText("Paste");
JToolBar tool = new JToolBar();
this.add(tool, BorderLayout.NORTH);
tool.add(Open);
tool.add(Save);
tool.addSeparator();
JButton cut = tool.add(Cut), copy = tool.add(Copy), paste = tool
.add(Paste);
cut.setText(null);
cut.setIcon(new ImageIcon("cut.png"));
copy.setText(null);
copy.setIcon(new ImageIcon("copy.png"));
paste.setText(null);
paste.setIcon(new ImageIcon("paste.png"));
Save.setEnabled(false);
SaveAs.setEnabled(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
document.addKeyListener(new JTextAreaListen(out, in, id));
setTitle(currentFile);
setVisible(true);
final int id2 = id;
Thread t = new Thread(new Runnable() {
public void run() {
out.println("GET " + id2);
while (true) {
out.println("GET " + id2);
String line = null;
do {
try {
line = in.readLine();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Connection Lost", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(-1);
}
} while (line == null);
int temp = JTextAreaListen.caretPos;
document.setText(line);
document.setCaretPosition(temp);
}
}
});
t.start();
}
private KeyListener keyPressed = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
changed = true;
Save.setEnabled(true);
SaveAs.setEnabled(true);
}
};
Action Open = new AbstractAction("Open", new ImageIcon("open.png")) {
private static final long serialVersionUID = -474289105133169886L;
public void actionPerformed(ActionEvent e) {
saveOld();
if (dialog.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
readInFile(dialog.getSelectedFile().getAbsolutePath());
}
SaveAs.setEnabled(true);
}
};
Action Save = new AbstractAction("Save", new ImageIcon("save.png")) {
private static final long serialVersionUID = 2064233284536910855L;
public void actionPerformed(ActionEvent e) {
if (!currentFile.equals("Untitled"))
saveFile(currentFile);
else
saveFileAs();
}
};
Action SaveAs = new AbstractAction("Save as...") {
private static final long serialVersionUID = -5473532525926088880L;
public void actionPerformed(ActionEvent e) {
saveFileAs();
}
};
Action Quit = new AbstractAction("Quit") {
private static final long serialVersionUID = -5339245808869817726L;
public void actionPerformed(ActionEvent e) {
saveOld();
System.exit(0);
}
};
ActionMap m = document.getActionMap();
Action Cut = m.get(DefaultEditorKit.cutAction);
Action Copy = m.get(DefaultEditorKit.copyAction);
Action Paste = m.get(DefaultEditorKit.pasteAction);
private void saveFileAs() {
if (dialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
saveFile(dialog.getSelectedFile().getAbsolutePath());
}
private void saveOld() {
if (changed) {
if (JOptionPane.showConfirmDialog(this, "Save " + currentFile
+ " ?", "Save", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
saveFile(currentFile);
}
}
private void readInFile(String fileName) {
try {
FileReader r = new FileReader(fileName);
document.read(r, null);
r.close();
currentFile = fileName;
setTitle(currentFile);
changed = false;
} catch (IOException e) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(this, "Could not find " + fileName);
}
}
private void saveFile(String fileName) {
try {
FileWriter w = new FileWriter(fileName);
document.write(w);
w.close();
currentFile = fileName;
setTitle(currentFile);
changed = false;
Save.setEnabled(false);
} catch (IOException e) {
JOptionPane
.showMessageDialog(this,
"An error has occurred. Your document may not have been saved");
}
}
}