Proper way to terminate thread
I'm trying to write chat application based on Sockets but I'm a bit confused, how to actually stop my server.
Here is my Server
constructor
public Server(int port) {
this.port = port;
this.shutdown = false;
this.clientComponentSet = new HashSet<>();
LOGGER.info("Starting the server...\n");
dbConnection = new DBConnection();
dbConnection.establish();
if(dbConnection.isConnected()) {
LOGGER.info("Established connection with database\n");
} else {
LOGGER.warn("Can't establish connection with database\n");
}
machineString = new SimpleStringProperty();
addressString = new SimpleStringProperty();
portString = new SimpleStringProperty();
status = new SimpleStringProperty();
status.set("Offline");
}
Then goes run
method
@Override
public void run() {
try {
serverSocket = new ServerSocket(port);
Platform.runLater(
() -> {
try {
machineString.set(serverSocket.getInetAddress().getLocalHost().getHostName());
addressString.set(serverSocket.getInetAddress().getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
LOGGER.error(e.toString());
}
portString.set(String.valueOf(this.port));
status.set("Online");
}
);
LOGGER.info("Server started\n");
while(!serverSocket.isClosed() && !shutdown) {
Socket clientSocket = serverSocket.accept();
ClientComponent clientComponent = new ClientComponent(this, clientSocket);
clientComponentSet.add(clientComponent);
clientComponent.start();
}
} catch (IOException e) {
LOGGER.error("Failed to start the server\n" + e.toString() + "\n");
}
}
and finnaly, method that should stop/close server
public void stopServer() {
try {
serverSocket.close();
shutdown = true;
LOGGER.info("Server stopped\n");
} catch (IOException e) {
LOGGER.error(e.toString());
}
}
Although, it isnt working as I expected. I start and then stop my server and logs are like this:
2018-03-17 12:48:01 INFO Starting the server...
2018-03-17 12:48:02 INFO Established connection with database
2018-03-17 12:48:03 INFO Server started
2018-03-17 12:48:04 INFO Server stopped
2018-03-17 12:48:04 ERROR Failed to start the server java.net.SocketException: socket closed
Trying to start server again now, will throw
Exception in thread "JavaFX Application Thread" java.lang.IllegalThreadStateException
How exactly can I stop/close my server then?
I actually forgot about my ServerController
class
public class ServerController {
final static Logger LOGGER = Logger.getLogger(ServerController.class);
private ServerController(){
}
private static ServerController instance = null;
public static ServerController getInstance() {
if(instance == null) {
instance = new ServerController();
}
return instance;
}
private Server server;
public void start() {
server = new Server(Integer.parseInt(Property.getByKey("SERVER_PORT")));
server.start();
if(!server.isAlive()) {
LOGGER.info("Server closed\n");
}
}
}
2 answers
-
answered 2018-03-17 11:56
Peter Lawrey
At least one confusing thing you can fix is that your ERROR will even if
closeServer()
is called.I suggest;
- you make
shutdown
volatile
- you always set it first
- you check whether the server was shutdown, and only print the error if it wasn't.
- don't assume the exception means it didn't start.
- always print the Exception with a stack trace to get the cause unless you are very confident it's not needed.
To restart a thread, you need to create a new one, to listen to a port after it has been closed, you need to create a new ServerSocket.
BTW You don't need to add extra new lines at the end of logs.
- you make
-
answered 2018-03-17 11:56
Dusty
You are receiving the "Server failed to start" message you close the ServerSocket while it is waiting for a connection to be established. The ServerSocket.accept method will block your thread until it receives some input. I believe the best way to solve this is to send it some "shutdown" signal when you wish to terminate the server. When the shutdown signal/message is received you can then safely close the ServerSocket and terminate your while loop.
See also questions close to this topic
-
Spring MVC: What's the right way to register custom Validator in REST controller
I'm trying to make sense of how validation works in Spring. So far I've learned that there are two ways to perform validation of user input data:
- JSR-303 validation based on
javax.validation.constraints
annotations. This validation is best suitable for simple object fields validation. But you can also implement your custom type level annotations to perform more complicated validation based on checking values of multiple fields. - Spring Validation based on
org.springframework.validation.Validator
interface. Seems to be better suited for more complicated validation.
If I want to use both these approaches, what is the right way to register my custom validator in controller?
This is what I'm trying to do.
My custom validator.
public class PasswordPairValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return PasswordPair.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { PasswordPair password = (PasswordPair) target; if (!password.getPassword().equals(password.getRepeatPassword())) { errors.reject("passwordField", "passwords don't match"); } } }
My controller.
@RestController @RequestMapping("/api/v1/users") public class UserController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.addValidators(new PasswordPairValidator()); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<UserInfo> createUser( @RequestBody @Valid UserInfo userInfo) { userInfo.setId(123); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(userInfo.getId()).toUri(); return ResponseEntity.created(location).body(userInfo); } @RequestMapping(value = "/change_password", method = RequestMethod.POST) public ResponseEntity<UserInfo> changePassword( @RequestBody @Valid PasswordPair password) { UserInfo user = new UserInfo("test@gmail.com", "testuser"); user.setId(123); return ResponseEntity.ok().body(user); } }
When I call
createUser
endpoint the code fails with the following error:ERROR c.e.testapp.controller.GlobalExceptionHandler - Internal Server Error java.lang.IllegalStateException: Invalid target for Validator [com.example.testapp.validation.PasswordPairValidator@49acd001]: com.example.testapp.domain.UserInfo@cae4750
The problem apparently is that Spring tries to apply
PasswordPairValidator
toUserInfo
object, which was not my intention. Why Spring doesn't use validator'ssupports()
method to check to which objects validator can be applied?
In a different stackoverflow question I found out that I need to specify value for@InitBinder
annotation to make it work and the value should be "passwordPair". But what is this value as it's not the class name ("PasswordPair") or method parameters value ("password")?The second question is if I want to add several validators do I need to define multiple
@InitBinder("value")
methods or is there a less cumbersome way to do it?And the final question, maybe it's better to use annotation based validation for everything, to validate separate fields and implement type level custom annotations with
ConstraintValidator
to perform more complicated validation? It's a bit confusing what are the pros and cons of these approaches. - JSR-303 validation based on
-
How to read from a ByteArrayInputStream with different Scanners?
I have a program that reads lines on System.in multiple times. Each time it reads a line, it creates a
Scanner
variable to read the line.For testing purposes, I want to set System.in to be a
ByteArrayInputStream
containing several lines before running the program. However when I do, only the firstScanner
can read from the stream, all subsequentScanner
instances connected to the stream fail.Here is a small example illustrating my problem:
import java.util.*; import java.io.*; public class SystemInTest { public static void main(String[] args) throws Exception { System.setIn(new ByteArrayInputStream("One\nTwo\nThree\nFour\n".getBytes())); Scanner sc; String s; // First Scanner reads first two lines (OK) sc = new Scanner(System.in); s = sc.nextLine(); System.out.println(s); s = sc.nextLine(); System.out.println(s); // Second Scanner fails on first read sc = new Scanner(System.in); s = sc.nextLine(); // fails with "java.util.NoSuchElementException: No line found" } }
Because I need to use this approach for testing, I would like a solution that doesn't change the fact that each read is done with a separate
Scanner
, and I can't change the input stream in between reads. I have to prepare everything, then launch the tested functions (that I cannot change) that will perform several reads, with differentScanner
instances. Is that possible? -
Redirection with UrlRewriteFilter
I am working on a Java web app hosted on a Tomcat server. I have to set up redirects from www to non-www and from http to https. I want the following three URLs:
to redirect to
For this purpose, I am using UrlRewriteFilter version 4.0.3 by tuckey.org. Here is my urlrewrite.xml file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd"> <urlrewrite> <rule> <name>Redirect www to non-www and http to https</name> <condition type="request-url" operator="equal">(^http://example.com|^http://www.example.com|^https://www.example.com)</condition> <from>^(.*)$</from> <to type="permanent-redirect" last="true">https://example.com$1</to> </rule> </urlrewrite>
The redirects work but the website does not load and the browser shows message:
This page isn’t working
example.com redirected you too many times.
I used a redirect checker and found out that after the initial redirect to https://example.com/, another redirect to https://example.com/ followed and then another one and so on – the URL redirects to itself. I don't understand what produces this infinite loop. Any help would be appreciated!
-
Connection Refused Error Coming At The Time Of Uploading Files From Local Machine To FTP Server
I am trying to upload files from local machine to ftp server and when this code starts first it store 6 folder data sucessfully on ftp server but from 7th folder to 25th folder i am getting connection refused error ... There is no limitation from client side for connections and only i am using these credentials for testing purpose . Can any one help me?
I am getting this issue because of mirror issue in code but i am not able to figureout this issue. Please help mepackage com.epath.smoketest.tests; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPSClient; public class FTPUploadDirectoryTest { public static void main(String[] args) { try { System.out.println("\n" + "---------------------------------------------------------------------------------" + "\r\n"); System.out.println("Read FTP Login details from PROPERTIES file" + "\r\n"); System.out.println( "---------------------------------------------------------------------------------" + "\r\n"); Properties prop = new Properties(); InputStream input = null; String inputFS = getAutomationInputDataPath() + "//Validation.properties"; input = new FileInputStream(inputFS); prop.load(input); // -Input file with test data System.out.println("Uploading file on ftp server"); String ftp_port = prop.getProperty("ftp_port"); int ftp_host = Integer.parseInt(prop.getProperty("ftp_host")); String ftp_username = prop.getProperty("ftp_username"); String ftp_password = prop.getProperty("ftp_password"); String server = ftp_port; int port = ftp_host; String user = ftp_username; String pass = ftp_password; FTPSClient ftpClient = new FTPSClient(); // connect and login to the server ftpClient.connect(server, port); ftpClient.login(user, pass); // use local passive mode to pass firewall ftpClient.enterLocalPassiveMode(); System.out.println("Connected"); String remoteDirPath = "/www/ngage/screenshots"; String localDirPath = folderPathForUploadingOnFTP; uploadDirectory(ftpClient, remoteDirPath, localDirPath, ""); // log out and disconnect from the server ftpClient.logout(); ftpClient.disconnect(); System.out.println("Disconnected"); } catch (IOException ex) { System.err.println("Error occured....." + ex.getMessage()); ex.printStackTrace(); } } public static void uploadDirectory(FTPSClient ftpClient, String remoteDirPath, String localParentDir, String remoteParentDir) throws IOException { File localDir = new File(localParentDir); File[] subFiles = localDir.listFiles(); if (subFiles != null && subFiles.length > 0) { for (File item : subFiles) { String remoteFilePath = remoteDirPath + "/" + remoteParentDir + "/" + item.getName(); if (remoteParentDir.equals("")) { remoteFilePath = remoteDirPath + "/" + item.getName(); } if (item.isFile()) { if (!checkFileExists(remoteFilePath, ftpClient)) { // upload the file String localFilePath = item.getAbsolutePath(); boolean uploaded = uploadSingleFile(ftpClient, localFilePath, remoteFilePath); if (uploaded) { System.out.println("UPLOADED a file to: " + remoteFilePath); } else { System.out.println("COULD NOT upload the file: " + localFilePath); } } else { System.out.println("This file alerady exist on ftp server "); } } else { // create directory on the server boolean created = ftpClient.makeDirectory(remoteFilePath); if (created) { System.out.println("CREATED the directory: " + remoteFilePath); } else { System.out.println("COULD NOT create the directory: " + remoteFilePath); } // upload the sub directory String parent = remoteParentDir + "/" + item.getName(); if (remoteParentDir.equals("")) { parent = item.getName(); } localParentDir = item.getAbsolutePath(); uploadDirectory(ftpClient, remoteDirPath, localParentDir, parent); } } } ftpClient.makeDirectory(remoteDirPath); } public static boolean uploadSingleFile(FTPSClient ftpClient, String localFilePath, String remoteFilePath) throws IOException { File localFile = new File(localFilePath); InputStream inputStream = new FileInputStream(localFile); try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return ftpClient.storeFile(remoteFilePath, inputStream); } finally { inputStream.close(); } } public static Boolean checkFileExists(String filePath, FTPSClient ftpClient) throws IOException { InputStream inputStream = ftpClient.retrieveFileStream(filePath); int returnCode = ftpClient.getReplyCode(); if (inputStream == null || returnCode == 550) { return false; } inputStream.close(); return true; } } Error coming . COULD NOT upload the file: \\192.168.10.21\volume1\ngage_dev\engineering\ngage\testing\automated\validation\Build_1.19.1\051\2018-04-23_07-54-39_AM\TC_UA_PSWD_0001_006_1.png java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:920) at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:627) at org.apache.commons.net.ftp.FTPClient._retrieveFileStream(FTPClient.java:1980) at org.apache.commons.net.ftp.FTPClient.retrieveFileStream(FTPClient.java:1967) at com.epath.smoketest.tests.FTPUploadDirectoryTest.checkFileExists(FTPUploadDirectoryTest.java:124)
-
Sending data from android to computer over hosted network
I've been trying to send data from an android device to a computer by hosting a virtual network on the computer and connecting the android device to it (basically sending data over WLAN).
However, upon debugging the android app it always throws the following exception:
System.Net.Sockets.SocketException (0x80004005): Network subsystem is down.
Android App Code Snippet:
namespace TestWifiApp { [Activity(Label = "TestWifiApp", MainLauncher = true)] public class MainActivity : Activity { string bssid = "00:18:39:12:2b:e9"; const string ssid = "TEST"; const string password = "123456abc"; const string kioskIp = "192.168.137.11"; const int kioskPort = 2201; void sendData(string ntlId) { try { System.Net.Sockets.Socket soc = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(kioskIp); System.Net.IPEndPoint ep = new System.Net.IPEndPoint(ipAdd, kioskPort); soc.Connect(ep); byte[] data = ASCIIEncoding.ASCII.GetBytes(ntlId); soc.Send(data); soc.Disconnect(false); soc.Close(); Log.Debug("TEST", "Data sent"); } catch(Exception ex) { Log.Debug("TEST",ex.ToString()); } } }
Server Code:
class Program { const int PORT_NO = 2201; static Socket serverSocket; static void Main(string[] args) { //---listen at the specified IP and port no.--- Console.WriteLine("Listening..."); serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT_NO)); serverSocket.Listen(4); //the maximum pending client, define as you wish serverSocket.BeginAccept(new AsyncCallback(acceptCallback), null); string result = ""; do { result = Console.ReadLine(); } while (result.ToLower().Trim() != "exit"); } private const int BUFFER_SIZE = 4096; private static byte[] buffer = new byte[BUFFER_SIZE]; //buffer size is limited to BUFFER_SIZE per message private static void acceptCallback(IAsyncResult result) { //if the buffer is old, then there might already be something there... Socket socket = null; try { socket = serverSocket.EndAccept(result); // The objectDisposedException will come here... thus, it is to be expected! //Do something as you see it needs on client acceptance socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket); serverSocket.BeginAccept(new AsyncCallback(acceptCallback), null); //to receive another client } catch (Exception e) { // this exception will happen when "this" is be disposed... //Do something here Console.WriteLine(e.ToString()); } } const int MAX_RECEIVE_ATTEMPT = 10; static int receiveAttempt = 0; //this is not fool proof, obviously, since actually you must have multiple of this for multiple clients, but for the sake of simplicity I put this private static void receiveCallback(IAsyncResult result) { Socket socket = null; try { socket = (Socket)result.AsyncState; //this is to get the sender if (socket.Connected) { //simple checking int received = socket.EndReceive(result); if (received > 0) { byte[] data = new byte[received]; //the data is in the byte[] format, not string! Buffer.BlockCopy(buffer, 0, data, 0, data.Length); //There are several way to do this according to https://stackoverflow.com/questions/5099604/any-faster-way-of-copying-arrays-in-c in general, System.Buffer.memcpyimpl is the fastest //DO SOMETHING ON THE DATA int byte[]!! Yihaa!! Console.WriteLine(Encoding.UTF8.GetString(data)); //Here I just print it, but you need to do something else //Message retrieval part //Suppose you only want to declare that you receive data from a client to that client string msg = "I receive your message on: " + DateTime.Now; socket.Send(Encoding.ASCII.GetBytes(msg)); //Note that you actually send data in byte[] Console.WriteLine("I sent this message to the client: " + msg); receiveAttempt = 0; //reset receive attempt socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket); //repeat beginReceive } else if (receiveAttempt < MAX_RECEIVE_ATTEMPT) { //fail but not exceeding max attempt, repeats ++receiveAttempt; //increase receive attempt; socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket); //repeat beginReceive } else { //completely fails! Console.WriteLine("receiveCallback fails!"); //don't repeat beginReceive receiveAttempt = 0; //reset this for the next connection } } } catch (Exception e) { // this exception will happen when "this" is be disposed... Console.WriteLine("receiveCallback fails with exception! " + e.ToString()); } } }
I've tried connecting another computer to the hosted network and sending data to that computer, but the same exception is thrown.
-
Trying to send data from C++ to Java involving Rmq. Considering IPC Sockets
My code will be running on 2 raspberry pi's.
The Process is this:
- C++ program generates a string of data on Pi1
- Data is sent to Send Java file on Pi1
- Send Java file sends it to Rabbitmq (done and shown below)
- Recv Java file receives the message on Pi2 (done and shown below)
- Recv Java file sends it to to the C++ program on Pi2
- Process is repeated from Pi2 to Pi1
You'll see that right now I am just making the string in my Send file but that piece needs to be replaced with the data/string that is being received from the C++ file. I also need to add a part in the Recv file to send the storedMessage/message to the C++ file.
I am kind of lost on what to do from here. I looked into Sockets but didn't find anything to help me start.
I am still a novice so sorry if this seems like an easy thing. Many thanks in advance.
Recv File
import com.rabbitmq.client.*; import java.io.IOException; public class Recv { public static String recv(String ip, String Q) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ip); factory.setUsername("test"); factory.setPassword("test"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); MyConsumer consumer=new MyConsumer(channel); channel.basicConsume(Q,true,consumer); return consumer.getStoredMessage(); } public static class MyConsumer extends DefaultConsumer { public String storedMessage; public MyConsumer(Channel channel) { super(channel); } public String getStoredMessage() { return storedMessage; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); storedMessage = message; // store message here } } }
Send file
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class Send { public static void send(String ip, String Q) throws Exception { ConnectionFactory factory = new ConnectionFactory(); //set connection info factory.setHost(ip); factory.setUsername("test"); factory.setPassword("test"); //create connection Connection connection = factory.newConnection(); //create channel Channel channel = connection.createChannel(); //publish message int a = 1; while (a!=0) { channel.queueDeclare(Q, false, false, false, null); for(int i=1; i<=2; i++) { String message = "Pizza #"+i; channel.basicPublish("", Q, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'" + Q); } a--; } //SHUT IT ALL DOWN! channel.close(); connection.close(); } }
-
Share one VMWare image with two PCs
I am running VMWare Workstation 12. I have two PCs at home, one is a high end desktop, the other is a mid-range laptop.
During the day, I work on the desktop. At night I work on the laptop.
Both run VMWare Workstation 12, configured for NAT.
I have an SSD with an Ubuntu VM on it.
I can move the SSD from the desktop to the laptop, and select "I have moved". However, the assigned IP address changes from laptop to desktop and vice verca.
Is there any way to configure the setup so that the VM has it's own fixed IP address on the local intranet that the desktop and laptop use? I have tried assigning a static IP address to the Linux VM and changing the adapter config to bridged connection, but that didn't work.
Any pointers gratefully received.
-
How to properly call releaseNetworkRequest(PendingIntent) when PendingIntent is no longer available
I am trying to request the network, so I build the NetworkRequest and I build the PendingIntent,
ConnectivityManager conn_manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest net_req; net_req = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) //Data Network? .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) //Wifi .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) //This might be what need internet permission .addCapability(NetworkCapabilities.NET_CAPABILITY_MMS) .build(); Intent intent_sent = new Intent(activity, Service_MmsNetworkAvailable.class); PendingIntent pending_intent_net_req_received = PendingIntent.getService(activity, 0, intent_sent, PendingIntent.FLAG_ONE_SHOT); conn_manager.requestNetwork(net_req, pending_intent_net_req_received);
Then once the Service runs from the PendingIntent calling it, I am doing some Network stuff inside the Service and then when I'm done I believe I need to call releaseNetworkRequest(PendingIntent).
But here's the whole problem of mine, how do I reference the PendingIntent that started the Service from inside the Service? There is no guarantee that the Activity that created the NetworkRequest and PendingIntent will still be alive so I cannot rely on returning to that Activity to be able to call releaseNetworkRequest(PendingIntent) where I have reference to the PendingIntent.
Android specifically states that you must pass in the same PendingIntent into releaseNetworkRequest(PendingIntent) that you passed into conn_manager.requestNetwork(net_req, pending_intent_net_req_received);
So how is a developer supposed to releaseNetworkRequest(PendingIntent)?
Can I somehow reference the PendingIntent from the Service? I understand that PendingIntents stay alive even after the Activity that called it parishes into the abyss.
I must be missing something here, PendingIntents call Activities, Receivers, and Services, none of which I see can reference back to the original PendingIntent. Furthermore, NULL cannot be passed into releaseNetworkRequest(PendingIntent) according to Android documentation?
Also just to note, I am only doing this because startUsingNetworkFeature() is deprecated and developers are encouraged to use NetworkRequest(), arg!!!
I am literally stuck here now with no way to go, this is rare to be so backed into a corner here if anyone can shed light on this predicament of mine I would be grateful.
-
Limitation of multicast bind in Zigbee
I'm new to Zigbee.
I was wondering if there is any limitation of multicast bind in Zigbee network. For Example, will the messages be dropped when I send several multicast messages? Furthermore, when doing binding and grouping in Zigbee, is multicast bind practical or I have to use unicast bind?
Thanks in advance.
-
change tableview cell color to click
I have a TableView that represents a calendar. Each cell is one day. and I want to add an event to the cells. When the cell is clicked, the background must be changed to red ... it should be possible to select more than one cell
-
set alignment of a pane in a stack pane
I try to create an application that contains 2 panes in a stackpane. One pane is the main pane and is centered, the second is smaller and docked to the bottom-left of the stage.
The thing is that I've tried using 'setAlignment' and it does'nt seems to work (although the button is aligned). The small pane is always centered.
What is the problem and how I fix this? I guess that maybe I can't align a pane, so how can I overcome this?
Pane pane = new Pane(); for (SerialPoint sp : points) { Circle circle = new Circle(sp.getX(), sp.getY(), 6, Color.GREEN); pane.getChildren().add(circle); } Pane smallPane = new Pane(); smallPane.setScaleX(0.25); smallPane.setScaleY(0.25); smallPane.setStyle("-fx-border-color: black;"); for (SerialPoint sp : points) { Circle circle = new Circle(sp.getX(), sp.getY(), 6, Color.RED); smallPane.getChildren().add(circle); } Button startBtn = new Button("Start"); StackPane stackPane = new StackPane(pane, smallPane, startBtn); StackPane.setAlignment(smallPane, Pos.BOTTOM_LEFT); StackPane.setAlignment(startBtn, Pos.TOP_RIGHT); StackPane.setMargin(startBtn, new Insets(5)); Scene scene = new Scene(stackPane);
(SerialPoint is my inner class)
-
Unable to resolve dependency Java FX spring boot
I am new to JavaFX and Spring Boot. I am trying to use Dependency Injection but dependency is not getting Autowired. can anybody please help.
Thanks in Advance. Here is my code
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport; @SpringBootApplication @ComponentScan("com.tillster.kisok.installer") public class Main extends AbstractJavaFxApplicationSupport { public static void main(String[] args) { System.setProperty("com.sun.javafx.touch", "true"); System.setProperty("com.sun.javafx.isEmbedded", "true"); System.setProperty("com.sun.javafx.virtualKeyboard", "none"); launch(Main.class, KisokInstallDetailView.class, args); } }
Here is my view File
import org.springframework.stereotype.Component; import de.felixroske.jfxsupport.AbstractFxmlView; import de.felixroske.jfxsupport.FXMLView; @Component @FXMLView(value="/view/LanguageMainScreen.fxml", bundle="bundles.locale") public class KisokInstallDetailView extends AbstractFxmlView { }
Configuration File
@Configuration @ComponentScan("com.kisok.installer") public class KISOKConfiguration { } }
Controller
@FXMLController @Component public class KisokInstallProgressController implements Initializable { @FXML VBox hBox; @FXML WebView webView; @Autowired @Qualifier("installStepService") InstallStepsService installService; ...................... @Override public void initialize(URL location, ResourceBundle resources) { Stage stage = Main.getStage(); WebEngine webEngine = webView.getEngine(); URL url = this.getClass().getClassLoader().getResource("test.html"); webEngine.load(url.toString()); Screen screen = Screen.getPrimary(); Rectangle2D bounds = screen.getVisualBounds(); double screenWidth = bounds.getWidth(); double screenHeight = bounds.getHeight(); webView.setPrefHeight(screenHeight); webView.setPrefWidth(screenWidth); hBox.setPrefWidth(screenWidth); hBox.setPrefHeight(screenHeight); stage.setFullScreen(true); stage.setMaximized(true); stage.setAlwaysOnTop(true); InstallKIOSKDetails installKISOKDtls = installService.getKIOSKDetails(); System.out.println(installKISOKDtls.getInstallSteps().length); }
Service Class:
import java.io.File; import java.io.IOException; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.ObjectMapper; import com.tillster.kisok.installer.domain.InstallKIOSKDetails; @Service("installStepService") public class InstallStepsServiceImpl implements InstallStepsService { private ObjectMapper objectMapper; @Override public InstallKIOSKDetails getKIOSKDetails() { System.out.println("Inside getKIOSKDetails"); objectMapper = new ObjectMapper(); InstallKIOSKDetails installKISOKDtls = null; File jsonInputFile = new File("E:\\KisokDeployment\\json.txt"); try { installKISOKDtls = objectMapper.readValue(jsonInputFile, InstallKIOSKDetails.class); } catch (IOException e) { e.printStackTrace(); } return installKISOKDtls; } }
Here's the Exception: javafx.fxml.LoadException: /E:/mna%20(3)/installer/target/classes/kioskInstallProgress.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579) Caused by: java.lang.NullPointerException at com.tillster.kisok.installer.controller.KisokInstallProgressController.initialize(KisokInstallProgressController.java:67) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548) ... 64 more
FXML
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.MenuBar?> <?import javafx.scene.image.ImageView?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.VBox?> <?import javafx.scene.web.WebView?> <VBox prefHeight="400.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.tillster.kisok.installer.controller.KisokInstallProgressController"> <children> <MenuBar VBox.vgrow="NEVER" /> <AnchorPane maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS"> <children> <WebView fx:id="webView" layoutX="1.0" /> </children> <children> <VBox fx:id="hBox" style="-fx-alignment:center;"> <HBox style="-fx-alignment:center;"> <VBox fx:id="vBox" layoutX="65.0" layoutY="61.0" prefHeight="819.0" prefWidth="627.0" style="-fx-background-color: #EEE;"> <children> <HBox prefHeight="70.0" prefWidth="627.0"> <children> <ImageView fx:id="logo" fitHeight="92.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" /> <Label style="-fx-font-size: 20; -fx-padding: 30 5 5 5;" text="Starting Process of Installation" /> </children> </HBox> <HBox prefHeight="33.0" prefWidth="627.0" /> </children></VBox> </HBox> </VBox> </children> </AnchorPane> </children> </VBox>