Set Field Text, Java - user-interface

I have two classes. MetaDataExtractor(GUI) and MetaData.
MetaData has the method which extracts the metadata from an image. MetaDataExtractor is designed to display the data in a JTextPane. (Please excuse the class names. I know it's a little confusing. I'm fairly new to Java).
MetaDataExtractor:
LongitudeField.setText("" + MetaDataTags.getLongitude());
MetaData:
public String getLongitude() {
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
String Longitude = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitude;
}
If I set the longitude to be displayed in the JTextPane, it returns "null". If however, I set it to print out on the command line, it prints the longitude fine?
Please excuse me if its a simple solution. I'm still getting to grips with Java.

Java is case sensitive and declare firstly your variable outside of try & catch statement.
Use a IDE like Eclipse to reduce syntax errors like these.
so you should have :
public String getLongitude() {
String longitudeDesc ="";
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
longitudeDesc = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitudeDesc ;
}

Related

Render Unicode (Hex) characters in PDF file using ITextRenderer

I am using Thymeleaf with Spring boot, I am generating PDF file from Thymeleaf template using ITextRenderer, I have some Unicode (HEX) value to display currency symbols but it does't render Unicode characters
I have taken currency symbol Unicode from this URL Currency Unicode reference
Here below is my Java code to generate PDF from Thymeleaf template
String html = templateEngine.process("templates/Quote", context);
FileOutputStream os = null;
File parentDirectory=null;
try {
OutputStream outputStream = new FileOutputStream(quoteNumber+".pdf");
BufferedOutputStream bs= new BufferedOutputStream(outputStream);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(bs,true);
outputStream.close();
Assert.notNull("greeting", "The templateName can not be null");
final Context ctx = new Context();
String processedHtml = templateEngine.process("greeting", ctx);
String fileName = UUID.randomUUID().toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
log.error("File not found >>> ",e);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
log.error("IO Exception >>> ",e);
}
finally {
if (os != null) {
try {
os.close();
} catch (IOException e) { /*ignore*/ }
}
}
Please help me to display currency symbols in generated PDF

Transform Optional String and return Date in Java 8?

I am currently parsing a nullable String to a Date. I try to use Optional to avoid using if statement. Here is what I have written so far :
Client client = new Client();
Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
try {
client.setBirthDate(DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
Is it possible to transform this lambda so I can make it a method similar to the following but java 8 style?
private Date parse(String complexString) {
Date birthDate = null;
if (complexString != null) {
try {
birthDate = DateUtils.parseDate(
StringUtils.substring(complexString, 0, 10),
new String[]{"yyyy-MM-dd"});
} catch (final ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
}
return birthDate;
}
Not sure how far you want to go, but you can start with
Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull())
.map((s) -> {
try {
return DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
You might also consider using flatMap instead of map and returning empty optional instead of throwing exception on error - depends on how you want to progress you flow.
On completely unrelated note, get rid of Date and use either joda or new java time classes ;)

Geocoder.getFromLocationName does not work for intersection address

I am trying to use Geocoder class in my App and found that Geocoder.getFromLocationName returns null if the address is intersection of two streets. Ex. "Quail Ave and Dunford Way, Sunnyvale, CA 94087" . However, the method works perfect for any other type address.
During Debug session, I could see the address parameter passed and reflects correctly, but "geocodeMatches" returns size(0) zero.
Appreciate any Help!!
public static List<Address> getGeoCode(#NonNull Context context, #NonNull String address){
try {
geocodeMatches = new Geocoder(context).getFromLocationName(address, 1);
if (!geocodeMatches.isEmpty())
{
return geocodeMatches;
}
} catch (IOException e) {
Log.e("ERROR", "Error to retrieve geocode" + e);
e.printStackTrace();
}
return geocodeMatches;
}
GeoCoder is working on NetworkLocationService. In some cases, NetworkLocationService is stopped working due to some reason. I don't know exact reason. But you can get address from google api in that case.
Hope below code will help you!
public static String GetLocationAddressFromLatLong(Context context, double latitude, double longitude) {
String finalAddress = "";
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
finalAddress = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1);
} else {
//Get address from Google api
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
+ longitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject location = Results.getJSONObject(0);
finalAddress = location.getString("formatted_address");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return finalAddress;
}

jTable that will listen to jDateChooser's 'textfield'?

Hello everyone I'm trying to make a scheduling system for my System and Analysis Design thesis and I am having trouble trying to connect/bind/make the jTable listen to the jDateChooser's input. Elaborately, I want my scheduling to be like this:
I choose a date in the jDateChooser
jTable will 'sort out' itself via the date inputted on the jDatechooser
is there anyway to do this?
For now all I have is a table propertyChangelistener:
private void sched_tablePropertyChangeListener(java.beans.PropertyChangeEvent evt) {
try{
String calendar = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ?";
ps= conn.prepareStatement(query);
ps.setString(1, calendar);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException ignore) {}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
Somehow when I run my application it doesn't seem to open if that block of code is on it which means I really did do something wrong. Can anyone change or tell me what I should do or where should I start with the jTable listening to the jDatechooser thing?
~Thanks in advance for those who will answer!~
Nevermind, turns out all I had to do was change the jDateChooser's Date Format since it wasn't exactly the same formatting hence I couldn't call anything from the database. If anyone's interested on what I did I'll just leave this here
private void jdcPropertyChange(java.beans.PropertyChangeEvent evt) {
try{
String d1 = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ? order by time,timezone";
ps = conn.prepareStatement(query);
ps.setString(1, d1);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null) {
try { conn.close();
} catch (SQLException ignore) {}
}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
What this does is that everytime I pick on a date from the jDateChooser(named it jdc) the table/database calls that date and sorts it out. Which is what I wanted.

How to make a save action that checks whether a 'save-as' has already been performed

I have researched and tried to refer back to my fileChooser.getSeletedFile() in my save as action but can not work out how to check whether or not a file has been created. Here is my attempted code so far:
Save as code(works well):
public void Save_As() {
fileChooserTest.setApproveButtonText("Save");
int actionDialog = fileChooserTest.showOpenDialog(this);
File fileName = new File(fileChooserTest.getSelectedFile() + ".txt");
try {
if (fileName == null) {
return;
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
outFile.write(this.jTextArea2.getText());//put in textfile
outFile.flush(); // redundant, done by close()
outFile.close();
} catch (IOException ex) {
}
}
"Save" code doesn't work:
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
File f = fileChooserTest.getSelectedFile();
try {
if (f.exists()) {
BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
String text = ((JTextArea) jTabbedPane1.getSelectedComponent()).getText();
bw1.write(text);
bw1.close();
} else {
Save_As();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Instead of storing an instance to the JFileChooser rather store an instance to the File (wich will be null before any save has been performed). In your SaveActionPerformed method check if the file is null. If it is null then do a Save_As and store the selected file in your file variable, if it is not null then do a normal save into the file.

Resources