I am calling class guibuilder from my class batchrun. code for batchrun is :-
public class batchrun {
public static String md5gen(String a) throws NoSuchAlgorithmException
{
MessageDigest m= MessageDigest.getInstance("MD5");
m.reset();
m.update(a.getBytes());
byte[] digest=m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
return hashtext;
}
private static String getInputAsString(InputStream is)
{
try(java.util.Scanner s = new java.util.Scanner(is))
{
return s.useDelimiter("\\A").hasNext() ? s.next() : "";
}
}
public static void main(String[] args) throws InterruptedException {
try {
guibuilder.main(args);
guibuilder gb=new guibuilder();
String fg=guibuilder.antd;
String arg1=gb.arg;
String userinp1=gb.userinp;
System.out.println("FG="+fg+" arg1="+arg1+" userinp="+userinp1);
Process pan = Runtime.getRuntime().exec(new String[] {"C:\\test1.bat",arg1,fg});
pan.waitFor();
String extra="\\";
extra+=userinp1;
String patha=fg+extra;
ProcessBuilder pb = new ProcessBuilder("adb","shell","getprop","ro.csc.sales_code");
Process p=pb.start();
p.waitFor();
String stdout = getInputAsString(p.getInputStream());
String newstring=stdout.substring(0,3);;
String fn=fg+"\\"+newstring+".txt";
ZipFile zipFile = new ZipFile(patha);
Enumeration<?> enu = zipFile.entries();
int flag=0;
String so="so";
File file = new File(fn);
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size= zipEntry.getSize();
String extension= name.substring(name.lastIndexOf(".")+1,name.length());
if(extension.equals(so))
{
String plaintext=name+size;
String md5result=md5gen(plaintext);
System.out.println(name+" "+size+" "+md5result);
++flag;
}
}
if(flag==0)
System.out.println("fail");
}catch (IOException ex){
System.out.println(ex.getMessage());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code for guibuilder is
public class guibuilder {
private JFrame frame;
public static String antd;
public static String arg;
public static String userinp;
/**
* Launch the application.
* #return
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
guibuilder window = new guibuilder();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public guibuilder() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnExtract = new JButton("Extract");
btnExtract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
fchooser fc1=new fchooser();
antd=fc1.demo();
arg=JOptionPane.showInputDialog("Enter the apk path");
userinp=JOptionPane.showInputDialog("Enter the apk name");
}
});
btnExtract.setBounds(69, 55, 89, 23);
frame.getContentPane().add(btnExtract);
JButton btnCompare = new JButton("Compare");
btnCompare.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
newjframe n = new newjframe();
n.setVisible(true);
}
});
btnCompare.setBounds(261, 55, 89, 23);
frame.getContentPane().add(btnCompare);
}
}
I want the program to wait for the execution of guibuilder before continuing with the code from batchrun. But in this code, i have not even selected the files in guibuilder and the program continues execution and System.out.println("FG="+fg+" arg1="+arg1+" userinp="+userinp1); this line is printed before i choose anything in guibuilder.
Your code shows that your java project has two main classes. one in batchrun class another is in guibuilder class. [from your statement guibuilder.main(args)]
Use only one main class in your project. This may fix your problem.
I think your guibuilder class has structure like this
class guibuilder{
...... //global variables
public static void main(String[] args){
......... //statments
}
}
Don't use two main method in a single project.
you need to structure your guibuilder class like this (shown below)
class guibuilder{
...... //global variables
public static void buildGui(){//you can use any method name here
......... //statments
}
}
to invoke this method from another class just use this statement
guibuilder.buildGui()
or, another way
class guibuilder{
...... //global variables
public void buildGui(){//you can use any method name here
......... //statments
}
}
to invoke this method from another class use this statement
guibuilder gui=new guibuilder();
gui.buildGui();
Related
I am writing a calculator that loads all the classes needed through maven dependencies dynamically.such as slf4j,...
but i have a problem.since i don't want to set my class path to manifest,my customClassLoader does it itself.
but my logger is a private static final field and JVM want to load it before i call my customClassLoader and i get error!what can i do?
public class Calculator{
private List<String> expressions = new ArrayList<String>() ;
private List<String> results = new ArrayList<String>();
private final Logger logger = LoggerFactory.getLogger(Calculator.class);
public Calculator(){
//System.out.println("HELLO");
OperatorsCatalog catalog = new OperatorsCatalog();
}
public void calculate(String inputaddress){
//this.loadAddedClasses();
try{
logger.debug("Start to read the input file");
this.read(inputaddress);
logger.info("Input file is read");
for(int i = 0;i<expressions.size();i++){
ExpressionCalculator e = new ExpressionCalculator(expressions.get(i),OperatorsCatalog.getKnownOperators());
e.evaluate();
results.add(e.getResult());
}
logger.info("All evaluations ended");
logger.debug("Writing to file started");
this.write();
}
catch(FileNotFoundException e){
logger.warn("Can not find Input file",e);
}
catch(IOException er){
logger.warn(er.getMessage());
}
}
public void read(String inputaddress)throws FileNotFoundException,IOException{
CustomReader reader = new CustomReader();
expressions =reader.read(inputaddress);
}
public void write(){
CustomWriter writer = new CustomWriter();
writer.write(results);
}
/*public void loadAddedClasses(){
CustomClassLoader classloader = new CustomClassLoader();
classloader.loadClasses();
}*/
public static void main(String args[]) {
System.out.println("HELLO");
CustomClassLoader classloader = new CustomClassLoader();
classloader.loadClasses();
Calculator calculator = new Calculator();
calculator.calculate(args[0]);
}
}
I'm stuck trying to deserialize a list of Scores. I spent my entire day searching here but couldn't find a solution.. My code looks something like this:
public class Score implements Comparable<Score>, Serializable {
private String name;
private int score;
// .......
}
public class MySortedList<T> extends...implements...,Serializable {
private ArrayList<T> list;
// ....
}
public class ScoreManager {
private final String FILEPATH;
private final String FILENAME = "highscores.ser";
private MySortedList<Score> scoreList;
public ScoreManager() {
File workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
if ((scoreList = loadScores()) == null) {
scoreList = new MySortedList<Score>();
}
}
public void addScore(Score score) {
scoreList.add(score);
saveScores();
}
public MySortedList<Score> getScoreList() {
return scoreList;
}
private void saveScores() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(scoreList);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MySortedList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MySortedList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The loadScores() method returns just an empty MySortedList everytime.
However program succesfully creates the highscores.ser file in the correct place and I have absolutely no errors. Score objects are added correctly to the MySortedList object.
Any ideas? Perhaps worth mentioning that this is a part of a bigger program made in Swing. the methods in the ScoreManager class is called when the player dies
only if it can help, this code is working for me:
class Score implements Comparable<Score>, Serializable{
private int point;
public Score(int point) {
this.point = point;
}
public int getPoint(){
return point;
}
#Override
public int compareTo(Score o) {
if (o.getPoint() == this.getPoint())
return 0;
return this.point < o.getPoint() ? - 1 : 1;
}
public String toString() {
return "points: " + point;
}
}
class MyList<T> implements Serializable {
private ArrayList<T> list = new ArrayList<>();
public void add(T e){
list.add(e);
}
public void show() {
System.out.println(list);
}
}
public class Main {
File workingFolder;
String FILEPATH;
private final String FILENAME = "highscores.ser";
MyList<Score> list = new MyList<>();
public static void main(String[] args) {
Main main = new Main();
main.createFolder();
main.addItems();
main.saveScores();
MyList<Score> tempList = main.loadScores();
tempList.show();
main.addMoreItems();
main.saveScores();
tempList = main.loadScores();
tempList.show();
}
private void addItems() {
Score sc = new Score(10);
list.add(sc);
}
private void addMoreItems() {
Score sc1 = new Score(20);
list.add(sc1);
Score sc2 = new Score(30);
list.add(sc2);
}
private void createFolder() {
workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
}
private void saveScores() {
System.out.println("before save: " + list);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MyList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MyList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This is my java code. Before, it calls BatchGenerateResult sequentially which is a lengthy process, but I want to try some multithreading and have each one of them run at the same time. However when I test it, the new time is the same as the old time. I expected the new time to be faster. Does anyone know whats wrong?
public class PlutoMake {
public static String classDir;
public static void main(String[] args) throws JSONException, IOException,
InterruptedException {
// determine path to the class file, I will use it as current directory
String classDirFile = PlutoMake.class.getResource("PlutoMake.class")
.getPath();
classDir = classDirFile.substring(0, classDirFile.lastIndexOf("/") + 1);
// get the input arguments
final String logoPath;
final String filename;
if (args.length < 2) {
logoPath = classDir + "tests/android.png";
filename = "result.png";
} else {
logoPath = args[0];
filename = args[1];
}
// make sure the logo image exists
File logofile = new File(logoPath);
if (!logofile.exists() || logofile.isDirectory()) {
System.exit(1);
}
// get the master.js file
String text = readFile(classDir + "master.js");
JSONArray files = new JSONArray(text);
ExecutorService es = Executors.newCachedThreadPool();
// loop through all active templates
int len = files.length();
for (int i = 0; i < len; i += 1) {
final JSONObject template = files.getJSONObject(i);
if (template.getBoolean("active")) {
es.execute(new Runnable() {
#Override
public void run() {
try {
BatchGenerateResult(logoPath, template.getString("template"),
template.getString("mapping"),
template.getString("metadata"), template.getString("result")
+ filename, template.getString("filter"),
template.getString("mask"), template.getInt("x"),
template.getInt("y"), template.getInt("w"),
template.getInt("h"));
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
es.shutdown();
boolean finshed = es.awaitTermination(2, TimeUnit.MINUTES);
}
private static void BatchGenerateResult(String logoPath, String templatePath,
String mappingPath, String metadataPath, String resultPath,
String filter, String maskPath, int x, int y, int w, int h)
throws IOException, JSONException {
ColorFilter filterobj = null;
if (filter.equals("none")) {
filterobj = new NoFilter();
} else if (filter.equals("darken")) {
filterobj = new Darken();
} else if (filter.equals("vividlight")) {
filterobj = new VividLight();
} else {
System.exit(1);
}
String text = readFile(classDir + metadataPath);
JSONObject metadata = new JSONObject(text);
Map<Point, Point> mapping = MyJSON.ReadMapping(classDir + mappingPath);
BufferedImage warpedimage = Exporter.GenerateWarpedLogo(logoPath, maskPath,
mapping, metadata.getInt("width"), metadata.getInt("height"));
// ImageIO.write(warpedimage, "png", new FileOutputStream(classDir +
// "warpedlogo.png"));
Exporter.StampLogo(templatePath, resultPath, x, y, w, h, warpedimage,
filterobj);
warpedimage.flush();
}
private static String readFile(String path) throws IOException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String text = new String(data, "UTF-8");
return text;
}
}
It looks like, for all practical purposes the following code should be the only one which can improve performance by using multithreading.
BufferedImage warpedimage = Exporter.GenerateWarpedLogo(logoPath, maskPath,
mapping, metadata.getInt("width"), metadata.getInt("height"));
// ImageIO.write(warpedimage, "png", new FileOutputStream(classDir +
// "warpedlogo.png"));
Exporter.StampLogo(templatePath, resultPath, x, y, w, h, warpedimage,
filterobj);
The rest of it major IO - I doubt how much performance improvement you can achieve there.
Do a profile and check how long each one of the methods is executing. Depending on that you should be able to understand.
Hi sorry not able add to comment part as just joined..
would suggest to first go for dummy method any check whether it works at your end then add your business logic...
if the sample works then you might need to check your "template" class
here's the sample.. check the timestamp
package example;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorStaticExample {
public static void main(String[] args){
ExecutorService ex = Executors.newCachedThreadPool();
for (int i=0;i<10;i++){
ex.execute(new Runnable(){
#Override
public void run() {
helloStatic();
System.out.println(System.currentTimeMillis());
}
});
}
}
static void helloStatic(){
System.out.println("hello form static");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
in netbeans I've got a JFrame and a JavaClass. In my JFrame I have a combobox to select a file that will be used in the operations within the Java class.
Java class:
public class WekaTest {
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("Ficheiro " + filename + " não encontrado");
}
return inputReader;
}
(...)
public static void main(String[] args) throws Exception {
JFrame1 form = new JFrame1();
form.setVisible(true);
BufferedReader datafile = readDataFile("weather.nominal.arff");
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
}
What I need is, from the JFrame's combobox, to select a different datafile to read from. So, as I change the selected item in my combobox, I want to set my datafile as that value.
Here's the JFrame code:
public class JFrame1 extends javax.swing.JFrame {
public JFrame1() {
initComponents();
}
(...)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(arffComboBox.getSelectedItem().toString());;
}
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
(...)
}
How can I do this?
Make the following a private (or public) member:
private BufferedReader datafile = null;
Then do the read within the action listener you've assigned to the combobox:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
datafile = readDataFile(pth);
}
Then you can use datafile either in the listener or elsewhere as necessary.
Something like that should do what you're after.
EDIT
Given the new information, you're probably going to do best with a PropertyChangeListener that subscribes to the JFrame1 (form.addPropertyChangeListener) object and listens to PropertyChangeEvents that you fire from within your arffComboBoxActionPerformed method.
In the arffComboBoxActionPerformed:
private void arffComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
String pth = arffComboBox.getSelectedItem();
firePropertyChange('combo_changed', null, pth);
}
Then in the main:
JFrame1 form = new JFrame1();
form.setVisible(true);
form.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pce) {
// Handle the change here
String pth = (String) pce.getNewValue();
BufferedReader datafile = readDataFile(pth);
Instances data = new Instances(datafile);
data.setClassIndex(data.numAttributes() - 1);
(...)
}
});