air process adt flex - air

I have two air applications and installed them in desktop and executed them and two air processes are listed in taskbar manager.Now how can I execute some method of one air application from another air application?

Use LocalConnection.
You can Host a Connection in one AIR application and connect from the the other AIR guy... From there - you can call methods.
BEWARE: LocalConnection can be a little tricky and odd (for example, connections are global and the names can't overlap).
From the Example Doc listed above....
// Code in LocalConnectionSenderExample.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.LocalConnection;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.StatusEvent;
import flash.text.TextFieldAutoSize;
public class LocalConnectionSenderExample extends Sprite {
private var conn:LocalConnection;
// UI elements
private var messageLabel:TextField;
private var message:TextField;
private var sendBtn:Sprite;
public function LocalConnectionSenderExample() {
buildUI();
sendBtn.addEventListener(MouseEvent.CLICK, sendMessage);
conn = new LocalConnection();
conn.addEventListener(StatusEvent.STATUS, onStatus);
}
private function sendMessage(event:MouseEvent):void {
conn.send("myConnection", "lcHandler", message.text);
}
private function onStatus(event:StatusEvent):void {
switch (event.level) {
case "status":
trace("LocalConnection.send() succeeded");
break;
case "error":
trace("LocalConnection.send() failed");
break;
}
}
private function buildUI():void {
const hPadding:uint = 5;
// messageLabel
messageLabel = new TextField();
messageLabel.x = 10;
messageLabel.y = 10;
messageLabel.text = "Text to send:";
messageLabel.autoSize = TextFieldAutoSize.LEFT;
addChild(messageLabel);
// message
message = new TextField();
message.x = messageLabel.x + messageLabel.width + hPadding;
message.y = 10;
message.width = 120;
message.height = 20;
message.background = true;
message.border = true;
message.type = TextFieldType.INPUT;
addChild(message);
// sendBtn
sendBtn = new Sprite();
sendBtn.x = message.x + message.width + hPadding;
sendBtn.y = 10;
var sendLbl:TextField = new TextField();
sendLbl.x = 1 + hPadding;
sendLbl.y = 1;
sendLbl.selectable = false;
sendLbl.autoSize = TextFieldAutoSize.LEFT;
sendLbl.text = "Send";
sendBtn.addChild(sendLbl);
sendBtn.graphics.lineStyle(1);
sendBtn.graphics.beginFill(0xcccccc);
sendBtn.graphics.drawRoundRect(0, 0,
(sendLbl.width + 2 + hPadding + hPadding), (sendLbl.height + 2), 5, 5);
sendBtn.graphics.endFill();
addChild(sendBtn);
}
}
}
// Code in LocalConnectionReceiverExample.as
package {
import flash.display.Sprite;
import flash.net.LocalConnection;
import flash.text.TextField;
public class LocalConnectionReceiverExample extends Sprite {
private var conn:LocalConnection;
private var output:TextField;
public function LocalConnectionReceiverExample() {
buildUI();
conn = new LocalConnection();
conn.client = this;
try {
conn.connect("myConnection");
} catch (error:ArgumentError) {
trace("Can't connect...the connection name is already
being used by another SWF");
}
}
public function lcHandler(msg:String):void {
output.appendText(msg + "\n");
}
private function buildUI():void {
output = new TextField();
output.background = true;
output.border = true;
output.wordWrap = true;
addChild(output);
}
}
}

Related

TornadoFx Undecorated window goes fullscreen when restored from task bar

I've been trying out Tornadofx. trying to create a custom title-bar, here's the code I'm currently trying
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp : App(Title::class) {
override fun start(stage: Stage) {
stage.initStyle(StageStyle.UNDECORATED)
stage.minWidth = 600.0
stage.minHeight = 450.0
stage.isMaximized = false
super.start(stage)
}
}
class Title : View() {
private var xOffset = 0.0
private var yOffset = 0.0
private var screenBounds: Rectangle2D = Screen.getPrimary().visualBounds
private var originalBounds: Rectangle2D = Rectangle2D.EMPTY
init {
primaryStage.isMaximized = false
}
override val root = borderpane {
onMousePressed = EventHandler { ev ->
xOffset = primaryStage.x - ev.screenX
yOffset = primaryStage.y - ev.screenY
}
onMouseDragged = EventHandler { ev ->
primaryStage.x = xOffset + ev.screenX
primaryStage.y = yOffset + ev.screenY
}
center = label("Forms")
right = hbox {
button("Mi") {
action {
with(primaryStage) { isIconified = true }
}
}
button("Ma") {
action {
if (primaryStage.isMaximized) {
with(primaryStage) {
x = originalBounds.minX
y = originalBounds.minY
width = originalBounds.width
height = originalBounds.height
isMaximized = false
}
text = "Ma"
} else {
with(primaryStage) {
originalBounds = Rectangle2D(x, y, width, height)
x = screenBounds.minX
y = screenBounds.minY
width = screenBounds.width
height = screenBounds.height
isMaximized = true
}
text = "Re"
}
}
}
button("X") {
action {
app.stop()
println("exiting")
exitProcess(0)
}
}
}
}
}
the following work without problems
close
maximize, restore
restored window minimized, then open from taskbar
but when a maximized window is minimized to taskbar, then open from taskbar, it goes full screen(taskbar is hidden)
how do i fix this behavior, is there any part of my code that is wrong, needs change, or in need of any inclusions?
my configuration is Windows 10 64bit, Java 11.0.2, Kotlin 1.4.21, JavaFx 11.0.2, TornadoFx 1.7.20
I think this is a general problem in JavaFX (I mean not specific with TornadoFX).
The root cause for this is because of setting the maximized property of stage to true. Not sure what JavaFX internally does, but when you open the window from task bar and if the maximized value is true, then it renders in full screen mode.
You can fix this in two ways.
Approach #1:
When the window is opened from task bar, the iconfied property will turn off, set the stage dimensions again to screen bounds if maximized is true.
primaryStage.iconifiedProperty().addListener((obs,old,iconified)->{
if(!iconified && primaryStage.isMaximized()){
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
}
});
Approach #2:
Don't rely on the maximized property of the Stage. I believe you need that property to toggle the window dimensions. So instead maintain a instance variable to handle that.
boolean maximized = false;
ma.setOnAction(e -> {
if (maximized) {
// Set stage to original bounds
maximized = false;
ma.setText("Ma");
} else {
// Set stage to screen bounds
maximized = false;
ma.setText("Re");
}
});
A full working demo is below with both the approaches. You can decide which way to go based on your other requirments.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class UndecoratedWindowFullScreenDemo extends Application {
private double xOffset = 0.0;
private double yOffset = 0.0;
private Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
private Rectangle2D originalBounds = Rectangle2D.EMPTY;
private boolean maximized = false;
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color:pink;");
Scene scene = new Scene(root, 600, 450);
primaryStage.setScene(scene);
Label label = new Label("Forums");
Button mi = new Button("Mi");
Button ma = new Button("Ma");
Button x = new Button("X");
HBox pane = new HBox(mi, ma, x);
pane.setPadding(new Insets(3));
pane.setSpacing(5);
root.setCenter(label);
root.setRight(pane);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setMinWidth(600);
primaryStage.setMinHeight(450);
primaryStage.setMaximized(false);
primaryStage.show();
root.setOnMousePressed(e -> {
xOffset = primaryStage.getX() - e.getScreenX();
yOffset = primaryStage.getY() - e.getScreenY();
});
root.setOnMouseDragged(e -> {
primaryStage.setX(xOffset + e.getScreenX());
primaryStage.setY(yOffset + e.getScreenY());
});
mi.setOnAction(e -> primaryStage.setIconified(true));
/* Use this approach if you want to go with the Stage maximized property */
// approach1(primaryStage, ma);
/* Use this approach if you want to avoid Stage maximized property and maintain a instance variable */
approach2(primaryStage, ma);
}
private void approach1(Stage primaryStage, Button ma) {
primaryStage.iconifiedProperty().addListener((obs, old, iconified) -> {
if (!iconified && primaryStage.isMaximized()) {
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
}
});
ma.setOnAction(e -> {
if (primaryStage.isMaximized()) {
primaryStage.setX(originalBounds.getMinX());
primaryStage.setY(originalBounds.getMinY());
primaryStage.setWidth(originalBounds.getWidth());
primaryStage.setHeight(originalBounds.getHeight());
primaryStage.setMaximized(false);
ma.setText("Ma");
} else {
originalBounds = new Rectangle2D(primaryStage.getX(), primaryStage.getY(), primaryStage.getWidth(), primaryStage.getHeight());
primaryStage.setX(screenBounds.getMinX());
primaryStage.setY(screenBounds.getMinY());
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
primaryStage.setMaximized(true);
ma.setText("Re");
}
});
}
private void approach2(Stage primaryStage, Button ma) {
ma.setOnAction(e -> {
if (maximized) {
primaryStage.setX(originalBounds.getMinX());
primaryStage.setY(originalBounds.getMinY());
primaryStage.setWidth(originalBounds.getWidth());
primaryStage.setHeight(originalBounds.getHeight());
maximized = false;
ma.setText("Ma");
} else {
originalBounds = new Rectangle2D(primaryStage.getX(), primaryStage.getY(), primaryStage.getWidth(), primaryStage.getHeight());
primaryStage.setX(screenBounds.getMinX());
primaryStage.setY(screenBounds.getMinY());
primaryStage.setWidth(screenBounds.getWidth());
primaryStage.setHeight(screenBounds.getHeight());
maximized = true;
ma.setText("Re");
}
});
}
}
There are two changes that were needed to solve the problem
The actual problem was that if isMaximized is set to true the app goes full screen when being open from task(minimized) even though isFullScreen property is separately available
Adding a maximized property listener so that we can invalidate if the isMaximized were to be ever modified by other means(like double clicking on title bar in Linux etc)
// CHANGE 1
stage.maximizedProperty().addListener { _, _, newValue ->
if (newValue) stage.isMaximized = false
}
by having a separate maximized instead of using isMaximized
// CHANGE 2
private var maximized: Boolean = false // <- here
if (maximized) { // <- here
// restore the window by setting bounds of original size
maximized = false // <- here
text = "Ma"
} else {
// maximize window by setting bounds from screen size
maximized = true // <- and here
text = "Re"
}
Bonus : use isFocusTraversable = false to make buttons that don't focus with keyboard traversal
Final solution
fun main(args: Array<String>) {
launch<MyApp>(args)
}
class MyApp : App(Window::class, Styles::class) {
override fun start(stage: Stage) {
stage.initStyle(StageStyle.UNDECORATED)
stage.minWidth = 600.0
stage.minHeight = 450.0
stage.width = 600.0
stage.height = 450.0
// CHANGE 1
stage.maximizedProperty().addListener { _, _, newValue ->
if (newValue) stage.isMaximized = false
}
stage.isMaximized = false
super.start(stage)
}
}
class Window : View() {
override val root = borderpane {
top = Title().root
}
}
class Title : View() {
// CHANGE 2
private var maximized: Boolean = false // <- here
private var xOffset = 0.0
private var yOffset = 0.0
private var screenBounds: Rectangle2D = Screen.getPrimary().visualBounds
private var originalBounds: Rectangle2D = Rectangle2D.EMPTY
init {
primaryStage.isMaximized = false
}
override val root = hbox {
hgrow = Priority.ALWAYS
onMousePressed = EventHandler { ev ->
xOffset = primaryStage.x - ev.screenX
yOffset = primaryStage.y - ev.screenY
}
onMouseDragged = EventHandler { ev ->
primaryStage.x = xOffset + ev.screenX
primaryStage.y = yOffset + ev.screenY
}
val l1 = hbox {
hgrow = Priority.ALWAYS
alignment = Pos.CENTER
label("Forms")
}
add(l1)
l1.requestFocus()
button("Mi") {
id = "min"
action {
with(primaryStage) { isIconified = true }
}
isFocusTraversable = false
}
button("Ma") {
id = "max"
action {
if (maximized) { // <- here
with(primaryStage) {
x = originalBounds.minX
y = originalBounds.minY
width = originalBounds.width
height = originalBounds.height
maximized = false // <- here
}
text = "Ma"
} else {
with(primaryStage) {
originalBounds = Rectangle2D(x, y, width, height)
x = screenBounds.minX
y = screenBounds.minY
width = screenBounds.width
height = screenBounds.height
maximized = true // <- and here
}
text = "Re"
}
l1.requestFocus()
}
isFocusTraversable = false
}
button("X") {
id = "close"
action {
app.stop()
println("exiting")
exitProcess(0)
}
isFocusTraversable = false
}
}
}

managed c++ classes crash in create_task

Basically, what is happening is when trying to change a variable of a Managed class (UWP), it crashes. Additionally, it seems to only crash if I try modifying a variable which is created with the app namespace. In other words, if I create a new namspace and managed class, I can modify variables just fine.
void ASynTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
create_task([taskDone, responseItem, rootPage]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
UberSnipAPI->Http->request();
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
});
This does not crash
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
but this one does
all_item->Title = "All";
I am almost positive it has something to do with it being in the apps default namespace and it being accessed outside of the main thread ... At least that's what it seems like as that's really the only difference besides the actual class.
This is what GENERIC_ITEM looks like.
[Windows::UI::Xaml::Data::Bindable]
public ref class GENERIC_ITEM sealed {
private:
Platform::String^ _title = "";
Platform::String^ _description;
Windows::UI::Xaml::Media::ImageSource^ _Image;
event PropertyChangedEventHandler^ _PropertyChanged;
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChangedEventArgs^ pcea = ref new PropertyChangedEventArgs(propertyName);
_PropertyChanged(this, pcea);
}
public:
GENERIC_ITEM() {
};
property Platform::String^ Title {
Platform::String^ get() {
return this->_title;
}
void set(Platform::String^ val) {
this->_title = val;
OnPropertyChanged("Title");
}
}
property Platform::String^ Description {
Platform::String^ get() {
return this->_description;
}
void set(Platform::String^ val) {
this->_description = val;
OnPropertyChanged("Description");
}
}
void SetImage(Platform::String^ path)
{
Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(path);
_Image = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage(uri);
}
};
I know there is no issue with the class because it works perfectly fine if I run this exact same code on the initial thread.
Any suggestions? Thanks! :D
Figured it out after several hours! In case someone else is having this issue, all you must do is use the Dispatcher to run code on the UI that is not available outside of the UI thread.
void loadCats(UberSnip::HELPER::ASYNC_RESPONSE^ responseItem, MainPage^ rootPage) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
}
void ASyncTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
auto dispatch = CoreWindow::GetForCurrentThread()->Dispatcher;
auto op2 = create_async([taskDone, responseItem, rootPage, dispatch] {
return create_task([taskDone, responseItem, rootPage, dispatch]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
try{
UberSnipAPI->Http->request();
}
catch (...) {
printf("Error");
}
int err = UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).find("__api_err");
if (err < 0) {
if (UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).length() < 3) {
return;
}
}
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
dispatch->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]()
{
rootPage->loadCats(responseItem, rootPage);
}));
for (int i = 0; i < 100;) {
}
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
});
});
//rootPage->loadCats(responseItem, rootPage);
}

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

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;
}
}
}

ActionScript 2: Event doesn't fire?

So I have a soundHandler class that's supposed to play sounds and then point back to a function on the timeline when the sound has completed playing. But somehow, only one of the sounds plays when I try it out. EDIT: After that sound plays, nothing happens, even though I have EventHandlers set up that are supposed to do something.
Here's the code:
import mx.events.EventDispatcher;
class soundHandler {
private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
var soundToPlay;
var soundpath:String;
var soundtype:String;
var prefix:String;
var mcname:String;
public function soundHandler(soundpath:String, prefix:String, soundtype:String, mcname:String) {
EventDispatcher.initialize(this);
_root.createEmptyMovieClip(mcname, 1);
this.soundpath = soundpath;
this.soundtype = soundtype;
this.prefix = prefix;
this.mcname = mcname;
}
function playSound(file, callbackfunc) {
_root.soundToPlay = new Sound(_root.mcname);
_global.soundCallbackfunc = callbackfunc;
_root.soundToPlay.onLoad = function(success:Boolean) {
if (success) {
_root.soundToPlay.start();
}
};
_root.soundToPlay.onSoundComplete = function():Void {
trace("Sound Complete: "+this.soundtype+this.prefix+this.file+".mp3");
trace(arguments.caller);
dispatchEvent({type:_global.soundCallbackfunc});
trace(this.toString());
trace(this.callbackfunction);
};
_root.soundToPlay.loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root.soundToPlay.stop();
}
}
Here's the code from the .fla file:
var playSounds:soundHandler = new soundHandler("signup", "su", "s", "mcs1");
var file = "000";
playSounds.addEventListener("sixtyseconds", this);
playSounds.addEventListener("transition", this);
function sixtyseconds() {
trace("I am being called! Sixtyseconds");
var phase = 1;
var file = random(6);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSounds.playSound(file, "transition");
}
function transition() {
trace("this works");
}
playSounds.playSound(file, "sixtyseconds");
I'm at a total loss for this one. Have been wasting hours to figure it out already.
Any help will be deeply appreciated.
Well, after using the Delegate class, I got it to work with this code:
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class soundHandler{
public var addEventListener:Function;
public var removeEventListener:Function;
private var dispatchEvent:Function;
private var soundToPlay;
private var soundpath:String;
private var soundtype:String;
private var prefix:String;
private var mcname:String;
public function soundHandler(soundpath:String, prefix:String, soundtype:String, mcname:String) {
EventDispatcher.initialize(this);
_root.createEmptyMovieClip(mcname, 1);
this.soundpath = soundpath;
this.soundtype = soundtype;
this.prefix = prefix;
this.mcname = mcname;
}
private function playSoundCallback(file, callbackfunc) {
var soundname = "s"+file;
_root[soundname] = new Sound(_parent.mcname);
_root[soundname].onLoad = function(success:Boolean) {
if (success) {
_root[soundname].start();
}
};
trace("Play Sound: "+file+".mp3; Function To Call: "+callbackfunc);
_root[soundname].onSoundComplete = Delegate.create(this,function():Void {
trace("Sound Complete: "+this.soundtype+this.prefix+this.file+".mp3");
dispatchEvent({type:callbackfunc});
});
_root[soundname].loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root[soundname].stop();
}
private function playRandomSoundCallback(phase, scope, callbackfunc) {
var file = random(scope);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSoundCallback(file, callbackfunc);
}
private function playSound(file) {
var soundname = "s"+file;
_root[soundname] = new Sound(_root.mcname);
_root[soundname].onLoad = function(success:Boolean) {
if (success) {
_root[soundname].start();
}
};
trace("Play Sound: "+file+".mp3");
_root[soundname].loadSound("../sound/"+soundpath+"/"+soundtype+prefix+file+".mp3", true);
_root[soundname].stop();
}
private function playSoundRandom(phase, scope) {
var file = random(scope);
if (file == 0) {
file = 1;
}
if (file<10) {
file = "0"+file;
}
file = phase+file;
playSound(file);
}
private function playSoundAS(identifier) {
var soundname = identifier;
_root[soundname] = new Sound(_root.mcname);;
trace("Play Sound AS: "+identifier+".mp3");
_root[soundname].attachSound("identifier");
_root[soundname].start();
}
}

JPanel not updating when my ArrayList of GamePieces changes

I have a simple game that is in progress. As of right now all I want to do is click the green button and have the fifth and third pieces switch places. The paintComponent is called after the swap in the arraylist is made, but the JPanel is not refreshed to show these changes. When i am running my application I am choosing 4 for the pieces for each side. Thus, the inner green and black pieces should change place. Please help.
Number1.java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.Container;
public class Number1 {
private static JButton greenButton,blackButton,newGameButton,inputButton;
private static JTextFieldNumber inputField;
static MyActionListen actionListen;
static Number1 myGame;
static JFrame myDialog,myFrame;
static DrawGamePieces gamePanel;
public int piecesPerSide = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
myGame = new Number1();
actionListen = new MyActionListen();
myGame.getStartingTokensValue();
System.out.println(Color.WHITE.toString());
}
private void makeComponents()
{
//Setting up the green button click
greenButton = new JButton("Green");
greenButton.setBounds(40, 0 , 100, 40);
greenButton.setForeground(Color.GREEN);
greenButton.addActionListener(actionListen);
//Setting up the black button click
blackButton = new JButton("Black");
blackButton.setBounds(greenButton.getLocation().x + greenButton.getWidth() + 10
, 0 , 100, 40);
blackButton.setForeground(Color.BLACK);
blackButton.addActionListener(actionListen);
//Setting up the new game button click
newGameButton = new JButton("New Game");
newGameButton.setBounds(blackButton.getLocation().x + blackButton.getWidth() + 10
, 0 , 100, 40);
newGameButton.setForeground(Color.BLUE);
newGameButton.addActionListener(actionListen);
//init gamePanel
gamePanel = new DrawGamePieces(myGame.piecesPerSide,myFrame.getSize().width, myFrame.getSize().height - 40);
gamePanel.setLocation(0, 40);
gamePanel.setBackground(Color.YELLOW);
}
private void makeGameFrame()
{
myFrame = new JFrame();
if(myGame.piecesPerSide <= 10) myFrame.setSize(400, 250);
else myFrame.setSize(600, 250);
myFrame.setLocation(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
myFrame.setTitle("Solitary Game"); //sets the title of the window
Container mainFrameContents = myFrame.getContentPane();//get the content pane to add components to
mainFrameContents.setLayout(null); //allowed setBounds on components to work properly
mainFrameContents.setBackground(Color.YELLOW);
myGame.makeComponents(); //makes all the sub components
//adds all subcomponents to content pane
mainFrameContents.add(greenButton);
mainFrameContents.add(blackButton);
mainFrameContents.add(newGameButton);
mainFrameContents.add(gamePanel);
myFrame.setVisible(true);
}
//gets the starting value of the tokens for the game
private void getStartingTokensValue()
{
myDialog = new JFrame("New Game Information");
myDialog.setSize(450, 150);
myDialog.setLocation(300, 100);
myDialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
JLabel l = new JLabel("Please Enter the Number of Pieces for each side of the game (1-20)");
l.setBounds((myDialog.getSize().width - 420)/2, 0, 420, 30);
inputField = new JTextFieldNumber("0123456789");
inputField.setBounds((myDialog.getSize().width - 100)/2, 35, 100, 30);
inputButton = new JButton("Submit");
inputButton.setBounds((myDialog.getSize().width - 100)/2, 75, 100, 30);
inputButton.addActionListener(actionListen);
myDialog.setLayout(null);
myDialog.add(inputButton);
myDialog.add(l);
myDialog.add(inputField);
myDialog.setVisible(true);
}
private static class MyActionListen implements ActionListener
{
public void actionPerformed(ActionEvent ap)
{
if(ap.getSource().equals(greenButton)){
System.out.println("Requet to green move");
gamePanel.greenMove();
}else if(ap.getSource().equals(blackButton)){
System.out.println("Requet to black move");
}else if(ap.getSource().equals(newGameButton)){
System.out.println("Requet to start new game");
}else if(ap.getSource().equals(inputButton)){
if(inputField.getText().length()>0)
{
myGame.piecesPerSide = Integer.parseInt(inputField.getText());
if(inputField.checkAllCharacters() && (myGame.piecesPerSide <= 20) && (myGame.piecesPerSide>0))
{
myDialog.dispose();
myGame.makeGameFrame();
}else{
JOptionPane.showMessageDialog(inputField, "Please only type in an integer from 1 to 20");
}
}
}
}
}
}
DrawGamePieces.java
import java.awt.*;
import java.util.ArrayList;
import javax.swing.JPanel;
public class DrawGamePieces extends JPanel{
private ArrayList<GamePiece> gamePieces;
private int ballR = 15;
//paint or repaints the board
protected void paintComponent( Graphics g ){
super.paintComponent(g);
System.out.println("paint components called");
for(int i=0;i<gamePieces.size();i++)
{
GamePiece temp = gamePieces.get(i);
g.setColor(temp.getColor());
g.fillOval(temp.x,temp.y,ballR,ballR);
}
}
//init the game board
public DrawGamePieces(int piecesPerSide,int aWidth,int aHeight){
gamePieces = new ArrayList<GamePiece>();
super.setSize(aWidth, aHeight);
//space between wall and first piece
int blankSpace = (int)((aWidth - (ballR)*(2*piecesPerSide+1))/2);
//initalized the pieces in the arraylist
for(int i=0;i<(2*piecesPerSide+1);i++)
{
GamePiece temp = null;
if(i == 0) temp = new GamePiece(blankSpace,80,Color.GREEN);
if((i < piecesPerSide) && (i != 0)) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.GREEN);
if(i > piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.BLACK);
if(i == piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.YELLOW);
gamePieces.add(temp);
}
}
public void greenMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
repaint();
}
public void blackMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
}
private int pieceMoveable(Color c){
int index = -1, start = 0, end = 0,change = 0;
if(c == Color.GREEN){
start = 0;
end = gamePieces.size();
change = 1;
}else{
start = gamePieces.size();
end = 0;
change = -1;
}
for (int i=start;i<end;i= i+change){
//if(change = )
}
return index;
}
}
GamePiece.java
import java.awt.Color;
import java.awt.Point;
public class GamePiece extends Point{
private Color pieceColor;
public Color getColor(){
return pieceColor;
}
public GamePiece()
{
super();
}
public GamePiece(int x,int y,Color aColor)
{
super(x,y);
pieceColor = aColor;
}
}
Add more printfs to get more information about what is happening. Inside greenMove(), print out the contents of the ArrayList after you do the swap. Do the same inside paintComponent. In the printf, also indicate where these debugging messages are being printed from. In the loop in printComponent, print out the location and color of each piece as you draw it.