Error occurred during initialization of boot layer : java.lang.module.ResolutionException - java

I am using a fingerprint device to register fingerprint into my MySQL database. However, I can't run my program correctly as it shows an error when I execute it.
I have done some research on this. On a lot of forums, it stats that it is the JRE version problem, so I have tried JRE 9, 10 and 11 without success.
Error occurred during initialization of boot layer
java.lang.module.ResolutionException: Module dpfpenrollment contains
package com.digitalpersona.onetouch.ui.swing, module dpfpverification
exports package com.digitalpersona.onetouch.ui.swing to dpfpenrollment
The actual result should register the ID, username, fingerprint in the MySQL.
This is the code that creates UserInterface and UserDatabase instances and runs UserInterface.
package com.my.apiit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Creates UserInterface and UserDatabase instances and runs UserInterface.
*/
public class AppFingerPrintToDb {
public static void main (String[] args) {
try {
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ConsoleUserDbManager());
exec.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.my.apiit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import com.digitalpersona.onetouch.DPFPDataPurpose;
import com.digitalpersona.onetouch.DPFPFeatureSet;
import com.digitalpersona.onetouch.DPFPFingerIndex;
import com.digitalpersona.onetouch.DPFPGlobal;
import com.digitalpersona.onetouch.DPFPSample;
import com.digitalpersona.onetouch.DPFPTemplate;
import com.digitalpersona.onetouch.capture.DPFPCapture;
import com.digitalpersona.onetouch.capture.DPFPCapturePriority;
import com.digitalpersona.onetouch.capture.event.DPFPDataEvent;
import com.digitalpersona.onetouch.capture.event.DPFPDataListener;
import com.digitalpersona.onetouch.capture.event.DPFPReaderStatusAdapter;
import com.digitalpersona.onetouch.capture.event.DPFPReaderStatusEvent;
import com.digitalpersona.onetouch.processing.DPFPEnrollment;
import com.digitalpersona.onetouch.processing.DPFPFeatureExtraction;
import com.digitalpersona.onetouch.processing.DPFPImageQualityException;
import com.digitalpersona.onetouch.readers.DPFPReadersCollection;
import com.digitalpersona.onetouch.verification.DPFPVerification;
import com.digitalpersona.onetouch.verification.DPFPVerificationResult;
/**
* Implementation of UserInterface.Factory interface that creates a console-based user interface
*/
public class ConsoleUserDbManager implements Runnable {
public void run() {
System.out.println("\n*** Console UI ***");
String activeReader = null;
boolean readerSelected = false;
activeReader = selectReader(activeReader);
readerSelected = true;
int res;
while ((res = MenuShow(mainMenu, MENU_WITH_EXIT)) != exitItem.getValue()) try {
switch (res) {
/*case MAIN_MENU_ADD:
//addUser();
break;*/
case MAIN_MENU_ENROLL:
addUser(activeReader);
break;
case MAIN_MENU_VERIFY:
verify(activeReader);
break;
}
} catch (Exception e) { }
}
/**
* Console menu item
*/
private static class MenuItem {
private String text;
private int value;
/**
* Creates a menu item
*
* #param text item text
* #param value value to return if item is chosen
*/
public MenuItem(String text, int value) {
this.text = text;
this.value = value;
}
/**
* Returns the menu item's text
*
* #return menu item text
*/
public String getText() {
return text;
}
/**
* Returns the menu item's associated value
*
* #return associated value
*/
public int getValue() {
return value;
}
}
/**
* Specifies that menu should be appended with "Back" item
*/
private static final int MENU_WITH_BACK = 2;
/**
* Specifies that menu should be appended with "Exit" item
*/
private static final int MENU_WITH_EXIT = 1;
/**
* "Exit" menu item
*/
private static final MenuItem exitItem = new MenuItem("Exit the application", -1);
/**
* "Back" menu item
*/
private static final MenuItem backItem = new MenuItem("Return to the previous menu", -2);
private static final int MAIN_MENU_ENROLL = 102;
private static final int MAIN_MENU_VERIFY = 103;
private static final Vector<MenuItem> mainMenu;
static {
mainMenu = new Vector<MenuItem>();
mainMenu.add(new MenuItem("Add User And Perform fingerprint enrollment", MAIN_MENU_ENROLL));
mainMenu.add(new MenuItem("Perform fingerprint verification", MAIN_MENU_VERIFY));
}
private int MenuShow(Vector<MenuItem> menu, int nMenuFlags) {
int choice = 0;
if (menu == null)
return choice;
while (true) {
System.out.println();
for (int i = 0; i < menu.size(); ++i)
System.out.printf("%d: %s\n", i + 1, menu.elementAt(i).getText());
StringBuilder sb = new StringBuilder();
sb.append(String.format("Choose an option (1 - %d", menu.size()));
if ((nMenuFlags & MENU_WITH_BACK) != 0) {
System.out.printf("\nR: %s\n\n", backItem.getText());
sb.append(", R");
}
if ((nMenuFlags & MENU_WITH_EXIT) != 0) {
System.out.printf("\nE: %s\n\n", exitItem.getText());
sb.append(", E");
}
sb.append("): ");
String userInput = ShowDialog(sb.toString());
if ((nMenuFlags & MENU_WITH_EXIT) != 0 && userInput.equalsIgnoreCase("E")) {
choice = exitItem.getValue();
break;
}
if ((nMenuFlags & MENU_WITH_BACK) != 0 && userInput.equalsIgnoreCase("R")) {
choice = backItem.getValue();
break;
}
int nInput;
try {
nInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.printf("\nInvalid input: \"%s\"\n", userInput);
continue;
}
if (nInput < 1 || nInput > menu.size()) {
System.out.printf("\nIncorrect choice: \"%s\"\n", userInput);
continue;
}
choice = menu.elementAt(nInput - 1).getValue();
break;
}
System.out.println();
return choice;
}
/**
* Adds user to the database
*/
private void addUser(String activeReader) {
System.out.printf("Adding person to the database…\n");
String username = ShowDialog("Enter a name: ");
register(activeReader,username);
/*if (username != null) {
System.out.printf("\"%s\" was added to the database.\n", username);
} else {
System.out.printf("\"%s\" was not added to the database.\n", username);
}*/
}
/**
* register() looks for the user in the database, invokes CreateRegistrationTemplate(),
* and stores the template in the database.
*
* #param activeReader reader to use for fingerprint acquisition
*/
private void register(String activeReader, String username) {
UserDAO userDAO = UserDAO.getInstance();
UserDb userDb = userDAO.selectUser(username);
if (userDb != null) {
System.err.println("User already exist…");
return;
}
System.out.printf("Performing fingerprint enrollment…\n");
try {
DPFPFingerIndex finger = DPFPFingerIndex.values()[1];
DPFPFeatureExtraction featureExtractor = DPFPGlobal.getFeatureExtractionFactory().createFeatureExtraction();
DPFPEnrollment enrollment = DPFPGlobal.getEnrollmentFactory().createEnrollment();
while (enrollment.getFeaturesNeeded() > 0) {
DPFPSample sample = getSample(activeReader,
String.format("Scan your finger (%d remaining)\n", enrollment.getFeaturesNeeded()));
if (sample == null)
continue;
DPFPFeatureSet featureSet;
try {
featureSet = featureExtractor.createFeatureSet(sample, DPFPDataPurpose.DATA_PURPOSE_ENROLLMENT);
} catch (DPFPImageQualityException e) {
System.out.printf("Bad image quality: \"%s\". Try again. \n", e.getCaptureFeedback().toString());
continue;
}
enrollment.addFeatures(featureSet);
}
DPFPTemplate template = enrollment.getTemplate();
// Write to database
userDb = new UserDb();
userDb.setUserName(username);
userDb.setFingerPrint(template.serialize());
userDAO.insertUser(userDb.getUserName(), userDb.fingerPrint);
//-- write to a specific file
/*FileOutputStream stream;
try {
stream = new FileOutputStream(new File("d:/fingerPrint/sample.fpt"));
stream.write(template.serialize());
stream.close();
} catch (Exception e) {
e.printStackTrace();
}*/
System.err.println("Congratulation your fingerprint is enrolled in database..");
} catch (UserDbException e){
System.out.printf(e.getMessage() + "\n");
} catch (DPFPImageQualityException e) {
System.out.printf("Failed to enroll the finger.\n");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Acquires fingerprint from the sensor and matches it with the registration templates
* stored in the database.
*
* #param activeReader fingerprint reader to use
*/
private void verify(String activeReader) {
System.out.printf("Performing fingerprint verification…\n");
String userName = ShowDialog("Enter the name of the person to be verified: ");
UserDAO userDAO = UserDAO.getInstance();
UserDb user =userDAO.selectUser(userName);
if (user == null) {
System.out.printf("\"%s\" was not found in the database.\n", userName);
} else {
if (user == null) {
System.out.printf("No fingers for \"%s\" have been enrolled.\n", userName);
} else {
try {
DPFPSample sample = getSample(activeReader, "Scan your finger\n");
if (sample == null)
throw new Exception();
DPFPFeatureExtraction featureExtractor = DPFPGlobal.getFeatureExtractionFactory().createFeatureExtraction();
DPFPFeatureSet featureSet = featureExtractor.createFeatureSet(sample, DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
DPFPVerification matcher = DPFPGlobal.getVerificationFactory().createVerification();
matcher.setFARRequested(DPFPVerification.MEDIUM_SECURITY_FAR);
try {
//-- reading from User
byte[] data = user.getFingerPrint();
DPFPTemplate t = DPFPGlobal.getTemplateFactory().createTemplate();
t.deserialize(data);
//--- reading from file
/*FileInputStream stream = new FileInputStream("d:/fingerPrint/sample.fpt");
byte[] data = new byte[stream.available()];
stream.read(data);
stream.close();
DPFPTemplate t = DPFPGlobal.getTemplateFactory().createTemplate();
t.deserialize(data);
*/
//setTemplate(t);
//-----verfiy -------------
if (t != null) {
DPFPVerificationResult result = matcher.verify(featureSet, t);
if (result.isVerified()) {
//System.err.println("Matching finger: Successfully Matched" ,(double)result.getFalseAcceptRate()/DPFPVerification.PROBABILITY_ONE);
System.err.println("Matching finger: Successfully Matched");
ShowDialog("\nPress enter to continue ....");
return;
}
}
} catch (Exception ex) {
System.out.printf("Failed to perform verification.");
}
} catch (Exception e) {
System.out.printf("Failed to perform verification.");
}
//System.out.printf("No matching fingers for \"%s\" were found.\n", userName);
System.out.printf("No matching fingers for "+ userName+" were found.\n");
ShowDialog("\nPress enter to continue…");
}
}
}
/**
* selectReader() stores chosen reader in *pActiveReader
* #param activeReader currently selected reader
* #return reader selected
* #throws IndexOutOfBoundsException if no reader available
*/
String selectReader(String activeReader) throws IndexOutOfBoundsException {
DPFPReadersCollection readers = DPFPGlobal.getReadersFactory().getReaders();
if (readers == null || readers.size() == 0)
throw new IndexOutOfBoundsException("There are no readers available");
int res = 0;
return readers.get(res).getSerialNumber();
}
/**
* Acquires a fingerprint sample from the specified fingerprint reader
*
* #param activeReader Fingerprint reader to use for acquisition
* #return sample acquired
* #throws InterruptedException if thread is interrupted
*/
private DPFPSample getSample(String activeReader, String prompt)
throws InterruptedException {
final LinkedBlockingQueue<DPFPSample> samples = new LinkedBlockingQueue<DPFPSample>();
DPFPCapture capture = DPFPGlobal.getCaptureFactory().createCapture();
capture.setReaderSerialNumber(activeReader);
capture.setPriority(DPFPCapturePriority.CAPTURE_PRIORITY_LOW);
capture.addDataListener(new DPFPDataListener() {
public void dataAcquired(DPFPDataEvent e) {
if (e != null && e.getSample() != null) {
try {
samples.put(e.getSample());
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
});
capture.addReaderStatusListener(new DPFPReaderStatusAdapter() {
int lastStatus = DPFPReaderStatusEvent.READER_CONNECTED;
public void readerConnected(DPFPReaderStatusEvent e) {
if (lastStatus != e.getReaderStatus())
System.out.println("Reader is connected");
lastStatus = e.getReaderStatus();
}
public void readerDisconnected(DPFPReaderStatusEvent e) {
if (lastStatus != e.getReaderStatus())
System.out.println("Reader is disconnected");
lastStatus = e.getReaderStatus();
}
});
try {
capture.startCapture();
System.out.print(prompt);
return samples.take();
} catch (RuntimeException e) {
System.out.printf("Failed to start capture. Check that reader is not used by another application.\n");
throw e;
} finally {
capture.stopCapture();
}
}
private String ShowDialog(String prompt) {
System.out.printf(prompt);
try {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
return stdin.readLine();
} catch (IOException e) {
return "";
}
}
}

Related

javax.media.NoDataSinkException

I am trying to convert Jpeg images into .mov video file
package com.ecomm.pl4mms.test;
import java.io.*;
import java.util.*;
import java.awt.Dimension;
import javax.media.*;
import javax.media.control.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.datasink.*;
import javax.media.format.VideoFormat;
import javax.media.format.JPEGFormat;
public class JpegImagesToMovie implements ControllerListener, DataSinkListener {
public boolean doItPath(int width, int height, int frameRate, Vector inFiles, String outputURL) {
// Check for output file extension.
if (!outputURL.endsWith(".mov") && !outputURL.endsWith(".MOV")) {
// System.err.println("The output file extension should end with a
// .mov extension");
prUsage();
}
// Generate the output media locators.
MediaLocator oml;
if ((oml = createMediaLocator("file:" + outputURL)) == null) {
// System.err.println("Cannot build media locator from: " +
// outputURL);
//System.exit(0);
}
boolean success = doIt(width, height, frameRate, inFiles, oml);
System.gc();
return success;
}
public boolean doIt(int width, int height, int frameRate, Vector inFiles, MediaLocator outML) {
try {
System.out.println(inFiles.size());
ImageDataSource ids = new ImageDataSource(width, height, frameRate, inFiles);
Processor p;
try {
// System.err.println("- create processor for the image
// datasource ...");
System.out.println("processor");
p = Manager.createProcessor(ids);
System.out.println("success");
} catch (Exception e) {
// System.err.println("Yikes! Cannot create a processor from the
// data source.");
return false;
}
p.addControllerListener(this);
// Put the Processor into configured state so we can set
// some processing options on the processor.
p.configure();
if (!waitForState(p, p.Configured)) {
System.out.println("Issue configuring");
// System.err.println("Failed to configure the processor.");
p.close();
p.deallocate();
return false;
}
System.out.println("Configured");
// Set the output content descriptor to QuickTime.
p.setContentDescriptor(new ContentDescriptor(FileTypeDescriptor.QUICKTIME));
System.out.println(outML);
// Query for the processor for supported formats.
// Then set it on the processor.
TrackControl tcs[] = p.getTrackControls();
Format f[] = tcs[0].getSupportedFormats();
System.out.println(f[0].getEncoding());
if (f == null || f.length <= 0) {
System.err.println("The mux does not support the input format: " + tcs[0].getFormat());
p.close();
p.deallocate();
return false;
}
tcs[0].setFormat(f[0]);
// System.err.println("Setting the track format to: " + f[0]);
// We are done with programming the processor. Let's just
// realize it.
p.realize();
if (!waitForState(p, p.Realized)) {
// System.err.println("Failed to realize the processor.");
p.close();
p.deallocate();
return false;
}
// Now, we'll need to create a DataSink.
DataSink dsink;
if ((dsink = createDataSink(p, outML)) == null) {
// System.err.println("Failed to create a DataSink for the given
// output MediaLocator: " + outML);
p.close();
p.deallocate();
return false;
}
dsink.addDataSinkListener(this);
fileDone = false;
// System.err.println("start processing...");
// OK, we can now start the actual transcoding.
try {
p.start();
dsink.start();
} catch (IOException e) {
p.close();
p.deallocate();
dsink.close();
// System.err.println("IO error during processing");
return false;
}
// Wait for EndOfStream event.
waitForFileDone();
// Cleanup.
try {
dsink.close();
} catch (Exception e) {
}
p.removeControllerListener(this);
// System.err.println("...done processing.");
p.close();
return true;
} catch (NotConfiguredError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* Create the DataSink.
*/
DataSink createDataSink(Processor p, MediaLocator outML) {
System.out.println("In data sink");
DataSource ds;
if ((ds = p.getDataOutput()) == null) {
System.out.println("Something is really wrong: the processor does not have an output DataSource");
return null;
}
DataSink dsink;
try {
System.out.println("- create DataSink for: " + ds.toString()+ds.getContentType());
dsink = Manager.createDataSink(ds, outML);
dsink.open();
System.out.println("Done data sink");
} catch (Exception e) {
System.err.println("Cannot create the DataSink: " +e);
e.printStackTrace();
return null;
}
return dsink;
}
Object waitSync = new Object();
boolean stateTransitionOK = true;
/**
* Block until the processor has transitioned to the given state. Return
* false if the transition failed.
*/
boolean waitForState(Processor p, int state) {
synchronized (waitSync) {
try {
while (p.getState() < state && stateTransitionOK)
waitSync.wait();
} catch (Exception e) {
}
}
return stateTransitionOK;
}
/**
* Controller Listener.
*/
public void controllerUpdate(ControllerEvent evt) {
if (evt instanceof ConfigureCompleteEvent || evt instanceof RealizeCompleteEvent
|| evt instanceof PrefetchCompleteEvent) {
synchronized (waitSync) {
stateTransitionOK = true;
waitSync.notifyAll();
}
} else if (evt instanceof ResourceUnavailableEvent) {
synchronized (waitSync) {
stateTransitionOK = false;
waitSync.notifyAll();
}
} else if (evt instanceof EndOfMediaEvent) {
evt.getSourceController().stop();
evt.getSourceController().close();
}
}
Object waitFileSync = new Object();
boolean fileDone = false;
boolean fileSuccess = true;
/**
* Block until file writing is done.
*/
boolean waitForFileDone() {
synchronized (waitFileSync) {
try {
while (!fileDone)
waitFileSync.wait();
} catch (Exception e) {
}
}
return fileSuccess;
}
/**
* Event handler for the file writer.
*/
public void dataSinkUpdate(DataSinkEvent evt) {
if (evt instanceof EndOfStreamEvent) {
synchronized (waitFileSync) {
fileDone = true;
waitFileSync.notifyAll();
}
} else if (evt instanceof DataSinkErrorEvent) {
synchronized (waitFileSync) {
fileDone = true;
fileSuccess = false;
waitFileSync.notifyAll();
}
}
}
public static void main(String arg[]) {
try {
String args[] = { "-w 100 -h 100 -f 100 -o F:\\test.mov F:\\Text69.jpg F:\\Textnew.jpg" };
if (args.length == 0)
prUsage();
// Parse the arguments.
int i = 0;
int width = -1, height = -1, frameRate = 1;
Vector inputFiles = new Vector();
String outputURL = null;
while (i < args.length) {
if (args[i].equals("-w")) {
i++;
if (i >= args.length)
width = new Integer(args[i]).intValue();
} else if (args[i].equals("-h")) {
i++;
if (i >= args.length)
height = new Integer(args[i]).intValue();
} else if (args[i].equals("-f")) {
i++;
if (i >= args.length)
frameRate = new Integer(args[i]).intValue();
} else if (args[i].equals("-o")) {
System.out.println("in ou");
i++;
System.out.println(i);
if (i >= args.length)
outputURL = args[i];
System.out.println(outputURL);
} else {
System.out.println("adding"+args[i]);
inputFiles.addElement(args[i]);
}
i++;
}
inputFiles.addElement("F:\\Textnew.jpg");
outputURL = "F:\\test.mov";
System.out.println(inputFiles.size() + outputURL);
if (outputURL == null || inputFiles.size() == 0)
prUsage();
// Check for output file extension.
if (!outputURL.endsWith(".mov") && !outputURL.endsWith(".MOV")) {
System.err.println("The output file extension should end with a .mov extension");
prUsage();
}
width = 100;
height = 100;
if (width < 0 || height < 0) {
System.err.println("Please specify the correct image size.");
prUsage();
}
// Check the frame rate.
if (frameRate < 1)
frameRate = 1;
// Generate the output media locators.
MediaLocator oml;
oml = createMediaLocator(outputURL);
System.out.println("Media" + oml);
if (oml == null) {
System.err.println("Cannot build media locator from: " + outputURL);
// //System.exit(0);
}
System.out.println("Before change");
System.out.println(inputFiles.size());
JpegImagesToMovie imageToMovie = new JpegImagesToMovie();
boolean status = imageToMovie.doIt(width, height, frameRate, inputFiles, oml);
System.out.println("Status"+status);
//System.exit(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void prUsage() {
System.err.println(
"Usage: java JpegImagesToMovie -w <width> -h <height> -f <frame rate> -o <output URL> <input JPEG file 1> <input JPEG file 2> ...");
//System.exit(-1);
}
/**
* Create a media locator from the given string.
*/
static MediaLocator createMediaLocator(String url) {
System.out.println(url);
MediaLocator ml;
if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null)
return ml;
if (url.startsWith(File.separator)) {
if ((ml = new MediaLocator("file:" + url)) != null)
return ml;
} else {
String file = "file:" + System.getProperty("user.dir") + File.separator + url;
if ((ml = new MediaLocator(file)) != null)
return ml;
}
return null;
}
///////////////////////////////////////////////
//
// Inner classes.
///////////////////////////////////////////////
/**
* A DataSource to read from a list of JPEG image files and turn that into a
* stream of JMF buffers. The DataSource is not seekable or positionable.
*/
class ImageDataSource extends PullBufferDataSource {
ImageSourceStream streams[];
ImageDataSource(int width, int height, int frameRate, Vector images) {
streams = new ImageSourceStream[1];
streams[0] = new ImageSourceStream(width, height, frameRate, images);
}
public void setLocator(MediaLocator source) {
}
public MediaLocator getLocator() {
return null;
}
/**
* Content type is of RAW since we are sending buffers of video frames
* without a container format.
*/
public String getContentType() {
return ContentDescriptor.RAW;
}
public void connect() {
}
public void disconnect() {
}
public void start() {
}
public void stop() {
}
/**
* Return the ImageSourceStreams.
*/
public PullBufferStream[] getStreams() {
return streams;
}
/**
* We could have derived the duration from the number of frames and
* frame rate. But for the purpose of this program, it's not necessary.
*/
public Time getDuration() {
return DURATION_UNKNOWN;
}
public Object[] getControls() {
return new Object[0];
}
public Object getControl(String type) {
return null;
}
}
/**
* The source stream to go along with ImageDataSource.
*/
class ImageSourceStream implements PullBufferStream {
Vector images;
int width, height;
VideoFormat format;
int nextImage = 0; // index of the next image to be read.
boolean ended = false;
public ImageSourceStream(int width, int height, int frameRate, Vector images) {
this.width = width;
this.height = height;
this.images = images;
format = new JPEGFormat(new Dimension(width, height), Format.NOT_SPECIFIED, Format.byteArray,
(float) frameRate, 75, JPEGFormat.DEC_422);
}
/**
* We should never need to block assuming data are read from files.
*/
public boolean willReadBlock() {
return false;
}
/**
* This is called from the Processor to read a frame worth of video
* data.
*/
public void read(Buffer buf) throws IOException {
// Check if we've finished all the frames.
if (nextImage >= images.size()) {
// We are done. Set EndOfMedia.
System.err.println("Done reading all images.");
buf.setEOM(true);
buf.setOffset(0);
buf.setLength(0);
ended = true;
return;
}
String imageFile = (String) images.elementAt(nextImage);
nextImage++;
System.err.println(" - reading image file: " + imageFile);
// Open a random access file for the next image.
RandomAccessFile raFile;
raFile = new RandomAccessFile(imageFile, "r");
byte data[] = null;
// Check the input buffer type & size.
if (buf.getData() instanceof byte[])
data = (byte[]) buf.getData();
// Check to see the given buffer is big enough for the frame.
if (data == null || data.length < raFile.length()) {
data = new byte[(int) raFile.length()];
buf.setData(data);
}
// Read the entire JPEG image from the file.
raFile.readFully(data, 0, (int) raFile.length());
System.err.println(" read " + raFile.length() + " bytes.");
buf.setOffset(0);
buf.setLength((int) raFile.length());
buf.setFormat(format);
buf.setFlags(buf.getFlags() | buf.FLAG_KEY_FRAME);
// Close the random access file.
raFile.close();
}
/**
* Return the format of each video frame. That will be JPEG.
*/
public Format getFormat() {
return format;
}
public ContentDescriptor getContentDescriptor() {
return new ContentDescriptor(ContentDescriptor.RAW);
}
public long getContentLength() {
return 0;
}
public boolean endOfStream() {
return ended;
}
public Object[] getControls() {
return new Object[0];
}
public Object getControl(String type) {
return null;
}
}
}
I am getting
Cannot create the DataSink: javax.media.NoDataSinkException: Cannot find a DataSink for: com.sun.media.multiplexer.BasicMux$BasicMuxDataSource#d7b1517
javax.media.NoDataSinkException: Cannot find a DataSink for: com.sun.media.multiplexer.BasicMux$BasicMuxDataSource#d7b1517
at javax.media.Manager.createDataSink(Manager.java:1894)
at com.ecomm.pl4mms.test.JpegImagesToMovie.createDataSink(JpegImagesToMovie.java:168)
at com.ecomm.pl4mms.test.JpegImagesToMovie.doIt(JpegImagesToMovie.java:104)
at com.ecomm.pl4mms.test.JpegImagesToMovie.main(JpegImagesToMovie.java:330)
Please help me to resolve this and let me what can be the cause of this
I am using java 1.8 and trying to create video with jpeg images and using
javax.media to perform this action. and i followed http://www.oracle.com/technetwork/java/javase/documentation/jpegimagestomovie-176885.html
to write the code
From experiment, this exception is thrown when the output file cannot be created (in your case "F:\\test.mov"). Check that the path is valid and that the application has write permission on it.
I recommend constructing a platform agnostic path somewhere under user.home e.g:
System.getProperty("user.home") + File.separator + "test.mov"
In Windows you need to use the file URL starting with file://, see https://github.com/agomezmoron/screen-recorder/issues/6#issuecomment-547072889

Java How to send data over network VIA a UI button

I'm learning about sockets and how server/client communicates.
So far, I have my protocols figured out and managed to simulate a synthetic TCP three-way-handshake:
Client successfully connects to server and sends SYN.
Server receives SYN and replies SYNACK to client.
Client receives SYNACK, and replies ACK to server.
Thats it, all this is linearly executed in the Run() method under a while(true) loop of my Runnable client service in a new Thread. I don't know how a Button in the GUI class can tell my Client Service to send a specific packet when, say, a specific button in the UI is pressed while the service runs in a different thread.
I have an idea but correct me on this: somehow add ActionListeners for all the buttons in my GUI inside the Service class instead of the GUI..
Thanks.
PS. I'm using DataInputStream and DataOutputStream to read/write data from/to socket stream.
ClientService.java:
public class ClientService implements Runnable, GameProtocol {
private Socket socket;
private int clientNumber;
private GameClient client;
private JTextArea clientConsole;
private DataInputStream fromServer;
private DataOutputStream toServer;
public ClientService(Socket aSocket, GameClient aClient, JTextArea textArea) {
this.socket = aSocket;
this.client = aClient;
this.clientConsole = textArea;
}
private void buildStreams() throws Exception {
this.fromServer = new DataInputStream(this.socket.getInputStream());
this.toServer = new DataOutputStream(this.socket.getOutputStream());
}
public void sendPacket(int data) {
try {
this.toServer.writeInt(data);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public void flushPacket() {
try {
this.toServer.flush();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public void run() {
try {
try {
buildStreams();
toServer.writeInt(PLAYER_SYN); // start synthetic three way handshake
toServer.flush();
if(fromServer.readInt() == SERVER_SYNACK) {
this.clientNumber = fromServer.readInt();
clientConsole.append("Client number from Server: " + clientNumber + "\n");
toServer.writeInt(PLAYER_ACK);
toServer.writeInt(this.clientNumber);
toServer.flush();
}
else {
clientConsole.append("Client -> Server Sync failed. Can't proceed.\n");
toServer.writeInt(PLAYER_QUIT);
toServer.flush();
socket.close();
System.exit(-1);
}
executeCommand();
} finally {
socket.close();
}
} catch (Exception e) {
System.out.println("Client Service: " + e.getMessage());
}
}
private void executeCommand() throws Exception {
boolean quit = false;
while(!quit) {
int command = -14324;
if(fromServer.available() > 0) {
command = fromServer.readInt();
}
switch (command) {
case WINNER:
clientConsole.append("You Win.\n");
break;
case LOSER:
clientConsole.append("You Lost.\n");
break;
case ENABLE_TURN:
client.enableTurn();
break;
case DISABLE_TURN:
client.disableTurn();
break;
}
}
}
}
GameClient.java:
public class GameClient extends JFrame implements GameProtocol {
/**
* TextArea size.
*/
private final int
TEXTAREA_ROWS = 5,
TEXTAREA_COLS = 40;
/**
* Client window size, unadjustable.
*/
private final int
FRAME_W = 535,
FRAME_H = 600;
// for Assignment 10
private Socket socket;
private DataOutputStream toServer;
private DataInputStream fromServer;
/**
* ArrayList of type Cards, by default, holds 20 cards.
*/
private ArrayList<Card> cards;
/**
* Console for debugging.
*/
private JTextArea gameConsole;
/**
* Button to terminate game
*/
private JButton quitButton;
/**
* Main Frame panels, cardsPanel and consolePanel are sub-panels of mainPanel.
*/
private JPanel mainPanel, cardsPanel, consolePanel;
/**
* Builds packets to be sent to the server
*/
private Packet packet;
/**
* players points, accumulated.
*/
private int points = 0;
/**
* card choice 1
*/
private int choice1 = -1;
/**
* card choice 2
*/
private int choice2 = -1;
/**
* for building packet arguments
*/
private static int packetBuilderCount = 0;
/**
* Counter for outbound and inbound packets
*/
private static int packetNumber = 1;
/**
* for timing out cards when recieving no match
*/
private Timer timer;
/**
* true when user is allowed to pick cards.
* false when another user is true
*/
private boolean isTurn = true;
// service
private ClientService service;
/**
* default contrustor. Builds JFrame and all components.
*/
public static void main(String[] args) {
new GameClient();
}
public GameClient() {
packet = new Packet();
buildButton();
buildCards();
addEventToCards(); // adds actionlistener to each card.
buildPanel();
buildTimer();
buildFrame();
buildConnection(); // for assignment 10
}
private void buildConnection() {
try {
this.socket = new Socket(HOST, PORT);
// this.toServer = new DataOutputStream(socket.getOutputStream());
// this.fromServer = new DataInputStream(socket.getInputStream());
gameConsole.append("Socket Connected\n");
service = new ClientService(socket, this, this.gameConsole);
new Thread(service).start();
} catch (SecurityException ex) {
System.out.println("Check your firewall or antivirus. Unable to establish connection to server.");
} catch (UnknownHostException ex) {
System.out.println("Host can't be found. Unable to establish connection to server.");
} catch (ConnectException ex) {
System.out.println("Connection refused. What now?");
ex.printStackTrace();
// ex.printStackTrace();
} catch (IOException ex) {
System.out.println("fuck......");
}
}
/**
* initializes the timer.
*/
private void buildTimer() {
int delay = 3000; // wait for 3000ms
timer = new Timer(delay, new AbstractAction() {
/**
* event handler for timer. Flips the cards back to face down position.
*/
#Override
public void actionPerformed(ActionEvent ae) {
flipCard(choice1, 10);
flipCard(choice2, 10);
}
});
}
/**
* Initializes JFrame
*/
private void buildFrame() {
this.setSize(FRAME_W, FRAME_H);
setResizable(false);
this.add(mainPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
/**
* Initializes and compiles panels together. Adds Cards to panels
*/
private void buildPanel() {
gameConsole = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLS);
JScrollPane scrollConsole = new JScrollPane(gameConsole);
scrollConsole.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
gameConsole.setEditable(false);
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(535, 475));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
cardsPanel = new JPanel(new GridLayout(4, 5, 20, 20));
for(int i = 0; i < 20; i++) {
cardsPanel.add(this.cards.get(i));
}
consolePanel = new JPanel();
consolePanel.add(scrollConsole);
consolePanel.add(quitButton);
mainPanel.add(cardsPanel);
mainPanel.add(consolePanel);
}
/**
* builds quit button, adds action listener to handle click
*/
private void buildButton() {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> {
buildQuitPacket();
});
}
/**
* builds 20 Card object.
*/
private void buildCards() {
cards = new ArrayList<Card>();
Card temp;
for(int i = 0; i < 20; i++) {
temp = new Card();
cards.add(temp);
}
}
/**
* adds actionlistener to all 20 card objects.
*/
private void addEventToCards() {
for(int i = 0; i < 20; i++) {
final int INDEX = i;
cards.get(i).addActionListener(e -> buildButtonPacket(this.cards.get(INDEX).getId()));
}
}
/**
* Builds and sends a Packet when a card is chosen
* #param value The card ID which was chosen.
*/
private void buildButtonPacket(int value) {
if(!isTurn) {
this.gameConsole.append("Its not you're turn.\n");
return;
}
if(packetBuilderCount == 0) {
packet.writeCommandToPacket(PICKED_CARDS);
packet.writeValueToPacket(value);
packetBuilderCount++;
choice1 = value;
}
else if(packetBuilderCount == 1) {
packet.writeValueToPacket(value);
packetBuilderCount = 0;
writeToConsoleOutBound(packet.toString());
choice2 = value;
// try{
// out.print(this.packet.getPacket());
// out.flush();
// } catch (Exception e) {
// gameConsole.append("could not send packet.\n");
// }
packet.clearPacket();
}
}
/**
* For handling commands from recieved Packet
* #param recieved the Packet object recieved. Gets and handles command and possible arguments that follows.
* See GameProtocol class for packet command definitions.
*/
public void handlePacket(Packet recieved) {
int cmd = recieved.getCommand();
writeToConsoleInBound(recieved.toString());
int arg1 = -99;
int arg2 = -99;
switch (cmd) {
case SERVER_SYNACK:
arg1 = recieved.getFirstArg();
if(arg1 == 1) {
this.isTurn = true;
}
else if (arg1 == 0) {
this.isTurn = false;
}
else {
writeToConsoleError("Server sync failed. Terminating..");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
writeToConsoleError(ex.getMessage());
} finally {
System.exit(-1);
}
}
break;
case CARDMATCH:
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 > 9) {
arg1 = 9;
}
if(arg2 > 9) {
arg2 = 9;
}
flipCard(choice1, arg1);
flipCard(choice2, arg2);
break;
case CARDNOMATCH:
// System.out.println("CLIENT: im going to sleep");
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 > 9) {
arg1 = 9;
}
if(arg2 > 9) {
arg2 = 9;
}
flipCard(choice1, arg1);
flipCard(choice2, arg2);
this.cardsPanel.revalidate();
this.cardsPanel.repaint();
this.consolePanel.revalidate();
this.consolePanel.repaint();
timer.setRepeats(false); //the timer should only go off once
timer.start();
break;
case SHOW_CARD:
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 < 0 || arg1 > 19) {
writeToConsoleError(" BAD PACKET ARGUMENT 1, \nCard index out of bounds");
}
else if(arg2 < 0 || arg2 > 10) {
writeToConsoleError(" BAD PACKET ARGUMENT 2, \nImage index out of bounds");
}
else {
flipCard(arg1, arg2);
}
break;
case ENABLE_TURN:
this.isTurn = true;
break;
case DISABLE_TURN:
this.isTurn = false;
break;
case WINNER:
this.gameConsole.append("You win!\n");
break;
case LOSER:
this.gameConsole.append("You lost :( \n");
break;
case ADD_POINTS:
arg1 = recieved.getFirstArg();
this.points += arg1;
this.gameConsole.append("** Gained " + Integer.toString(arg1) + ", you now have " + Integer.toString(this.points) + " points.\n");
break;
case OTHER_QUIT:
this.gameConsole.append("Other player forfeited. You win!\n");
break;
}
}
/**
* Builds a packet containing QUIT when quit button is pressed
* Only available when isTurn == true.
*/
private void buildQuitPacket() {
if(this.isTurn == false) {
this.gameConsole.append("You can only quit when it is your turn.");
return;
}
service.sendPacket(PLAYER_QUIT);
service.flushPacket();
// this.service.sendPacket(PLAYER_QUIT);
// this.service.flushPacket();
System.exit(0);
}
/**
* Writes the outgoing packet to the game console.
* #param msg the actual packet message.
*/
public void writeToConsoleOutBound(String msg) {
this.gameConsole.append(Integer.toString(packetNumber++) + ": SENDING: " + msg + "\n");
}
/**
* Writes the incoming packet to the game console.
* #param msg the actual packet message.
*/
public void writeToConsoleInBound(String msg) {
this.gameConsole.append(Integer.toString(packetNumber++) + ": RECEIVING: " + msg + "\n");
}
/**
* Writes an error to the game console.
* #param msg the error message.
*/
public void writeToConsoleError(String msg) {
this.gameConsole.append("Error handling packet number " + Integer.toString(packetNumber) + "." + msg + "\n");
}
/**
* Flips a Card object and show an image
* #param whichCard the card ID which will be flipped.
* #param imgID the image which will be shown on the flipped card.
*/
public void flipCard(int whichCard, int imgID) {
this.cards.get(whichCard).flipCard(imgID);
}
/**
* Accumulates points.
* #param amt the amount to be added.
*/
public void gainPoints(int amt) {
this.points += amt;
}
public void enableTurn() {
this.isTurn = true;
}
public void disableTurn() {
this.isTurn = false;
}
}
Your connection to a socket works because it is in a constructor, no calls to modify a rendered element have been made (say update a button's text). Your client service needs a loop waiting for requests made by the UI, otherwise you would need to create a thread with every request made by the UI. It will become a bottleneck, specially in a game when one user action can trigger several UI updates. Look at the code posted you should follow more or less that pattern
package so;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
class ClientService implements Runnable{
JLabel label;
ConcurrentLinkedQueue<Long> work;
#Override
public void run() {
Long i = null;
try{
while(true){
if ((i = work.poll()) != null){
final long ii = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText(ii + "");
}
});
}
Thread.sleep(10);
}
}
catch(Exception x){
}
}
}
class GameClient extends JFrame{
Thread worker;
ConcurrentLinkedQueue<Long> work;
private JLabel label;
private JButton button;
GameClient(){
setLayout(new GridLayout(2, 1));
label = new JLabel("Label");
button = new JButton("Button");
button.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
work.add(System.currentTimeMillis());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
this.add(label);
this.add(button);
work = new ConcurrentLinkedQueue<Long>();
ClientService cs = new ClientService();
cs.label = this.label;
cs.work = this.work;
this.worker = new Thread(cs);
this.worker.start();
}
}
class SOCLass {
public static void main(String[] args){
SOCLass m = new SOCLass();
GameClient frame = new GameClient();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.worker.interrupt();
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
}

Date and time not updating

My program uses dates to check when an engineer has visited a machine. The only problem with this is that the date does not remain up to date. The date and time that the machine displays is the exact time that the machine was started. Not when the button was clicked. Any assistance would be helpful.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
You never re-initialize date, you're just updating storedDate with the existing date in login. You could change this line in login
storedDate = date;
to
storedDate = new Date();
And then (I think) you can remove date.
Date does not keep a persistent current time. Date is backed by a long that is set when the Date is instantiated and is never changed.
You can either make a new Date() in your logon method, so it would be created when the user logs on, or just use System.currentTimeMillis() to get the current time as a long.

How to display each instance of a user logging into a server with a button click?

I have been tasked with creating a recycling machine server which a engineer can log into empty, reset, etc. Each time the engineer logs into a machine it creates a string that says "Engineer has logged in on this (date)". I need to create a JButton that prints out each instance of this string being written.
So when pressed it prints out something like this:
"Engineer visited this machine on 01/01/2016"
"Engineer visited this machine on 02/01/2016"
"Engineer visited this machine on 05/04/2016"
The log in function is working and uses stored cookies to figure out if the user has input the correct information. I am however unable to figure out how to print out this summary of visits via one button click. Any help would be appreciated.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits = 0;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = new Date();
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
So after working around with the code for a while I discovered that there was one simple piece of code that was causing it to not display the information I wanted.
private int numberOfVisits = 0;
Defining the int as a 0 to begin with caused the code to reset the value of the int every time I pressed the "visits" button.
Removing the 0 fixed this issue.
private int numberOfVisits;

RMS stored values are not permanently available in J2ME emulator

I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session

Categories