Primefaces Document Viewer Exception Handling - jsf

I am using Primefaces documentViewer from primefaces-extensions 12 as follows :
<pe:documentViewer zoom="page-fit" pagemode="thumbs"
id="iframeViewPdf" width="80%" height="800"
url="/pdfServlet?id=#{param.id}"/>
My controller writes the bytes to the response as follows :
#RequestMapping(value = "/pdfServlet")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// code here
try{
documentId = request.getParameter("id");
inputStream = myRepository.getFileAsInputStream(documentId);
outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
}catch(Exception e){
// all below didn't work
// request.getRequestDispatcher(request.getContextPath() + "/error").forward(request, response);
// response.sendRedirect(request.getContextPath() + "/error");
// throw e;
// what should be done here to redirect to error page / show error message in the page
}finally{
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
Above code works fine, but when any exception occurs in the backend I want to handle it in the client side, I tried to throw the exception in the catch part and got no effect.
Note: my application has error page configuration for any exception to forward to error page.
I also tried to redirect/forward to error page in the catch part, but I always gets an exception that cannot forward/redirect after response is committed.
How can I better handle exception in this case?
UPDATE : below is the response I get in the viewer when loading exception occurs in the backend, is there's any way to call a javascript function instead ?

I was able to handle the error using javascript interval on load as follows :
window.onload = function(){
PF('statusDialog').show();
var checkExist = setInterval(function() {
var iframe=document.getElementsByTagName('iframe')[0];
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var viewer = innerDoc.getElementById('viewer');
var errorMessage = innerDoc.getElementById('errorMessage');
var innerHTML = viewer.innerHTML;
if(innerHTML != null && innerHTML!='' && innerHTML!='undefined'){
clearInterval(checkExist);
PF('statusDialog').hide();
}
if(errorMessage != null && errorMessage.innerText != ''){
clearInterval(checkExist);
PF('statusDialog').hide();
// handle error here
window.location.href = getContextPath()+'/error';
}
}, 1000);
}

Why not put a custom Error in your web.xml???
web.xml
<!-- Handle Invalid PDF errors gracefully -->
<error-page>
<exception-type>com.your.InvalidPdfException</exception-type>
<location>/pages/error.xhtml</location>
</error-page>
Then in your code throw new InvalidPdfException().

Related

How to solve the cross domain in HtmlUnit

Error:
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.xml.XmlPage <init>
警告: Failed parsing XML document http://live3.win007.com/vbsxml/goalBf3.xml?r=0071466496906000: Content is not allowed in prolog.
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine handleJavaScriptException
信息: Caught script exception
======= EXCEPTION START ========
EcmaError: lineNumber=[41] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[http://live3.win007.com/common2.js] message=[TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:865)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:747)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:1032)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:395)
at com.gargoylesoftware.htmlunit.html.HtmlScript$3.execute(HtmlScript.java:276)
common2.js code:
function getOddsData() {
oddsHttp.open("get", "vbsxml/goalBf3.xml?r=007" + Date.parse(new Date()), false);
oddsHttp.setRequestHeader("User-Agent", "");
oddsHttp.send(null);
var root = oddsHttp.responseXML.documentElement.childNodes[0];
oddsHttp as XMLHttpRequest
I suspect that a cross domain problem leads to " Cannot read property "childNodes""
I want to modify the JS by the following methods
public WebResponse getResponse(WebRequest request) throws IOException {
if(request.getUrl().toExternalForm().contains("common2.js")){
....
}
}
How to fix it?
This is not a cross domain problem,the warning: Content is not allowed in prolog is the key
I solved the problem by the following code
new WebConnectionWrapper(wc) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if(request.getUrl().toExternalForm().contains("goalBf3.xml")){
System.out.println(response.getContentAsString("UTF-8"));
String content = response.getContentAsString("UTF-8");
if(null != content && !"".equals(content)){
if(content.indexOf("<") != -1 && content.lastIndexOf(">") != -1 && content.lastIndexOf(">") > content.indexOf("<"))
content = content.substring(content.indexOf("<"), content.lastIndexOf(">") + 1);
}
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
}

how to use javaxt.io with SSJS in XPages

In an XPages application I would like to use the javaxt library to extract EXIF information from uploaded images.
My upload function runs in SSJS so my routine to check metadata looks as follwed (just a test)
try {
importPackage(javaxt.io);
var image = new javaxt.io.Image(tempFile);
if (image != null) {
print("image not null")
var height = image.getHeight();
if (height != null) {
print(height);
} else {
print("no height")
}
}
} catch (e) {
print("Upload.readMetaData: " + e.toString());
}
In the server console I get to see the following:
HTTP JVM: image not null
Upload.readMetaData: java.lang.NullPointerException
I wonder what statement I should make instead of image.getHeight() ?

xpages SSJS: cannot get rid of "com.ibm.xsp.acl.RedirectSignal" warnings in log

I am building a multilingual application and I am storing the value of the latest language used in a cookie.
When the user opens up the application, the sessionScope variable is not set and the code will look for the cookie value and reload the page if not in the proper Locale.
I am getting the "com.ibm.xsp.acl.RedirectSignal" warning each time the page is reloaded in the proper locale, and I'd lilke to avoid it.
My code is located in the beforeRenderResponse event of the ApplicationLayout control I am using in the application, and looks like this:
if(!sessionScope.lang) { //this only happens when the page is opened in browser for the first time
var lang = context.getUrlParameter("lang").toLowerCase();
if(!!lang) {
sessionScope.lang = lang.toUpperCase();
//set cookie for next time the site is opened by user
setCookie("lang", lang.toUpperCase(), 30);
context.setLocale(new Locale(lang.toLowerCase()));
} else {
//set language from cookie
var lang = getLangFromCookie();
if(!!lang) {
sessionScope.lang = lang;
context.setLocale(new Locale(lang.toLowerCase()));
} else {
sessionScope.lang = Appconfig.defaultLang;
context.setLocale(new Locale(Appconfig.defaultLang.toLowerCase()));
}
}
//need to trpa the redirect error thrown here, as it is just a warning - avoid filling log with this
//importPackage(com.ibm.xsp.acl.RedirectSignal);
importPackage(com.ibm.xsp.acl.RedirectSignal);
try {
//reload the page so Locale value kicks in
context.reloadPage();
} catch (RedirectSignal rs) {
//just ignore
}
}
Even though I added the importPackage line, I am still getting an error when saving the code (it is in a script Library):
Encountered " "rs"" at line...
How can I make this work?
Thanks :D
The catch is a Throwable, not a RedirectSignal. Here's the code I use in my handleException function
try {
try {
if (t instanceof RedirectSignal) {
return;
}
if ("javax.faces.el.EvaluationException".equals(t.getClass().getName())) {
if (t.getCause() instanceof RedirectSignal) {
return;
}
}
} catch (Throwable e) {
// Error checking cause, skip
}
// Now log the error
} catch (Throwable e) {
e.printStackTrace();
}
In SSJS you don't define the type/class of the exception in the catch block. Since you're not doing anything with the "exception", there's also no need to import the RedirectSignal class.
try {
context.reloadPage();
} catch ( redirectSignal ) {
// Ignore redirect signal "exception"
}

J2ME XML Parsing

I have another question about a "JDWP Error: 21" logged: Unexpected JDWP Error 21
I am trying to parse some XML I gather from a servlet into a J2ME MIDlet with the code below. So far unsuccessfully, I think due to the JDWP error on my HttpConnection how ever the InputStream is filled with XML and once parsed everything inside the Document is null.
Has anyone got and ideas about the JDWP error, and also does that code look like it should work?
In MIDlet I am using JSR-172 API javax.xml.parsers.*.
if(d==form1 && c==okCommand)
{
// Display Webpage
webPage = new TextBox(txtField.getString(),
"",
100000,
TextField.ANY
);
Display.getDisplay(this).setCurrent(webPage);
try
{
HttpConnection conn = (HttpConnection)Connector.open("http://localhost:8080/Blogging_Home/Interface?Page=Bloggers&Action=VIEW&Type=XML");
conn.setRequestMethod(HttpConnection.GET);
int rc = conn.getResponseCode();
getConnectionInformation(conn, webPage);
webPage.setString(webPage.getString() + "Starting....");
String methodString = getStringFromURL("");
if (rc == HttpConnection.HTTP_OK)
{
InputStream is = null;
is = createInputStream(methodString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document;
try
{
builder = factory.newDocumentBuilder();
document = builder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
webPage.setString(webPage.getString() + "ERROR:" + rc);
}
}
catch(Exception ex)
{
// Handle here
webPage.setString("Error" + ex.toString());
}

groovy HTTP Builder not returning results

I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text

Resources