Difficulty handling NULL exceptions and changing HTML within JXBrowser - java

I have recently started using JXBrowser to build a Visualisation of Edit Distances (Levenshtein). I am using JXBrowser to integrate JAVA with HTML, CSS and JS.
My application starts with the MainFrame class by loading up my start screen, specifically hello.html.
public MainFrame() {
final Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame("JxBrowser - EditDistance");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
InputStream urlStream = getClass().getResourceAsStream("../web/hello.html");
String html = null;
try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
StringBuilder builder = new StringBuilder();
String row;
while ((row = urlReader.readLine()) != null) {
builder.append(row);
}
html = builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
browser.loadHTML(html);
DOMDocument document = browser.getDocument();
final DOMElement documentElement = document.getDocumentElement();
if (documentElement != null) {
try{
DOMElement element = documentElement.findElement(By.id("button"));
element.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
public void handleEvent(DOMEvent event) {
new UserInput();
}
}, false);
}catch(NullPointerException e){
System.out.println("NULLL on Entry");
}
}
}
I then call UserInput() and no Null error is thrown. I then load my UserInputForm class using the same methodology as above, instead using UserInputForm.html as my view.
InputStream urlStream = getClass().getResourceAsStream("../web/UserInputForm.html");
String html = null;
try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
StringBuilder builder = new StringBuilder();
String row;
while ((row = urlReader.readLine()) != null) {
builder.append(row);
}
html = builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
browser.loadHTML(html);
final DOMDocument document = browser.getDocument();
final DOMElement documentElement = document.getDocumentElement();
if (documentElement != null) {
DOMElement submitElement = documentElement.findElement(By.id("enterButton"));
if (submitElement != null) {
submitElement.addEventListener(DOMEventType.OnClick, new DOMEventListener() {
public void handleEvent(DOMEvent event) {
DOMElement source = document.findElement(By.id("sourceString"));
DOMElement target = document.findElement(By.id("targetString"));
}}, false);
}
else{
System.out.println("NULL on Sub Form");
}
}
}
The problem occurs mainly when the UserInputForm loads. I get a NULL returned by the submitElement document element. Sometimes I get a NULL returned as the application starts. I feel like I am missing a fundamental procedure when loading these forms up. Does anyone have any insight into making sure that document elements don't return NULL? Is this an issue with my HTML loading techniques?

The Browser.loadHTML() method is executed asynchronously as a request to load a specific HTML. Therefore, there is no guarantee that the web page is loaded completely when this method returns.
Before accessing the DOM document on the loaded web page, it is necessary to wait until the web page is loaded completely. If the web page is not loaded completely, the DOM document or some DOM elements may appear broken or missing.
The following sample code demonstrates how to load an HTML and wait until it's loaded completely:
// Blocks current thread execution and waits until the web page is loaded completely
Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
#Override
public void invoke(Browser value) {
value.loadHTML("<html><body>Your HTML goes here</body></html>");
}
});
Note: use this approach for loading the web pages only.
The following article describes how to load a web page and wait until it is loaded completely: https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013107-loading-waiting

Related

Convert html to Pdf with with very big data

I have implemented html to pdf conversion using openhtmltopdf and I use it in Struts 2 action and it works very well. However, in the case of very large data, e.g. the html data is > 3Mb (pdf file ~1.6Mb) when I test it with JMeter for 50 hits the application crashes with message java.lang.OutOfMemoryError: Java heap space.
If I increase the java limit with the -Xmx option I just get some extra hits
The code i use is like this:
First clean html
public class HtmlToXhtmlConverterHTMLCleaner2 extends AbstractHtmlToXhtmlConverter
implements IHtmlToXhtmlConverter {
public HtmlToXhtmlConverterHTMLCleaner2(String htmlData) {
super(htmlData);
}
#Override
public void convert() {
final HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties cleanerProperties = cleaner.getProperties();
cleanerProperties.setAdvancedXmlEscape(true);
cleanerProperties.setOmitXmlDeclaration(true);
cleanerProperties.setOmitDoctypeDeclaration(false);
cleanerProperties.setTranslateSpecialEntities(true);
cleanerProperties.setTransResCharsToNCR(true);
cleanerProperties.setRecognizeUnicodeChars(true);
cleanerProperties.setIgnoreQuestAndExclam(true);
cleanerProperties.setUseEmptyElementTags(false);
cleanerProperties.setPruneTags("script");
final XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
try {
final TagNode rootTagNode = cleaner.clean(htmlData);
this.xhtmlData = xmlSerializer.getAsString(rootTagNode);
} catch (Exception ex) {
ex.printStackTrace();
}
}
then convert cleaned html to pdf
public class PDFConverterHtmlToPdf extends AbstractPDFConverter implements IPDFConverter {
ByteArrayOutputStream psfData;
public PDFConverterHtmlToPdf(String xhtmlData, String cssFile) {
super();
this.xhtmlData = xhtmlData;
this.cssFile = cssFile;
}
#Override
public void convert() {
pdfData = new ByteArrayOutputStream();
try {
// There are more options on the builder than shown below.
PdfRendererBuilder builder = new PdfRendererBuilder();
if(cssFile != null && cssFile.length() > 0){
builder.withHtmlContent(xhtmlData, cssFile);
} else {
builder.withHtmlContent(xhtmlData, "");
}
builder.toStream(pdfData);
builder.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
then send data from strus2 action to request
private void buildPdfContent(String htmlContent) {
String pdfConverterCssFile = "http://localhost:8080/DocumentConverterApi/css/htmlToPdf.css";
PDFConverterHelp pdfConverterHelp = new PDFConverterHelp("demo.pdf",
htmlContent, pdfConverterCssFile);
pdfConverterHelp.build();
inputStream = new ByteArrayInputStream(pdfConverterHelp.getPDFFile().toByteArray());
pdfConverterHelp.closePdfData();
contentDisposition = "inline;filename=\"" + "demo.pdf\"";
}
I'm doing something wron?
Is there any other way to implement it without the risk of crashing the application?

FXML and lambda expressions in Java not working?

I'm working on rewriting my simple Contacts app from normal JAVA FX to FXML.THe problem is in Lambda expressions. I have interface like:
interface ObjectCreator {
void create(String[] array);
}
And the problem is when i use this CSVFileReader:
public static class CSVFileReader {
String fileName;
CSVFileReader(String fileName) {
this.fileName = fileName;
}
void read(ObjectCreator creator) {
try {
BufferedReader csv = new BufferedReader(new FileReader(fileName));
String row = csv.readLine();
while (row != null) {
creator.create(row.split(","));
row = csv.readLine();
}
csv.close();
} catch (IOException e) {
}
}
}
In this code i use lambda expression to read Contacts from file:
#FXML
public void openFile() {
FileChooser fileChooser = new FileChooser();
File fileE = fileChooser.showOpenDialog(scene.getWindow());
if (fileE != null) {
CSVFileReader reader = new CSVFileReader(fileE.getName());
data.clear();
reader.read(v ->
data.add(new Contact(v[0], v[1], v[2], v[3])));
}
System.out.println("open list");
}
I use JDK 1.8.65 so preeety new one. Problem is that there is no error or exception just looks like code "v->data.add(new Contact(v[0], v[1], v[2], v[3]))" would not be invoked.
Question is am I doing something wrong or it just wont be working??
Ok no question, after futher studying my app i discovered i was taking
fileE.getName();
and i should take
fileE.getAbsolutePath();
So the app would look in proper location for a file.

Extracting link from a facebook page

I want to extract content of a facebook page mainly the links in a facebook page. I tried extracting using jsoup but it does not show the relevant link the link which is showing the likes for the topic for eg :https://www.facebook.com/search/109301862430120/likers.may be it's a jquery,ajax or javascript type code. So how can I extract those link using java how can i extract/access that link or calling a JavaScript function with HTMLUnit
public static void main(String args[])
{
Testing t=new Testing();
t.traceLink();
}
public static void traceLink()
{
// File input = new File("/tmp/input.html");
Document doc = null;
try
{
doc = Jsoup.connect("https://www.facebook.com
/pages/Ice-cream/109301862430120?rf=102173023157556").get();
Elements link = doc.select("a[href]");
String stringLink = null;
for (int i = 0; i < link.size(); i++)
{
stringLink = link.toString();
System.out.println(stringLink);
}}}
System.out.println(link);
}
catch (IOException e)
{
//e.printStackTrace();
}
Element links = doc.select("a[href]").first();
System.out.println(links);

JSF Read Text File

I've been googling all over the place for information on how to display content from a .txt file onto a web page using JSF with no success.
From what I think/guess, the basic jsf form would be something like
<h:outputText value="#{beanName.printTextFileMethod}"/>
or something.
Help on how to set up bean appreciated. I tried playing with InputStream/BufferedStream, having a lot of problem just trying to get rid of the red lines in codes. Also I'm absolutely horrid at defining relative path. And absolute path doesn't seem to work with inputstream?
Thank you for your time.
public class TextFileBean{
String completeMessage = null;
public TextFileBean(){
try{
//read data from the text file
java.io.BufferedReader in=
new java.io.BufferedReader(
new java.io.InputStreamReader(
TextFileBean.this.getClass().
getResourceAsStream("txtFile.txt"
)));
System.out.println("in :" +in);
readData(in);
in.close();
} catch (java.io.IOException IOex) {
System.out.println("IO Error :" +IOex);
}
}
private void readData(BufferedReader br) {
// dosomethig
String line = null;
StringBuffer appendMessage = null;
try {
appendMessage = new StringBuffer(16384);
while ((line = br.readLine()) != null) {
appendMessage.append(line);
appendMessage.append('\n');
}
if (appendMessage != null) {
completeMessage = appendMessage.toString();
}
} catch (Exception e) {
}
}
public String printTextFileMethod()
{
System.out.println("completeMessage:: "+ completeMessage);
return completeMessage;
}
}

java SAX parser giving NullPointerException after change in working code

I'm modifying an app that loads data dynamically from an XML file that contains a quiz and displays questions and replies. The change consists in the fact that i want to load a single(hardcoded for now) file instead of using a JFileChooser.
Here's the relevant code working before(undefined variables are class attributes but i won't post the whole class declaration):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i &lt nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
And now for the code that doesn't work:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:\\file.xml");
pathname = "C:\\file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
Also, the exception:
Exception in thread "main" java.lang.NullPointerException
and it occurs at question.setText(e.getAttribute("value")); on calling setupQuestion("q1");.
Edit: Interestingly enough System.out.println(fileName); gets printed before the Exception is thrown and System.out.println(idno); is printed after it. Actually on restarting the IDE both echos appear after the exception is thrown.
I've been stuck on this for quite some time. Any help is much appreciated.
Found the culprit. I guess I haven't mentioned everything. I've forgot to allocate memory for question and replies. I am so ashamed.

Categories

Resources