I have some code, what loaded:
1) HSQLDB v. 2.2.8 bundle
2) Bundle with service:
package ihtika2.i_internalfunctions.service;
import com.google.code.ihtika.Vars.Ini;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.DriverManager;
/**
*
* #author Arthur
*/
public class InternalFunctions implements InternalFunctionsInterface {
// launch browser
public void launchBrowser(String uriStr) {
Desktop desktop;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
// launch browser
URI uri;
try {
uri = new URI("http://" + uriStr);
desktop.browse(uri);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
}
}
public void initDB() {
try {
Class.forName("org.hsqldb.jdbcDriver");
Ini.conn = DriverManager.getConnection("jdbc:hsqldb:file:Db/pages");
Ini.stmt = Ini.conn.createStatement();
Ini.rs = null;
Ini.rs = Ini.stmt.executeQuery("select count(1) as qwe from "
+ " information_schema.system_tables "
+ "where table_schem = 'PUBLIC'"
+ "and table_name = 'PAGES';");
Ini.rs.next();
if (Ini.rs.getInt("qwe") == 0) {
Ini.stmt.executeUpdate("CREATE SEQUENCE SEQU");
Ini.stmt.executeUpdate("CREATE CACHED TABLE PAGES (id bigint "
+ "GENERATED BY DEFAULT AS SEQUENCE SEQU PRIMARY KEY, "
+ "url varchar(7777), lastUpdateDate varchar(7777)) ");
Ini.stmt.executeUpdate("CREATE CACHED TABLE LINKDATA (id int, "
+ "nazvanie varchar(777), linkURL varchar(777), razmer varchar(777)) ");
Ini.stmt.executeUpdate("CREATE INDEX linkDataID ON LINKDATA (id)");
Ini.stmt.executeUpdate("CREATE INDEX pagesURL ON PAGES (url)");
}
} catch (Exception ex) {
Ini.logger.fatal("Error on DB init", ex);
}
}
}
3) Some bundle, what calls bundle number 2.
try {
ServiceReference[] refs = context.getServiceReferences(
InternalFunctionsInterface.class.getName(), "(Funct=IFuncts)");
if (refs == null) {
System.out.println("Not Found IFuncts on init");
} else {
InternalFunctions = (InternalFunctionsInterface) context.getService(refs[0]);
}
} catch (Exception ex) {
Ini.logger.fatal("Error on IFuncts init", ex);
}
InternalFunctions.initDB();
On executing I get error in logs:
[FATAL] 2012-08-02 20:18 root (InternalFunctions.java:initDB:61)
Error on DB init
java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver not found by ihtika2.I_InternalFunctions [7]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1460)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at ihtika2.i_internalfunctions.service.InternalFunctions.initDB(InternalFunctions.java:40)
at ihtika2.mainform.IC_MainForm.<init>(IC_MainForm.java:66)
at ihtika2.mainform.IC_MainForm$4.run(IC_MainForm.java:225)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Please, advice - how to use HSQLDB bundle in other bundle?
Answered by me:
The solution is using
DriverManager.registerDriver(new JDBCDriver());
Ini.conn = DriverManager.getConnection("jdbc:hsqldb:file:Db/pages");
insted of using
Class.forName("org.hsqldb.jdbcDriver");
Ini.conn = DriverManager.getConnection("jdbc:hsqldb:file:Db/pages");
Unfortunately this is a very OSGi unfriendly solution. You might want to take a look at H2. H2 implements the OSGi spec, it provides a org.osgi.service.jdbc.DataSourceFactory service. You might also want to raise a bug at the hsqldb project and ask for OSGi support, it is trivially to implement for them.
Related
When connecting to an Informix server via a Bean (or Jar - I've tried both) in an NSF, the nhttp task it spiking and staying spiked. I do not get this problem if the code is run in Eclipse. Here is what I trigger from an XPage (via a managed bean):
public void InformixSQLRS() {
try {
String url = "jdbc:informix-sqli://IPADDRESSHERE:PORTHERE/db_cra:INFORMIXSERVER=SERVERNAME;user=USERNAME;password=PASSWORD";
Class.forName("com.informix.jdbc.IfxDriver");
conn = DriverManager.getConnection(url);
System.out.println("After getting Driver");
String selectSQL = "SELECT FIRST 10 * FROM RtCSQsSummary ";
String whereSQL = "WHERE startdatetime >= TODAY ";
String orderbySQL = "ORDER BY startdatetime DESC";
String strsql = selectSQL + orderbySQL;
stmt = conn.createStatement();
System.out.println(strsql);
ResultSet rs = stmt.executeQuery(strsql);
System.out.println("after executeQuery");
ResultSetMetaData rsmd = rs.getMetaData();
int ncols = rsmd.getColumnCount();
int i, type;
String s = null;
for (i = 1; i < ncols; i++) {
System.out.println(
rsmd.getColumnLabel(i) + " " + rsmd.getColumnType(i));
}
stmt.close();
rs.close();
conn.close();
} catch (
SQLException e) {
System.out.println("ERROR: failed to connect!");
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
return;
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException se) {
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
System.out.println("Goodbye! (finally)");
}
System.out.println("Last call");
}
I am on DDE Release 9.0.1FP10 SHF81. I have the Informix JDBC driver jdbc-4.10.8.1.jar. I have tried putting it in the Jars element, and importing to WebContent/WEB_INF/lib. This happens on both a Domino server Release 9.0.1FP9HF63 on Linux 2.6.32-696.13.2.el6.x86_64 and my local running Windows 7.
I get this error: Exception in thread "Informix-PreparedStatementCacheCleanupThread". Debugged in DDE and found that "IfxSqliConnectCleaner-Thread-1" was taking up a lot of CPU. Suspending that thread let the CPU count to return to normal.
The process completes, printing the results, and the strings at the end of finally and the block. Closing the browser does not release nhttp.
This matches samples provided to connect to Informix. I'm not sure what is causing it to spike/peg for Domino. Is there something I can do to get the thread to release?
Currently, I have a repeat control with computed fields that display column values from a Domino view. In each row in the repeat control I have another computed field that executes a SQL query that returns a value from a SQL table. The SQL query has a parameter that uses one of the column values from the Domino view.
For the SQL computed field I wrote a function that instantiates a JDBC connection and then executes a SQL query for each row in the repeat control. The function looks like this (the pTextNo argument comes from one of the column values in the Domino view):
function getFormulaTextDetailRows(pTextNo){
if(pTextNo == null){return ""};
var con:java.sql.Connection;
try {
con = #JdbcGetConnection("as400");
vStatement = "SELECT TXSQN, TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? ORDER BY TXSQN";
var vParam = [pTextNo];
var resultset:java.sql.ResultSet = #JdbcExecuteQuery(con, vStatement, vParam);
var returnList = "<ul>";
//format the results
while(resultset.next()){
returnList += ("<li>" + resultset.getString("TXDTA").trim() + "</li>");
}
returnList += "</ul>";
}catch(e){
returnList = e.toString()
}finally{
con.close();
}
return returnList;
}
This works fine but I'm sure this isn't the most efficient way of utilising the JDBC connection. Opening and closing a JDBC connection on each row in the repeat control isn't right and I'm concerned that when more than one person opens the XPage the server will run into difficulties with the number of open connections.
After doing some research on the internet it seems I should be using a jdbcConnectionManager on the page.
I added a jdbcConnectionManager to my custom control and also added a jdbcQuery data source to the panel that holds the repeat control. The jdbcConnectionManager looks like this:
<xe:jdbcConnectionManager
id="jdbcConnectionManager1"
connectionName="as400">
</xe:jdbcConnectionManager>
And the jdbcQuery data source looks like this:
<xe:jdbcQuery
var="jdbcProcessText"
scope="request"
calculateCount="true"
sqlQuery="SELECT TXSQN,TXDTA FROM DOMINO.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN"
connectionManager="jdbcConnectionManager1">
<xe:this.sqlParameters>
<xe:sqlParameter value="#{javascript:requestScope.processTextNo}">
</xe:sqlParameter>
</xe:this.sqlParameters>
</xe:jdbcQuery>
My computed field's value property in the repeat control looks like this:
requestScope.processTextNo = textrow.getDocument().getItemValueString('ProcessTextNo');
var vCount = jdbcProcessText.getCount();
var returnList = "<ul>";
for(i=0; i<vCount; i++){
returnList += ("<li>" + jdbcProcessText.get(i).getColumnValue("TXDTA") + "</li>");
}
returnList += "</ul>";
return returnList;
The problem I've run into is that I don't get any data from the JDBC query at all. Even if I hard code a value I know exists in the SQL table in the sqlParameter property of the jdbcQuery object I still get no results. I suspect I'm not calling the jdbcQuery object correctly but I can't figure out how to do so. Any help will be greatly appreciated.
You may want to reconsider your approach. I would suggest creating a Java bean to get the Domino view data, loop through that and call out to your query for each row in the view. Build up a List (Java List) of a Row class that has all the data you want to show. Then in the repeat call to your Java bean to a method that returns the List of Row classes. In each control in the repeat you would call to the getXXX method in your Row class. This way you can quickly build the List the repeat works on. Doing it your way in the control in the repeat will be very slow.
Howard
Here's the bean I wrote to do the job. At the start it opens a connection to the SQL data source, grabs a viewEntryCollection using a document UNID as a key, and then puts the column values into a HashMap for each row in the viewEntryCollection. One of the values in the HashMap is pulled from a SQL query. My repeat control iterates over the List returned by the bean. In other words the bean returns a List of HashMaps where most of the values in each HashMap comes from Domino view entry data and one value comes from SQL (not sure if that's the correct way of saying it, but it makes sense to me!).
Here's my code:
package com.foo;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewEntry;
import lotus.domino.ViewEntryCollection;
import com.ibm.xsp.extlib.relational.util.JdbcUtil;
import com.ibm.xsp.extlib.util.ExtLibUtil;
public class ProcessTextLines implements Serializable {
private static final long serialVersionUID = 1L;
private Connection conn = null;
public int rowCount = 0;
public int getRowCount() {
return rowCount;
}
// public void setRowCount(int rowCount) {
// this.rowCount = rowCount;
// }
public ProcessTextLines() {
/*
* argumentless constructor
*/
try {
// System.out.println("ProcessTextLines.java - initialising connection to as400");
this.conn = this.initialiseConnection();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (this.conn != null) {
// System.out.println("ProcessTextLines.java - closing connection to as400");
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public List<HashMap<String, String>> getRows(final String unid)
throws NotesException {
List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("luProductMasterFormula");
view.setAutoUpdate(false);
ViewEntryCollection vec = view.getAllEntriesByKey(unid, true);
ViewEntry ve = vec.getFirstEntry();
while (ve != null) {
result.add(processRowVals(ve));
rowCount++;
ViewEntry tmp = vec.getNextEntry(ve);
ve.recycle();
ve = tmp;
}
view.recycle();
db.recycle();
vec.recycle();
} catch (NotesException e) {
e.printStackTrace();
}
return result;
}
/*
* Create a HashMap of names + column values from a ViewEntry
*/
#SuppressWarnings("unchecked")
private HashMap<String, String> processRowVals(ViewEntry ve) {
HashMap<String, String> processRow = new HashMap<String, String>();
try {
Vector cols = ve.getColumnValues();
processRow.put("sequenceNo", cols.get(1).toString());
processRow.put("textNo", cols.get(3).toString());
processRow.put("status", cols.get(6).toString());
processRow.put("textLines", getProcessTextLines(cols.get(3).toString()));
// unid of the entry's doc
processRow.put("unid", ve.getUniversalID());
} catch (NotesException e) {
e.printStackTrace();
}
return processRow;
}
private Connection initialiseConnection() throws SQLException {
Connection connection = null;
try {
connection = JdbcUtil.createNamedConnection(FacesContext
.getCurrentInstance(), "as400");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
private String getProcessTextLines(String textNo) {
String resultHTML = "<ul class=\"processTextList\">";
try {
// System.out.println("ProcessTextLines.java - setting SQL parameter: " + textNo);
PreparedStatement prep = conn
.prepareStatement("SELECT TXSQN,TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN");
// supply a value to the PreparedStatement's parameter (the first
// argument is 1 because it is the first parameter)
prep.setString(1, textNo);
ResultSet resultSet = prep.executeQuery();
while (resultSet.next()) {
resultHTML += ("<li>" + resultSet.getString("TXDTA").trim() + "</li>");
}
} catch (SQLException e) {
// e.printStackTrace();
}
resultHTML += "</ul>";
return resultHTML;
}
}
It took me a while because of my lack of Java knowledge but with the pointers #Howard gave plus the few bits and pieces I found on the web I was able to cobble this together.
Opening and closing the SQL connection in the constructor feels counter intuitive to me, but it seems to work.
I am facing an issue with random behaviour for element wait/present/clickable. I have used below logic to wait for that element but its working some times and does not working some other times. Can some one please help me how to solve this issue with generic/standard way of element wait.
Issue/Requirement : I have to wait for an element till its present/clickable while loading web page. I am using Selenium Web driver 2.44.0 and Firefox 33.0.3
Logic used :
package com.ericsson.testing.automation.framework.ui.common;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.base.Function;
public class Test {
public static WebDriver driver;
public static long timeOut = 180000;
/** The poll time. */
public int pollTime = 100;
public void isElementClickable(WebDriver driver, WebElement webelement,
long timeOutForEachElement) {
try {
WebDriverWait wait = new WebDriverWait(driver,
timeOutForEachElement);
wait.until(ExpectedConditions.elementToBeClickable(webelement));
} catch (UnhandledAlertException ex) {
// Some debug logging info
}
}
// Senario 2
public void waitTillElementPresent(WebElement webelement) {
System.out.println("Before Fluent Wait");
System.out.println("Xpath = " + webelement);
FluentWait<WebElement> fluentWait = new FluentWait<WebElement>(
webelement);
fluentWait.pollingEvery(pollTime, TimeUnit.MILLISECONDS);
fluentWait.withTimeout(timeOut, TimeUnit.MILLISECONDS);
System.out.println("After Fluent Wait");
fluentWait.until(new Function<WebElement, Boolean>() {
public Boolean apply(WebElement webelement) {
try {
System.out.println("inside isDisplayed check");
return webelement.isDisplayed();
} catch (NoSuchElementException ex) {
System.out.println("Inside NoSuchElementException");
return false;
} catch (ElementNotVisibleException ex) {
System.out.println("Inside ElementNotVisibleException");
return false;
} catch (StaleElementReferenceException ex) {
System.out.println("Inside StaleElementRefException");
return false;
} catch (UnhandledAlertException ex) {
System.out.println("Inside UnhandledAlertException");
// Some logic for debug logging
return false;
}
}
});
}
// Senario 3
public void clickOnElement(String element) {
while (true) {
driver.findElement(By.xpath(element)).click();
System.out.println("Trying to click on element" + element);
break;
}
System.out.println("Clicked on element" + element);
}
/*
* private boolean isElementPresent(String element) {
* int myLink
* =driver.findElements(By.xpath(element)).size();
* if (myLink != 0) return true;
* else return false; }
*/
// Senario 4
public void waitTillElementisClicked(String element) {
boolean flag = true;
while (flag == true) {
// driver.findElement(By.xpath(element)).click();
// flag=driver.findElement(By.xpath(element)).isSelected();
driver.findElement(By.xpath(element)).click();
// driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
if (driver.findElement(By.xpath(element)).isSelected()) {
flag = false;
System.out.println("element already clicked");
}
// driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
System.out.println("trying to click the element");
}
System.out.println("Clicking the element");
}
}
try "driver.findElement(By.xpath(element)).size()>0". With my experience if you are doing everything correct still facing element issue, this works.
Though the size() works for webelements, you could pass your single element in the locator
wait.until(new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver webDriver)
{
return verifyWebElementListIsPresent(se.driver().findElements(locator));
}
});
public boolean verifyWebElementListIsPresent(List<WebElement> element)
{
List<WebElement> adminPermissions = element;
if (adminPermissions.size() > 0)
{
System.out.println("Element is displayed on the page");
return true;
}
else
{
System.out.println("Element is not displayed on the page");
return false;
}
}
public static WebElement elementExists(String xpath){
// make sure driver is available to this method..
WebDriverWait wait = new WebDriverWait(driver, 2); //Increase wait time if required
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
System.out.println("Element having xpath - "+xpath+" is present!");
return driver.findElement(By.xpath(xpath));
}catch(ElementNotFoundException e1){
System.out.println("Element having xpath - "+xpath+" is not present!");
return null;
} catch (TimeoutException e) {
System.out.println("Element having xpath - "+xpath+" is not present!");
return null;
}
}
WebElement xyz = elementExists(pass xpath string);
If web element is found, it will return web element, else it will return null.
If web element is present also check whether its displayed for use.
webelement.isDisplayed() should return true.
I want to make a Java program to calculate the P-value of my data that I want to upload, but getting too much trouble to do so. The data is been read by the Java program, but next step is to solve data for getting p-value.
The input file is:
The input Should be:-
Name A B C
a 1.7085586 0.73179674 3.3962722
b 0.092749596 -0.10030079 -0.47453594
c 1.1727467 0.15784931 0.0572958
d -0.91714764 -0.62808895 -0.6190882
e 0.34570503 0.10605621 0.30304766
f 2.333506 -0.2063818 0.4022169
g 0.7893815 1.449388 1.5907407
And the Output should be like this:-
Name pValue
a 0.129618298
b 0.4363544
c 0.323631285
d 0.017916658
e 0.076331828
f 0.385619995
g 0.035449488
I have run this data in R program but I want to write some Java to solve this.
My Java code till now is:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Abc {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:/Documents and Settings/Admin/Desktop/test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
//output = BufferedReader.getParser().getAsDoubleArray("br");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is only reading my data and showing it in the console of Java. How to proceed?
I think your are facing problem with retrieving and printing values from file. Below program gives output in required format :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Abc {
public static void main(String[] args) {
BufferedReader br = null;
String sCurrentLine;
try {
br = new BufferedReader(new FileReader("C:/Documents and Settings/Admin/Desktop/test.txt"));
// Override Default Header Row
br.readLine();
System.out.println("Name" + "\t" + "pValue");
while ((sCurrentLine = br.readLine()) != null) {
int i = 0;
String str[] = sCurrentLine.split("\t");
System.out.print(str[i] + "\t");
Double dValue1 = Double.parseDouble(str[++i]);
Double dValue2 = Double.parseDouble(str[++i]);
Double dValue3 = Double.parseDouble(str[++i]);
// Do pValue Calc here
Double pValue = 1.2334;
System.out.println(pValue);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
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 ;
}