GUI Java FX app is not responding after pressing button - java

I ve been working on JAVA FX application which uploads certain file on remote computer and then executing mentioned file via cmd. It's working with all platforms Windows, Linux and Mac but I have one problem.
Problem: when file is bigger GUI totally crashes resulting in unable to click or do anything (App Not responding) eventhough file is uploaded and run via CMD after I check it.
I've been reading that JAVA FX is using single thread for GUI and all operations so basicly I need to create separate thread for GUI and separate thread for other code. I ve been trying to figure this out for pass 3 days and couldnt come up with solution. My program consists of more classes which depends on each other resulting to be harder to come up with solution. Will anybody be kind to help me with this problem?
Please bare in mind I m not a programmer this is kind of my hobby I know this programm does not fullfill coding standards.
Code:
Main:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class App extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("GUI.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 600, 420);
stage.setTitle("App name");
stage.setScene(scene);
stage.setResizable(false);
Image icon = new Image("icon.png");
stage.getIcons().add(icon);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Class Uploader:
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.IOException;
public class Uploader {
public String remoteHost;
public String username;
public String password;
public String path;
public String filename;
public Uploader(String remoteHost,String username,String password, String path, String filename){
this.remoteHost = remoteHost;
this.username = username;
this.password = password;
this.path = path;
this.filename = filename;
}
public SSHClient setupSshj() throws IOException {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(remoteHost);
client.authPassword(username, password);
return client;
}
public void whenUploadFileUsingSshj_thenSuccess(String osType) throws IOException {
String localFilePath = "";
String remoteDirPath = "";
SSHClient sshClient = setupSshj();
System.out.println("Connection established...");
SFTPClient sftpClient = sshClient.newSFTPClient();
if (osType.equals("win")){
remoteDirPath = "C:\\"+filename;
localFilePath = path+filename;
}
else if (osType.equals("lin")) {
remoteDirPath = "//tmp//" + filename;
localFilePath = path+filename;
}
else{
remoteDirPath = "Downloads//" + filename;
localFilePath = path+filename;
}
sftpClient.put(localFilePath, remoteDirPath);
System.out.println("File uploaded successfully...");
sftpClient.close();
sshClient.disconnect();
}
}
class Cmdrunner:
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.DefaultSessionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CommandRunner {
public CommandRunner(String username, String hostname, String password, String cmd) throws JSchException, IOException {
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(username, hostname, 22);
Map props = new HashMap<String, String>();
props.put("StrictHostKeyChecking", "no");
sessionFactory.setConfig(props);
sessionFactory.setPassword(password);
com.pastdev.jsch.command.CommandRunner runner = new com.pastdev.jsch.command.CommandRunner(sessionFactory);
com.pastdev.jsch.command.CommandRunner.ExecuteResult result = runner.execute(cmd);
System.out.println("cmd successfully executed...");
runner.close();
}
}
class Controler:
import com.jcraft.jsch.JSchException;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import java.io.IOException;
public class Controller {
String osType = "win";
#FXML
public TextField host_input;
public TextField user_input;
public TextField pass_input;
public TextField path_input;
public TextField file_name;
//public Label state_id;
#FXML
public void winOs() { osType = "win";
file_name.setText("File name");
}
public void linOs() {
osType = "lin";
file_name.setText("Filename");
}
public void macOs() { osType = "mac"; }
public void upload() throws IOException, JSchException {
//state_id.setText("");
Uploader upload = new Uploader(host_input.getText(),user_input.getText(),pass_input.getText(),
path_input.getText(), file_name.getText());
upload.whenUploadFileUsingSshj_thenSuccess(osType);
if (osType.equals("win")){
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
String.format("C:\\%s --silent --accepteula",file_name.getText()));
//state_id.setText("Installer uploaded and run successfully!");
}
if (osType.equals("lin")){
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"chmod 777 //tmp//"+file_name.getText());
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
String.format("echo %s | sudo -S //tmp//%s", pass_input.getText(), file_name.getText()));
}
else {
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"chmod 777 Downloads//"+file_name.getText());
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"Downloads//"+file_name.getText());
}
}
public void exit() {
Platform.exit();
}
}

Related

Modded Command in Minecraft 1.8.9 command doesn't exist in Multiplayer server

I am developing some minecraft mod for 1.8.9.
What I'm trying to create is command that simply send message to sender.
here's the code for command class and main class
command class:
package happyandjust.happymod.commands;
import java.util.HashMap;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
public class Command extends CommandBase {
private HashMap<String, String> collection = new HashMap<String, String>();
#Override
public String getCommandName() {
return "collection";
}
#Override
public String getCommandUsage(ICommandSender sender) {
return "collection <enchant name>";
}
#Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
collection.put("harvesting", "Wheat Collection Level 2");
collection.put("cubism", "Pumpkin Collection Level 5");
if (args.length < 1) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Usage: /collection [Enchant Name]"));
return;
}
if (args.length == 1) {
String enchant_name = args[0].toLowerCase();
String collec = collection.get(enchant_name);
if (collec == null) {
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.RED + enchant_name.toUpperCase() + " is not valid Enchant Name"));
return;
}
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.GREEN + enchant_name.toUpperCase() + " is at " + collection.get(enchant_name)));
}
}
#Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return true;
}
}
main class:
package happyandjust.happymod.main;
import happyandjust.happymod.commands.Command;
import happyandjust.happymod.proxy.CommonProxy;
import happyandjust.happymod.util.Reference;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class HappyMod {
#Instance
public static HappyMod instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public static void preInit(FMLPostInitializationEvent e) {
}
#EventHandler
public static void init(FMLInitializationEvent e) {
ClientCommandHandler.instance.registerCommand(new Command());
}
#EventHandler
public static void postInit(FMLPostInitializationEvent e) {
}
}
It works fine in single player but if I went to the multi player server like hypixel.
It says "Unknown command"
I have no idea to do this
Can anyone help me to work this command in multi player server?
You need to override the getRequiredPermissionLevel() method from CommandBase for it to work on multiplayer.
#Override
public int getRequiredPermissionLevel() {
return 0;
}

Process file (which sit on Server A) on Server B

Since Server A and server B doesn't have SFTP, and I am try to implement a web service on Server B, that takes the file on Server A and process it. I tried using Spring boot to do this, like save the file first, and the process. But this way it seems like async, which means when the code try to process the file, the file is not ready yet, (confirm when I print the file location, it return null). What is the good way to handle this?
Current Code I have for the controller is following:
package com.example.filedemo.controller;
import com.example.filedemo.payload.UploadFileResponse;
import com.example.filedemo.service.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Response;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
#RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
private static final String PYTHON_FILE = "V:/speechRecognition/audio_transcribe.py";
#Autowired
private FileStorageService fileStorageService;
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri =
ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile/").path(fileName).toUriString();
return new UploadFileResponse(fileName, fileDownloadUri, file.getContentType(), file.getSize());
}
#PostMapping("/processFile")
public ResponseEntity<String> processFile(#RequestParam("file") MultipartFile file) throws IOException {
String filename = uploadFile(file).getFileName();
File actualFile = new File("E:\\Audio\\uploads\\" + filename);
String fetching = "python " + PYTHON_FILE + " " + actualFile.getAbsolutePath();
String[] command = new String[] {"cmd.exe", "/c", fetching};
Process p = Runtime.getRuntime().exec(command);
String pythonPath = System.getProperty("PYTHON_PATH");
System.out.println("pythonPath is " + pythonPath);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println(ret);
return new ResponseEntity<String>("Success", HttpStatus.OK);
}
}
FileStorageService.java
package com.example.filedemo.service;
import com.example.filedemo.exception.FileStorageException;
import com.example.filedemo.exception.MyFileNotFoundException;
import com.example.filedemo.property.FileStorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
#Service
public class FileStorageService {
private final Path fileStorageLocation;
#Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
}
}
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
long numberOfByte = Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Copy byte " + numberOfByte);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new MyFileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new MyFileNotFoundException("File not found " + fileName, ex);
}
}
}
UploadFileResponse
package com.example.filedemo.payload;
public class UploadFileResponse {
private String fileName;
private String fileDownloadUri;
private String fileType;
private long size;
public UploadFileResponse(String fileName, String fileDownloadUri, String fileType, long size) {
this.fileName = fileName;
this.fileDownloadUri = fileDownloadUri;
this.fileType = fileType;
this.size = size;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileDownloadUri() {
return fileDownloadUri;
}
public void setFileDownloadUri(String fileDownloadUri) {
this.fileDownloadUri = fileDownloadUri;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
I would recommend storing the file in the database, then operating on it from there. Obviously, be careful the file size doesn't overrun the column size.
If your operations require an actual file on disk (rather than, say, a stream of bytes), then you could create a sync service that polls the database for new files and saves a copy on the local disk when found. Then your processing code can use the local disk file handle.

Getting Null pointer exception while loading property file in selenium java

This is the java code for file reader
package dataProviders;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class ConfigFileReader {
private Properties properties;
private final String propertyFilePath = System.getProperty("user.dir"+"//src//main//resources//configs/Configurations.properties");
public ConfigFileReader() throws IOException
{
FileInputStream fis = new FileInputStream(propertyFilePath);
properties.load(fis);
fis.close();
}
public String getUrl()
{
String url = properties.getProperty("url");
if(url!=null)
{
return url;
}
else
{
throw new RuntimeException("URL is not specified in configuration.properties file");
}
}
public String driverpath()
{
String driverpath = properties.getProperty("driverpath");
if(driverpath!=null)
{
return driverpath;
}
else
{
throw new RuntimeException("Driver path is not specified in configuration.properties");
}
}
}
This is the java code which contains cucumber Annotation and which works as main method
package stepDefinations;
import java.util.List;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import pageObjects.CartPage;
import pageObjects.Checkoutpage;
import pageObjects.HomePage;
import pageObjects.ProductListingPage;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import dataProviders.ConfigFileReader;
public class EndtoEndTest {
WebDriver driver;
ConfigFileReader cnffilered;
#Given("^User is on Homepage$")
public void user_is_on_Homepage() throws Throwable {
cnffilered = new ConfigFileReader();
System.setProperty("webdriver.chrome.driver",cnffilered.driverpath());
driver = new ChromeDriver();
driver.get(cnffilered.getUrl());
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
}
#When("^he searches for \"([^\"]*)\"$")
public void he_searches_for(String arg1) throws Throwable {
HomePage home = new HomePage(driver);
home.perform_Search(arg1);
}
#When("^Choose to buy the first item$")
public void choose_to_buy_the_first_item() throws Throwable {
ProductListingPage productListingPage = new ProductListingPage(driver);
productListingPage.select_Product(0);
productListingPage.clickOn_AddToCart();
}
#When("^moves to checkout from mini cart$")
public void moves_to_checkout_from_mini_cart() throws Throwable {
CartPage cartPage = new CartPage(driver);
cartPage.clickOn_Cart();
cartPage.clickOn_ContinueToCheckout();
}
#When("^enter personal details onn checkout page$")
public void enter_personal_details_onn_checkout_page() throws Throwable {
Checkoutpage checkoutPage = new Checkoutpage(driver);
checkoutPage.fill_PersonalDetails();
}
#When("^select same delivery address$")
public void select_same_delivery_address() throws Throwable {
Checkoutpage checkoutPage = new Checkoutpage(driver);
checkoutPage.check_ShipToDifferentAddress(false);
}
#When("^select payment method as \"([^\"]*)\" payment$")
public void select_payment_method_as_payment(String arg1) throws Throwable {
Checkoutpage checkoutPage = new Checkoutpage(driver);
checkoutPage.select_PaymentMethod("CheckPayment");
}
#When("^place the order$")
public void place_the_order() throws Throwable {
Checkoutpage checkoutPage = new Checkoutpage(driver);
checkoutPage.check_TermsAndCondition(true);
checkoutPage.clickOn_PlaceOrder();
driver.quit();
}
}
While Executing my Cucumber feature file i am getting below exception and i tried many things but still don't know why it is throwing Null Pointer Exception
java.lang.NullPointerException
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at dataProviders.ConfigFileReader.<init>(ConfigFileReader.java:17)
at stepDefinations.EndtoEndTest.user_is_on_Homepage(EndtoEndTest.java:32)
at ✽.Given User is on Homepage(src/test/resources/functionalTest/EndtoEndTest.feature:8)
Any Help will be appreciated. Thanks in advance.
ConfigFileReader.Java17: FileInputStream fis = new FileInputStream(propertyFilePath);
EndtoEndTest.java32:cnffilered = new ConfigFileReader();
where your attribute properties is initialized in class ConfigFileReader?
private Properties properties;
After reading your code it seems that property object will always be null. You are not injecting it from outside, neither initializing it.
Please try Properties prop = new Properties();
Plus your are not passing the correct value for propertyFilePath variable. wrong concatenation .
Correct one will be as below
private final String propertyFilePath = System.getProperty("user.dir") + "//src//main//resources//configs/Configurations.properties";

java.lang.NoClassDefFoundError: net/sourceforge/tess4j/TesseractException

I try to do an ocr application for Mirth with Java and Tesseract.I export the project in jar file and call in Mirth with Javascript that did a hello world application.I believe that I add the jar files right way.However I have a problem in Java OCR,so I get this error,
ERROR (com.mirth.connect.connectors.js.JavaScriptDispatcher:193): Error evaluating JavaScript Writer (JavaScript Writer "RTF>DCM" on channel b469e5af-a78d-41ca-86a0-a7b507799a4d).
java.lang.NoClassDefFoundError: net/sourceforge/tess4j/TesseractException
Project Screenshot
package com.imagerad.ocr;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class JavaOCRTest {
static String Tc;
static String phone;
static String date;
public static void main(String[] args) throws IOException{
}
public String returnText(String fileName) throws IOException{
Files.walk(Paths.get(fileName)).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
File imageFile = filePath.toFile();
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(imageFile);
int i=result.indexOf("Numarasn: ");
int j=result.indexOf("Tel No:");
int k=result.indexOf("Bilgllendirme Tarihl:");
Tc = result.substring(i+10, i+22);
phone = result.substring(j+8,j+23);
date = result.substring(k+22,k+32);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
});
return Tc+""+phone+""+date;
}
public String returnTC() throws IOException{
return Tc;
}
public String returnPhone() throws IOException{
return phone;
}
public String returnDate() throws IOException{
return date;
}
}
Thank you so much for your helps.
You have to download the Tess4J.jar and add it to the classpath. This jar contains the missing class net/sourceforge/tess4j/TesseractException

An example in Java using Embedded Cassandra Server to test a Cassandra-Spark job

I am new to Cassandra and Spark. I am trying to set up a test for my Spark job, which does the following:
Loads data from table A into DataFrames
Does some filtering, grouping and aggregating on these DataFrames
Loads the result into table B
I want to use Embedded Cassandra Server to run the test rather than having it connecting to a local instance of the Cassandra database. Has anyone done this before? If so, could someone point me to a good example please? Thanks for your help in advance!
this code does
package cassspark.clt;
import java.io.*;
import javafx.application.Application;
import java.util.concurrent.Executors ;
import java.util.concurrent.ExecutorService;
import org.apache.cassandra.service.CassandraDaemon;
import com.datastax.driver.core.exceptions.ConnectionException;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import org.apache.spark.sql.SparkSession;
public class EmbeddedCassandraDemo extends Application {
private ExecutorService executor = Executors.newSingleThreadExecutor();
private CassandraDaemon cassandraDaemon;
public EmbeddedCassandraDemo() {
}
public static void main(String[] args) {
try {
new EmbeddedCassandraDemo().run();
}
catch(java.lang.InterruptedException e)
{
;
}
}
#Override public void start(javafx.stage.Stage stage) throws Exception
{
stage.show();
}
private void run() throws InterruptedException, ConnectionException {
setProperties();
activateDeamon();
}
private void activateDeamon() {
executor.execute( new Runnable() {
#Override
public void run() {
cassandraDaemon = new CassandraDaemon();
cassandraDaemon.activate();
SparkSession spark = SparkSession .builder().master("local").appName("ASH").getOrCreate();
}
});
}
private void setProperties() {
final String yaml = System.getProperty("user.dir") + File.separator +"conf"+File.separator+"cassandra.yaml";
final String storage = System.getProperty("user.dir") + File.separator +"storage" + File.separator +"data";
System.setProperty("cassandra.config", "file:"+ yaml );
System.setProperty("cassandra.storagedir", storage );
System.setProperty("cassandra-foreground", "true");
String log4JPropertyFile = "./conf/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
} catch (IOException e) {
System.err.println("./conf/log4j.properties not found ");
System.exit(1);
;
}
}
}

Categories