When a user clicks on a link, I want to change the page and then load the relevant info.
However, the HTMLElement is always null.
The following is the code:
WebViewPanel.java
//to be used in JFX Thread
public void loadURLFX(final String url) {
if (Misc.stringHasContent(url)) {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
boolean invalidURL = false;
InputStream stream = null;
try {
URL urlObj = new URL(tmp);
stream = urlObj.openStream();
} catch (Exception e) {
invalidURL = true;
} finally {
try {
stream.close();
} catch (Exception ex) {
}
stream = null;
}
if (!invalidURL) {
engine.load(tmp);
} else {
//https://www.google.com.sg/search?q=searchTerm
engine.load("https://www.google.com.sg/search?q=" + url);
}
}
}
App.java
public void load(){
if(Platform.isFxApplicationThread()){
webViewPanel.loadURLFX(App.class.getResource("/hello.html").toExternalForm());
HTMLElement element = (HTMLElement) WebMisc.getHTMLElement(webViewPanel.getWebEngine(), "menu");
}
}
element is always null. What should I do to fix it?
Related
sonar issue
private void getGtcj(String gtcjStatusValue, String strArchiveReqd) throws Exception {
XPathHelper activationConfigParser = null;
try {
activationConfigParser = ConfigUtil.getInstance().getConfigParser(new URL((V21Constants.FILE
+ System.getProperty(V21Constants.USER_DIR) + "/vServe21/config/ActivationParameters.xml")));
} catch (Exception e) {
log.error(e.getMessage());
}
StringBuffer useGTCJSolution = new StringBuffer();
useGTCJSolution.append(XPathConstants.ACTIVATION_CONFIG_ACTIVATION_PARAM)
.append("/parameter[#name = '").append(XPathConstants.TAG_NAME_USE_GTCJ_SOLUTION)
.append("']");
String useGTCJSolutionStr = activationConfigParser.evaluateXPath(useGTCJSolution.toString());
log.debug("useGTCJSolutionStr value:" + useGTCJSolutionStr);
if (useGTCJSolutionStr != null && useGTCJSolutionStr.trim().equalsIgnoreCase(V21Constants.YES)
&& (gtcjStatusValue.equalsIgnoreCase(Statuses.ACTIVATION_SUCCESS)
|| gtcjStatusValue.equalsIgnoreCase(Statuses.ROLLBACK_SUCCESS)
|| gtcjStatusValue.equalsIgnoreCase("Rollback Failure"))) {
log.debug("No need to archive and send response from here.");
} else {
log.debug("inside GTCJSolution for GTCJ orders...Archiving and sending response xml");
if (strArchiveReqd != null && "Yes".equalsIgnoreCase(strArchiveReqd)) {
archiveXML(responseFileName, V21Constants.VIF_ARCHIVE_RESPONSE_XML_PATH);
}
// sending the response XML
response = new Response();
response.sendResponseXML(properties, responseXml, bNBSConnectivityFlag, queueName, address);
}
}
I figured out there should be a finally block after catch, but I don't know what to add inside the finally block. Or is there any other solution?
When you create the variable activationCOnfigParser you're in a try/Catch block. You can bypass this error :
private void getGtcj(String gtcjStatusValue, String strArchiveReqd) throws Exception {
XPathHelper activationConfigParser = null;
try {
activationConfigParser = ConfigUtil.getInstance().getConfigParser(new URL((V21Constants.FILE
+ System.getProperty(V21Constants.USER_DIR) + "/vServe21/config/ActivationParameters.xml")));
} catch (Exception e) {
actionConfigParser = <DEFAULT VALUE>
log.error(e.getMessage());
}
In catch block there is that you can replace with a value that actionConfigParser has to assuming in case of exception.
I want to search for particular string inside all files in a Directory.
Ex: Search for "tiger" in path D:/test/chapters/
D:/test/chapters
/chapter1.log
/chapter2.log
/chapter3.log all these sub files under D:/test/chapters/ .
Sample code I have tried :
public class Example {
public Example() {
super();
}
public int plugin_execute() {
boolean foundstring=false;
try {
File dir = new File("D:/test/chapters");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
if (filename !=null) {
foundstring = testString(filename, "tiger");
System.out.println("failed");
}
//Search for entry in file
if (!foundstring) {
return //failuremsg
} else {
System.out.println("failed");
return //succes
}
}
}
return 1;
} catch (Exception e) {
return //error mssg
}
}
private boolean teststring(String filePath, String str) {
BufferedReader br = null;
File file = new File(filePath);
boolean result = false;
if(!file.exists())
return false;
try {
br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.contains(str)) {
result = true;
System.out.println(str);
System.out.println("Found entry ");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
It only returns the output of last file, means if it search success in last file it return success otherwise failed.
But I want success if string is found in first file. i.e chapter1 should return success, if not found in Chapter1 it should continue search in chapter2 ....
Please suggest how can I modify this code..
Problem: Simple mix-up with ! and true/false locations.
Solution: Change this
if (! foundString)
{
return // failuremsg
}
else
{
System.out.println("failed");
return // success
}
to
if (foundString)
{
// return success message
}
else
{
// return failure message
}
Another problem I believe I see in your code is that the line foundstring = findString(filename, "tiger"); calls the method findString, whereas the other method you posted in your code is testString. I assume this is a name mix up.
public void listFiles(Path dir , String text)
{
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir))
{
for (Path path : directoryStream)
{
if (Files.isRegularFile(path) && Files.isReadable(path))
{
//this.findString(path, text);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
private boolean findString(Path file, String text)
{
//Your implementation
return true;
}
The aim is to make the link clickable in jtable so that when user clicks on the link the desired page gets opened in the browser. One of the items fetched from database is link and my attempt is to make it active and clickable. I get the error as
Unhandled exception type URISyntaxException
For the line in my code:
final URI uri = new URI("http://www.roseindia.net");
And even if i put it in try catch block, the error doesn't seem to resolve. Rather on surrounding in a try-catch block, I get the error as
Cannot refer to a non-final variable uri inside an inner class defined in a different method
So what could be the possible solution and fix?
public class JTableButtonMouseListener extends MouseAdapter
{
private final JTable table;
public JTableButtonMouseListener(JTable table)
{
this.table = table;
}
public void mouseClicked(MouseEvent e) {
counter=0;
// System.out.println("***************************************************************");
System.out.println("counter value="+counter++);
//System.out.println("/////////////////////////////////////////////////////////////////////");
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
// System.out.println("row clicked="+row);
//System.out.println("column clicked="+column);
System.out.println("object value="+value);
System.out.println(".............................................................");
/* public void getsecname(String s)
{
String ss=s;
}*/
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
// final URI uri = null;
// URI uri;
try{
final URI uri = new URI("http://www.roseindia.net");
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
// button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
} else {
}
}
});
}
// String link_string=ob.toString();
//ob.setClickable(true);
if(value==null)
{
Object v=table.getValueAt(row, 1);
//System.out.println("--------------------------------------------");
s = v.toString();
jmenu_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jmenu_frame.setContentPane(new ListModelExample(s));
jmenu_frame.setSize(260, 200);
jmenu_frame.setVisible(true);
jmenu_frame.setLocationRelativeTo(null);
//it ends here
}
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
You can not use non-final variable inside your inner class. Discussion.
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
try {
final URI uri = new URI("http://www.roseindia.net");
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
//button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
}
}
});
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
What is telling you is that you need a try catch block to handle a URISyntaxException:
final URI;
try{
uri = new URI("http://www.roseindia.net");
} catch (URISyntaxException e) {
e.printStackTrace();
}
To solve uri cannot be resolved to a variable You could instead of using try catch, add a throws URISyntaxException to the method in which uri is declared. But I do not think that is a good practice. Maybe it works in your case.
I have the following method that I run from my map task in a multithreaded execution , however this works fine in a standalone mod e, but when I runt this in Hadoop YARN it runs out of the physical memory of 1GB and the virtual memory also shoots up.
I need to know if I am doing anything wrong from a programming perspective, I think I am closing all the streams that I am opening ASAP , so I see no reason for a memory leak to happen . Please advise.
Thanks.
public static void manageTheCurrentURL(String url) {
logger.trace("Entering the method manageTheCurrentURL ");
InputStream stream = null;
InputStream is = null;
ByteArrayOutputStream out = null;
WebDriver driver = null;
try {
if (StringUtils.isNotBlank(url)) {
caps.setJavascriptEnabled(true); // not really needed: JS
// enabled by default
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"/usr/local/bin/phantomjs");
// Launch driver (will take care and ownership of the phantomjs
// process)
driver = new PhantomJSDriver(caps);
driver.get(url);
String htmlContent = driver.getPageSource();
if (htmlContent != null) {
is = new ByteArrayInputStream(htmlContent.getBytes());
ByteArrayDocumentSource byteArrayDocumentSource = new ByteArrayDocumentSource(
is, url, "text/html");
Any23 runner = new Any23();
runner.setHTTPUserAgent("test-user-agent");
out = new ByteArrayOutputStream();
TripleHandler handler = new NTriplesWriter(out);
try {
runner.extract(byteArrayDocumentSource, handler);
} catch (ExtractionException e) {
} finally {
if (driver != null) {
driver.quit();
//driver.close();
}
try {
handler.close();
} catch (TripleHandlerException e) {
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
if (out != null) {
stream = new ByteArrayInputStream(out.toByteArray());
Iterator<Node[]> it = new DeltaParser(stream);
if (it != null) {
SolrCallbackForNXParser callback = new SolrCallbackForNXParser(
url);
callback.startStory();
while (it.hasNext()) {
Node[] abc = it.next();
callback.processStory(abc);
}
callback.endStory();
}
}
}
}
} catch (IOException e) {
return;
}
finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
logger.trace("Exiting the method manageTheCurrentURL ");
}
I'm using the Bluecove library to devolep an Obex ftp client/server on android 2.X.
So far i managed to connect as a client from android to a pc.
I tried the bluecove example code for a server but doesn't work.
Is it possible to develop a server on android 2.X. Does any one have the code to do it.
Thank you.
public class OBEXServer implements Runnable {
private SessionNotifier serverConnection;
private boolean isStoped = false;
private boolean isRunning = false;
public final UUID OBEX_OBJECT_PUSH = new UUID(0x1105);
public static final String SERVER_NAME = "OBEX Object Push";
private UserInteraction interaction;
private OBEXServer(UserInteraction interaction) {
this.interaction = interaction;
}
public static OBEXServer startServer(UserInteraction interaction) {
OBEXServer srv = new OBEXServer(interaction);
Thread thread = new Thread(srv);
thread.start();
while (!srv.isRunning && !srv.isStoped) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new Error(e);
}
}
if (!srv.isRunning) {
throw new Error("Can't start server");
}
return srv;
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
isStoped = false;
LocalDevice localDevice;
try {
localDevice = LocalDevice.getLocalDevice();
if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) {
Logger.error("Fail to set LocalDevice Discoverable");
}
serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:" + OBEX_OBJECT_PUSH + ";name="
+ SERVER_NAME);
} catch (Throwable e) {
Logger.error("OBEX Server start error", e);
isStoped = true;
return;
}
try {
ServiceRecord record = localDevice.getRecord(serverConnection);
String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
Logger.debug("BT server url: " + url);
final int OBJECT_TRANSFER_SERVICE = 0x100000;
try {
record.setDeviceServiceClasses(OBJECT_TRANSFER_SERVICE);
} catch (Throwable e) {
Logger.debug("setDeviceServiceClasses", e);
}
DataElement bluetoothProfileDescriptorList = new DataElement(DataElement.DATSEQ);
DataElement obbexPushProfileDescriptor = new DataElement(DataElement.DATSEQ);
obbexPushProfileDescriptor.addElement(new DataElement(DataElement.UUID, OBEX_OBJECT_PUSH));
obbexPushProfileDescriptor.addElement(new DataElement(DataElement.U_INT_2, 0x100));
bluetoothProfileDescriptorList.addElement(obbexPushProfileDescriptor);
record.setAttributeValue(0x0009, bluetoothProfileDescriptorList);
final short ATTR_SUPPORTED_FORMAT_LIST_LIST = 0x0303;
DataElement supportedFormatList = new DataElement(DataElement.DATSEQ);
// any type of object.
supportedFormatList.addElement(new DataElement(DataElement.U_INT_1, 0xFF));
record.setAttributeValue(ATTR_SUPPORTED_FORMAT_LIST_LIST, supportedFormatList);
final short UUID_PUBLICBROWSE_GROUP = 0x1002;
final short ATTR_BROWSE_GRP_LIST = 0x0005;
DataElement browseClassIDList = new DataElement(DataElement.DATSEQ);
UUID browseClassUUID = new UUID(UUID_PUBLICBROWSE_GROUP);
browseClassIDList.addElement(new DataElement(DataElement.UUID, browseClassUUID));
record.setAttributeValue(ATTR_BROWSE_GRP_LIST, browseClassIDList);
localDevice.updateRecord(record);
} catch (Throwable e) {
Logger.error("Updating SDP", e);
}
try {
int errorCount = 0;
int count = 0;
isRunning = true;
while (!isStoped) {
RequestHandler handler = new RequestHandler();
try {
count++;
Logger.debug("Accepting OBEX connections");
handler.connectionAccepted(serverConnection.acceptAndOpen(handler));
} catch (InterruptedIOException e) {
isStoped = true;
break;
} catch (Throwable e) {
if ("Stack closed".equals(e.getMessage())) {
isStoped = true;
}
if (isStoped) {
return;
}
errorCount++;
Logger.error("acceptAndOpen ", e);
continue;
}
errorCount = 0;
}
} finally {
close();
Logger.debug("OBEX Server finished!");
isRunning = false;
}
}
public void close() {
isStoped = true;
try {
if (serverConnection != null) {
serverConnection.close();
}
Logger.debug("OBEX ServerConnection closed");
} catch (Throwable e) {
Logger.error("OBEX Server stop error", e);
}
}
private static File homePath() {
String path = "bluetooth";
boolean isWindows = false;
String sysName = System.getProperty("os.name");
if (sysName != null) {
sysName = sysName.toLowerCase();
if (sysName.indexOf("windows") != -1) {
isWindows = true;
path = "My Documents";
}
}
File dir;
try {
dir = new File(System.getProperty("user.home"), path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new SecurityException();
}
}
} catch (SecurityException e) {
dir = new File(new File(System.getProperty("java.io.tmpdir"), System.getProperty("user.name")), path);
}
if (isWindows) {
dir = new File(dir, "Bluetooth Exchange Folder");
}
if (!dir.exists()) {
if (!dir.mkdirs()) {
return null;
}
} else if (!dir.isDirectory()) {
dir.delete();
if (!dir.mkdirs()) {
return null;
}
}
return dir;
}
private void showStatus(final String message) {
interaction.showStatus(message);
}
private class RequestHandler extends ServerRequestHandler {
Timer notConnectedTimer = new Timer();
boolean isConnected = false;
boolean receivedOk = false;
Connection cconn;
void connectionAccepted(Connection cconn) {
Logger.debug("Received OBEX connection");
showStatus("Client connected");
this.cconn = cconn;
if (!isConnected) {
notConnectedTimer.schedule(new TimerTask() {
public void run() {
notConnectedClose();
}
}, 1000 * 30);
}
}
void notConnectedClose() {
if (!isConnected) {
Logger.debug("OBEX connection timeout");
try {
cconn.close();
} catch (IOException e) {
}
if (!receivedOk) {
showStatus("Disconnected");
}
}
}
public int onConnect(HeaderSet request, HeaderSet reply) {
isConnected = true;
notConnectedTimer.cancel();
Logger.debug("OBEX onConnect");
return ResponseCodes.OBEX_HTTP_OK;
}
public void onDisconnect(HeaderSet request, HeaderSet reply) {
Logger.debug("OBEX onDisconnect");
if (!receivedOk) {
showStatus("Disconnected");
}
}
public int onSetPath(HeaderSet request, HeaderSet reply, boolean backup, boolean create) {
Logger.debug("OBEX onSetPath");
return super.onSetPath(request, reply, backup, create);
}
public int onDelete(HeaderSet request, HeaderSet reply) {
Logger.debug("OBEX onDelete");
return super.onDelete(request, reply);
}
public int onPut(Operation op) {
Logger.debug("OBEX onPut");
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
if (name != null) {
Logger.debug("name:" + name);
showStatus("Receiving " + name);
} else {
name = "xxx.xx";
showStatus("Receiving file");
}
Long len = (Long) hs.getHeader(HeaderSet.LENGTH);
if (len != null) {
Logger.debug("file lenght:" + len);
interaction.setProgressValue(0);
interaction.setProgressMaximum(len.intValue());
}
File f = new File(homePath(), name);
FileOutputStream out = new FileOutputStream(f);
InputStream is = op.openInputStream();
int received = 0;
while (!isStoped) {
int data = is.read();
if (data == -1) {
Logger.debug("EOS received");
break;
}
out.write(data);
received++;
if ((len != null) && (received % 100 == 0)) {
interaction.setProgressValue(received);
}
}
op.close();
out.close();
Logger.debug("file saved:" + f.getAbsolutePath());
showStatus("Received " + name);
receivedOk = true;
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
Logger.error("OBEX Server onPut error", e);
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
} finally {
Logger.debug("OBEX onPut ends");
interaction.setProgressDone();
}
}
public int onGet(Operation op) {
Logger.debug("OBEX onGet");
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
} catch (IOException e) {
Logger.error("OBEX Server onGet error", e);
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
} finally {
Logger.debug("OBEX onGet ends");
}
}
public void onAuthenticationFailure(byte[] userName) {
Logger.debug("OBEX AuthFailure " + new String(userName));
}
}
}