I have been working on a class project using javafx and I have to serialize all the data and load all the data to project when the project is launched. I was able to serialize the data from the textfield but unable to load the serialized data to the textfield.
Here is my serialization code:
public class Controller {
Employee nameFile = new Employee();
#FXML
private TextField firstNameField;
#FXML
private TextField lastNameField;
public void getinfo() throws FileNotFoundException, IOException {
String filename = "file.abc";
nameFile.setFirstNameField(firstNameField.getText());
nameFile.setLastNameField(lastNameField.getText());
// Serialization
try
{
//Saving of object in a file
File employeeName = new File("file.abc");
FileOutputStream file = new FileOutputStream(employeeName);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(nameFile);
out.close();
file.close();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Saved");
alert.setHeaderText(null);
alert.setContentText("Your Information has been saved!");
alert.showAndWait();
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
}
public void setDataField() {
try {
// Reading the object from a file
FileInputStream file = new FileInputStream("file.abc");
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
nameFile = (Employee) in.readObject();
/*How to I pull that data to the textfield firstnamefield and lastnamefield this method is invoked */
in.close();
file.close();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException is caught");
} catch (IOException ex) {
System.out.println("IOException is caught");
}
}
}
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
nameFile = (Employee) in.readObject();
// *** Here we set data back to text fields ***
firstNameField.setText(nameFile.getFirstNameField());
lastNameField.setText(nameFile.getLastNameField());
Related
I am creating javafx application where I have this case that I need to listen for data sent over Bluetooth.
I have one fxml window on which I need to initialize Bluetooth and start listening from data.
Following is my Code for fxml controller:
//all imports
public class NewBarcodeInvoicePaneController implements Initializable{
private BluetoothController bc;
public BluetoothController getBc() {
return bc;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
bc = new BluetoothController();
new Thread(bc).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And BluetoothController is task where I initialize bluettoth and listen to the data
public class BluetoothController extends Task<Void> {
#Override
protected Void call() throws Exception {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
System.err.println("THIS IS HAPENING");
connection = notifier.acceptAndOpen();
System.err.println("HAPENING???????????????????????????");
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
System.out.println(stringObj);
});
System.out.println("AFTER DATA RECIEVED");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
}
It Works fine if I send data over bluetooth and blocking call to notifier.acceptAndOpen() is unblocked.
My problem is when we do not pass any data and I just want to close the window I opened..
It still have blocking call open with extra thread by the task.
I tried to cancel BluetoothController task in Main controller where I open this window like following
private void openNewBarcodeInvoicePane(ActionEvent ae) {
//following are custom classes to open windows from fxml and getting controller back for further manipulation
PostoryModalWindow modalWindow = new PostoryModalWindow();
modalWindow.openNewModalPaneWithParent("New Invoice", "fxml/newbarcodeinvoicepane.fxml", ae);
//getting controller object
NewBarcodeInvoicePaneController controller = (NewBarcodeInvoicePaneController) modalWindow.getDswFromController();
controller.getWindowStage().showAndWait();
BluetoothController bc = controller.getBc();
if(bc != null){
System.err.println("CANCELLING");
bc.cancel(true);
}
}
But it doesn't throw InterrupttedExeption (In which I might have Choice to close Bluetooth thread) and after research I found that waiting on Socket doesn't work on interrupt.
Any help on this?
Thanks
Got Solution After Some Research.
I just added new task to call notifier.acceptAndOpen();
And added method to close Bluetooth notifier.
public class BluetoothController extends Task<Void> {
private final ObservableList<Item> items = FXCollections.observableArrayList();
public ObservableList<Item> getItems() {
return items;
}
StreamConnectionNotifier notifier;
#Override
protected Void call() throws Exception {
try {
BluetoothConnectionTask bct = new BluetoothConnectionTask(items);
new Thread(bct).start();
Thread.sleep(2000);
notifier = bct.getNotifier();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public void cancelandExit() {
try {
if (notifier != null) {
notifier.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Here is new task for blocking call
public class BluetoothConnectionTask extends Task<Void>{
private StreamConnectionNotifier notifier;
private StreamConnection connection;
private ObservableList<Item> items = FXCollections.observableArrayList();
public StreamConnection getConnection() {
return connection;
}
public StreamConnectionNotifier getNotifier() {
return notifier;
}
public BluetoothConnectionTask(ObservableList<Item> is){
items = is;
}
#Override
protected Void call() throws Exception {
try {
LocalDevice local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
connection = notifier.acceptAndOpen();
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
ItemDAO idao = new ItemDAO();
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
String barcode = (String) stringObj;
Item i = idao.getItemByBarCode(barcode);
System.err.println("Adding Item "+i.getName());
items.add(i);
});
System.out.println("AFTER DATA RECIEVED");
return null;
}
}
Now for cancelling closing my bluetooth thread I am calling cancelandExit() after window is closed.
I have a problem with Titan 0.5.1. I try to upgrade Titan 0.4.4 to 0.5.1. Currently, I use berkeleyje and i configure like this :
BaseConfiguration conf = new BaseConfiguration();
// Storage info
conf.setProperty("storage.directory", directory + File.separator + DB_NAME);
conf.setProperty("storage.backend", "berkeleyje");
// Class info storage
conf.setProperty("attributes.allow-all", "true");
conf.setProperty("attributes.custom.attribute1.attribute-class", "model.Property");
conf.setProperty("attributes.custom.attribute1.serializer-class", "PropertySerializer");
TitanGraph graph = TitanFactory.open(conf);
For serialize my object i use :
public class PropertySerializer implements AttributeSerializer<Property> {
#Override
public Property read(ScanBuffer buffer) {
Property object = null;
ArrayList<Byte> records = new ArrayList<Byte>();
try {
while (buffer.hasRemaining()) {
records.add(Byte.valueOf(buffer.getByte()));
}
Byte[] bytes = records.toArray(new Byte[records.size()]);
ByteArrayInputStream bis = new ByteArrayInputStream(ArrayUtils.toPrimitive(bytes));
ObjectInput in = new ObjectInputStream(bis);
object = (Property) in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
#Override
public void write(WriteBuffer out, Property attribute) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput outobj;
outobj = new ObjectOutputStream(bos);
outobj.writeObject(attribute);
byte[] propertybyte = bos.toByteArray();
for (int i = 0; i < propertybyte.length; i++) {
out.putByte(propertybyte[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void verifyAttribute(Property value) {
// TODO Auto-generated method stub
}
#Override
public Property convert(Object value) {
// TODO Auto-generated method stub
return null;
}
}
Typically, i add a property like this :
Vertex r = this.model.addVertex(null);
Property p = new Property();
r.setProperty("object", p);
this.model.commit();
But i obtain this error :
Exception in thread "main"
com.thinkaurelius.titan.core.TitanException: Could not commit
transaction due to exception during persistence at
com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx.commit(StandardTitanTx.java:1310)
at
com.thinkaurelius.titan.graphdb.blueprints.TitanBlueprintsGraph.commit(TitanBlueprintsGraph.java:60)
Caused by: com.thinkaurelius.titan.core.TitanException: Serializer
Restriction: Cannot serialize object of type: class
.model.Property at
com.thinkaurelius.titan.graphdb.database.serialize.StandardSerializer$StandardDataOutput.writeClassAndObject(StandardSerializer.java:160)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writePropertyValue(EdgeSerializer.java:383)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writePropertyValue(EdgeSerializer.java:377)
at
com.thinkaurelius.titan.graphdb.database.EdgeSerializer.writeRelation(EdgeSerializer.java:293)
at
com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.prepareCommit(StandardTitanGraph.java:485)
at
com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.commit(StandardTitanGraph.java:613)
at
com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx.commit(StandardTitanTx.java:1299)
Can you help me please ? Because, with 0.4.4 version it worked. The new documentation don't help me.
Thanks in advance
I have a CAS consumer AE which is expected to iterates over CAS objects in a pipeline, serialize them and add the serialized CASs to an xml file.
public class DataWriter extends JCasConsumer_ImplBase {
private File outputDirectory;
public static final String PARAM_OUTPUT_DIRECTORY = "outputDir";
#ConfigurationParameter(name=PARAM_OUTPUT_DIRECTORY, defaultValue=".")
private String outputDir;
CasToInlineXml cas2xml;
public void initialize(UimaContext context) throws ResourceInitializationException {
super.initialize(context);
ConfigurationParameterInitializer.initialize(this, context);
outputDirectory = new File(outputDir);
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
}
#Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
String file = fileCollectionReader.fileName;
File outFile = new File(outputDirectory, file + ".xmi");
FileOutputStream out = null;
try {
out = new FileOutputStream(outFile);
String xmlAnnotations = cas2xml.generateXML(jCas.getCas());
out.write(xmlAnnotations.getBytes("UTF-8"));
/* XmiCasSerializer ser = new XmiCasSerializer(jCas.getCas().getTypeSystem());
XMLSerializer xmlSer = new XMLSerializer(out, false);
ser.serialize(jCas.getCas(), xmlSer.getContentHandler());*/
if (out != null) {
out.close();
}
}
catch (IOException e) {
throw new AnalysisEngineProcessException(e);
}
catch (CASException e) {
throw new AnalysisEngineProcessException(e);
}
}
I am using it inside a pipeline after all my annotators, but it couldn't read CAS objects (I am getting NullPointerException at jCas.getCas()). It looks like I don't seem to understand the proper usage of CAS consumer. I appreciate any suggestions.
I am creating a Portlet project using Vaadin and Liferay6.0.
I need to upload a csv file from ui and read the file.
My class is as fllows:
#SuppressWarnings("serial")
public void init() {
Window window = new Window("Vaadin Portlet Application");
setMainWindow(window);
window.addComponent(new Label("Hello Vaadin user!"));
window.addComponent(new Label("We are here"));
final TextField tf = new TextField("Device Name:");
// Create the Upload component.
final Upload upload =
new Upload("Upload the file here", null);
// Use a custom button caption instead of plain "Upload".
upload.setButtonCaption("Upload Now");
try{
System.out.println("I am here only");
final DeviceManager dManager = new DeviceManager();
final DeviceSoap[] devices = dManager.getAll();
//getDeviceByName("207.20.47.137");
for (DeviceSoap deviceSoap : devices) {
window.addComponent(new Label("Device Name! "+deviceSoap.getName()));
}
window.addComponent(tf);
Button submitBttn = new Button("Add Device");
Button updateBttn = new Button("Update Device");
window.addComponent(submitBttn);
// Handle button clicks
submitBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = new DeviceSoap();
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
updateBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = devices[1];
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
upload.addListener((Upload.SucceededListener) this);
upload.addListener((Upload.FailedListener) this);
window.addComponent(upload);
}catch(Exception e){
e.printStackTrace();
}
}
Thanks
Hiamsnhu
I'm doing the same thing, and in reading your code, I see that you forgot making:
window.addComponent(updateBttn);
Hope this works.
I use a servlet to access a folder outside the web container to load some graphics to web application by using GWT. I use the following snippet in servlet to test the idea:
String s = null;
File inputFile = new File("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
FileInputStream fin = null;
try {
fin = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte c[] = new byte[(int) inputFile.length()];
try {
fin.read(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fin.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String imgFolderPath = getServletContext().getRealPath("/")+"img";
File imgFolder = new File(imgFolderPath);
imgFolder.mkdir();
File newImage = new File("megan-fox.jpg");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(newImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fout.write(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
boolean success = newImage.renameTo(new File(imgFolderPath, newImage.getName()));
The code in servlet reads the image file from the specified folder in hard disk, creates a new folder called 'img' in war folder and copies to it the jpg file. Then it returns to the client the path to the image (for now hardcoded as) '/img/megan-fox.jpg'.
The client then uses the Image class in GWT with the returned path-string to display the image, like in the following snippet:
public void onSuccess(String result) {
String myImage = result;
image = new Image(myImage);
RootPanel.get().add(image);
closeButton.setFocus(true);
}
I need to know if there is a way to achieve the same result without using the 'intermediate' step of creating a folder in the web container root (optional) and copying the file there in order to access it with Image GWT class and display it?
updated: The original servlet class.
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the absolute path of the image
ServletContext sc = getServletContext();
// i want to load the image in the specified folder (outside the web container)
String filename = sc.getRealPath("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
resp.setContentType(mimeType);
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
// This is the method that is called from the client using GWT-RPC
public String greetServer(String input) throws IllegalArgumentException {
HttpServletRequest req = this.getThreadLocalRequest();
HttpServletResponse res = this.getThreadLocalResponse();
try {
doGet(req, res);
} catch (IOException e) {
e.printStackTrace();
}
// actually i dont know what that means but i thought i would have to returned something like the image's url?
return res.encodeURL("/img/image0.png");
}
}
I logically misused the method that was proposed to solve my problem. What is the correct way?
Sure, just have your servlet serve the image directly:
Set the Content-Type header to image/jpeg.
Write out image file contents to servlet response writer.
Here is an example.