Intercept rendered HTML - java

I am writing a web-application using Play 1.2.3. One of the feature is to export a rendered HTML page as PDF. I already have the HTML template rendered dynamically based on the parameters sent by the server.
I am planning to use wkhtmltopdf to convert the rendered HTML to PDF. Is there a way in which I can intercept the final HTML (processed by the framework by replacing all template tags) for this purpose..? Or is there a better way to achieve this?

There is already a module for that : http://www.playframework.org/modules/pdf
If you want to do it yourself you can watch in the Controller class how a template is loaded and replace some part to get the rendered template as a string
protected static String renderTemplate(String templateName, Map<String,Object> args) {
try {
Template template = TemplateLoader.load(template(templateName));
// Get the template into a String
return template.render(args);
} catch (TemplateNotFoundException ex) {
if (ex.isSourceAvailable()) {
throw ex;
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex);
if (element != null) {
throw new TemplateNotFoundException(templateName, Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber());
} else {
throw ex;
}
}

Related

Java Spring Boot - getting images paths for emails to work in Freemarker

I am new to Java Spring boot. -
I've got access to the Freemarker demo -- but how do I get hold of the image path for "\src\main\resources\static\images"
//Map < String, Object > model = new HashMap < String, Object > ();
model.put("firstName", "Yashwant");
model.put("lastName", "Chavan");
model.put("imgPath", "resources/static/images/");
mimeMessageHelper.setText(geContentFromTemplate(fmConfiguration, model), true);
mailSender.send(mimeMessageHelper.getMimeMessage());
} catch (MessagingException e) {
System.out.println("ERROR - mimeMessage>>>");
e.printStackTrace();
}
}
}
public String geContentFromTemplate(Configuration fmConfiguration, Map < String, Object > model) {
StringBuffer content = new StringBuffer();
try {
content.append(FreeMarkerTemplateUtils
.processTemplateIntoString(fmConfiguration.getTemplate("email-template.html"), model));
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
Spring already provides this out of the box, where you can map such paths to static URIs.
What you will need to do is, define a Spring Configuration class, extend it with WebMvcConfigurerAdapter
This will give you access to addResourceHandlers method, override that method and provide the path to your static resources along with what URI you want to map it with. Am providing link to another SO answer which does the same thing.
Spring 4 loading static resources
Spring 4 - addResourceHandlers not resolving the static resources

Get the HTML page using htmlunit

I am trying to get the HTML page of a website (ex http://htmlunit.sourceforge.net) but I get an error of IlleagalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver. My code is as follow:
public class Main1 {
public static void main(String[] args) {
try {
homePage();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void homePage() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://www.google.com");
String text = page.asText();
System.out.println(text);
}
}
}
Is there something wrong with the code? Thanks
It's counter-intuitive but we can use asXml() on HtmlPage or HtmlElement to get it as HTML/XML representation.
page.asXml()
The way you wrote the code, it will return a text representation for what would be shown to a used on browser.
May you need to add this to enable JavaScript:
webClient.options.setJavaScriptEnabled(true)
IlleagalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver
This looks like a wrong version of the HttpClient dependency. Please check your classpath to have only one (and only the correct) version of every dependency.
For the current version you can finde a list of dependencies here http://htmlunit.sourceforge.net/dependencies.html
You can use jsoup parser.
Little code sample
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");
Advanced Usage
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
Helpful URLs
Dom Navigation
Extracting
Working with URLs

Access Wicket page object outside of wicket component hierarchy

I have pojo classes that handle my backend connections. I want to encapsulate my (backend) error handling in these classes by catching backend exceptions inside.
Is there any way to access the current wicket page (or any component for that matter) to enable me to give feedback to the user from outside the wicket component hierarchy?
class MyService {
...
public void doBackEndThing(){
try {
backEndService.doRemoteCall();
} catch (BackendException e) {
//we're not inside the component hierarchy! so no getPage() available
WebPage page = getCurrentPage();
page.error("Backend is currently not available");
}
}
I've tried the PageManager, but I have no idea how to retrieve the correct version and so I do not know if would work at all:
int version = ?;
WebPage page = (WebPage )Session.get().getPageManager().getPage(version);
There isn't a nice way and it doesn't seem to be a good idea to do this. Your frontend should call your backend not the other way. So the easiest way to do this would be to store the errors inside your service and have your page get these.
class MyService {
private String error;
public void doBackEndThing(){
try {
backEndService.doRemoteCall();
} catch (BackendException e) {
error ="Backend is currently not available";
}
}
}
and
class MyPage extends WebPage {
private MySerivce service;
public void doSomethingFrontendy() {
error = service.getError();
}
}
or you could return an error from your backend method or throw an Exception and handle this in your WebPage or use IRequestCycleListener#onException() like #svenmeier pointed out.
IRequestCycleListener#onException() is a better place for this - you can get access to the current page via RequestCycle#getActiveRequestHandler().

Exception after reading values from jsp page

I am inserting values into database but I am getting UIException here is my code sample,
public void createTeacherInfo(HttpServletRequest request) {
try{
TeacherInfo teacherInfo= new TeacherInfo();
request.getParameter("flowName");
DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
String tId= request.getParameter("teacherId");
teacherInfo.setTeahcerId(Integer.parseInt(tId));
//teacherInfo.setTeahcerId(Integer.parseInt(request.getParameter("teacherId")));
teacherInfo.setTeacherName(request.getParameter("teacherName"));
/*teacherInfo.setDob(df.parse(request.getParameter("dob")));
teacherInfo.setDoj(df.parse(request.getParameter("doj")));*/
teacherInfo.setTeacherEducation(request.getParameter("education"));
teacherInfo.setPreviousEmployeDetails(request.getParameter("prevdetails"));
//teacherInfo.setYearOfExper(Integer.parseInt(request.getParameter("experience")));
teacherInfo.setTeahcherPhoto(request.getParameter("photo"));
teacherInfo.setTeacherEmail(request.getParameter("email"));
System.out.println(tId);
System.out.println("TeacherId");
pupilInfoManagementBusinessService.createTeacherInfo(teacherInfo);
}catch (BusinessException e) {
webLayerLogger.error(CommonUtils.getStackTrace(e));
throw new UIException(e,UIMessageHelper.getLocalValue("exception while Inserting data"));
}
}
In this method after reading all values it will go to service method , Here is service class method,
#Override
public void createTeacherInfo(TeacherInfo teacherInfo) throws BusinessException {
try {
pupilInfoManagementDataService.createTeacherInfo(teacherInfo);
}catch (Exception e) {
businessServiceLogger.error(CommonUtils.getStackTrace(e));
throw new BusinessException(this.getClass(), e, e.getMessage());
}
}
My problem is values are reading but not inserting to database. Please help me in this .
I'll bet the html form for this includes a file upload for the photo. When a form includes a file upload, then request.getParameter will not work any longer (the values will always be null). When you do a file upload you have to use Apache Commons File Upload library to retrieve the parameters from the request, or you can use request.getPart (if you are on the latest version of your servlet container).

JUnit testing for HTML parsing

I'm trying to set up unit tests on a web crawler and am rather confused as to how I would test them. (I've only done unit testing once and it was on a calculator program.)
Here are two example methods from the program:
protected static void HttpURLConnection(String URL) throws IOException {
try {
URL pageURL = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) pageURL
.openConnection();
stCode = connection.getResponseCode();
System.out.println("HTTP Status code: " + stCode);
// append to CVS string
CvsString.append(stCode);
CvsString.append("\n");
// retrieve URL
siteURL = connection.getURL();
System.out.println(siteURL + " = URL");
CvsString.append(siteURL);
CvsString.append(",");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
and:
public static void HtmlParse(String line) throws IOException {
// create new string reader object
aReader = new StringReader(line);
// create HTML parser object
HTMLEditorKit.Parser parser = new ParserDelegator();
// parse A anchor tags whilst handling start tag
parser.parse(aReader, new HTMLEditorKit.ParserCallback() {
// method to handle start tags
public void handleStartTag(HTML.Tag t, MutableAttributeSet a,
int pos) {
// check if A tag
if (t == HTML.Tag.A) {
Object link = a.getAttribute(HTML.Attribute.HREF);
if (link != null) {
links.add(String.valueOf(link));
// cast to string and pass to methods to get title,
// status
String pageURL = link.toString();
try {
parsePage(pageURL); // Title - To print URL, HTML
// page title, and HTTP status
HttpURLConnection(pageURL); // Status
// pause for half a second between pages
Thread.sleep(500);
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}, true);
aReader.close();
}
I've set up a test class in Eclipse and have outline test methods along these lines:
#Test
public void testHttpURLConnection() throws IOException {
classToTest.HttpURLConnection( ? );
assertEquals("Result", ? ? )
}
I don't really know where to go from here. I'm not even sure whether I should be testing live URLs or local files.
I found this question here: https://stackoverflow.com/questions/5555024/junit-testing-httpurlconnection
but I couldn't really follow it and I'm not sure it was solved anyway.
Any pointers appreciated.
There is no one conclusive answer to your question, what you test depends on what your code does and how deep you want to test it.
So if you have a parse method that takes an HTML and returns the string: "this is a parsed html" (obviously not very usefull, but just making a point), you'll test it like:
#Test
public void testHtmlParseSuccess() throws IOException {
assertEquals("this is a parsed html", classToTest.parse(html) ) //will return true, test will pass
}
#Test
public void testHtmlParseSuccess() throws IOException {
assertEquals("this is a wrong answer", classToTest.parse(html) ) //will return false, test will fail
}
There are a lot more methods besides assertEquals() so you should look here.
eventually it is up to you to decide what parts to test and how to test them.
Think about what effects your methods should have. In the first case the expected thing that should happen when HttpURLConnection(url) is called seems to be that the status code and url are appended to something called CvsString. You will have to implement something in CvsString so that you can inspect if that what you expected did actually happen.
However: Looking at your code I would suggest you consult a book about unit testing and how to refactor code so that it becomes well testable. In your code snippets I see a lot of reasons why unit testing your code is difficult if not impossible, e. g. overall use of static methods, methods with side effects, very little separation of concerns etc. Because of this it is impossible to answer your question fully in this context.
Don't get me wrong, this isn't meant in an offending way. It is well worth learning these things it will improve your coding abilities a lot.

Categories

Resources