Problems with Adobe Flash Player blocking HTTP Response - java

I have a project that I have been working on part - time and it is now due to be submitted. I am connected to an external plc via ethernet and trying to retrieve data from the device using HTTP requests. I had this working, with the data being received back in XML format and I was able to parse this data and submit it to a database.
I am only now submitting the project and what was working is no longer working!! Instead of getting the data back in XML format I am getting a message to install Adobe Flash Player. On investigating the problem, Google and the other browsers have disabled some of the abilities of how to control how the flash player can be used. Previously when I had the program running I had to enable flash player on all sites and this worked. Now I am only allowed to enable it on specified sites and no matter what option I input I am still getting the same error.
In relation to the HTTP connection I am getting a code 200 response which shows that the connection is working but I cannot get back the data that I was always getting.
Has anyone else had this problem since Chrome has changed its policy? I have tried other browsers but the same problem. I have tried back tracking with an older version of Chrome but have only been able to get a .exe file to run individually rather than installed on the computer so Netbeans doesn't recognise it. I have tried Firefox and their extended version which is meant to allow for these issues until March/April 2018 but I am getting the same problem with this also.
Any insight or help would be appreciated.
This is the server information
This is the result from the request for information
'<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!--
Smart developers always View Source.
This application was built using Apache Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops and mobile phones via Adobe AIR.
Learn more about Flex at http://flex.apache.org
// -->
<head>
<title></title>
<meta name="google" value="notranslate" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Include CSS to eliminate any default margins/padding and set the height of the html element and
the body element to 100%, because Firefox, or any Gecko based browser, interprets percentage as
the percentage of the height of its parent container, which has to be set explicitly. Fix for
Firefox 3.6 focus border issues. Initially, don't display flashContent div so it won't show
if JavaScript disabled.
-->
<style type="text/css" media="screen">
html, body { height:100%; }
body { margin:0; padding:0; overflow:auto; text-align:center;
background-color: #ffffff; }
object:focus { outline:none; }
#flashContent { display:none; }
</style>
<!-- Enable Browser History by replacing useBrowserHistory tokens with two hyphens -->
<!-- BEGIN Browser History required section -->
<link rel="stylesheet" type="text/css" href="history/history.css" />
<script type="text/javascript" src="history/history.js"></script>
<!-- END Browser History required section -->
<script type="text/javascript" src="451swfob.js"></script>
<script type="text/javascript">
// For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection.
var swfVersionStr = "12.0.0";
// To use express install, set to playerProductInstall.swf, otherwise the empty string.
var xiSwfUrlStr = "451inst.swf";//"expressInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "WebApp";
attributes.name = "WebApp";
attributes.align = "middle";
swfobject.embedSWF(
"WebApp.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
// JavaScript enabled so display the flashContent div in case it is not replaced with a swf object.
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>
</head>
<body>
<!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough
JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show
when JavaScript is disabled.
-->
<div id="flashContent">
<p>
To view this page ensure that Adobe Flash Player version
12.0.0 or greater is installed.
</p>
<script type="text/javascript">
var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"
+ pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" );
</script>
</div>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="WebApp">
<param name="movie" value="WebApp.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="WebApp.swf" width="100%" height="100%">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<!--<![endif]-->
<!--[if gte IE 6]>-->
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
12.0.0 or greater is not installed.
</p>
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</noscript>
</body>
</html>`
This is basically telling me to install Adobe Flash Player as far as I can see which is already done!
The following is code from the servlet.
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.ByteArrayInputStream;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.xml.sax.*;
import javax.xml.parsers.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.*;
/**
*
* #author ******
*/
#WebServlet(urlPatterns = {"/DeviceReadDateTime"})
public class DanfossDeviceReadDateTime extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
String userName;
String userPassword;
String siteAddress;
String tagReference;
String reportType;
String danfossResponseXMLReturned;
String danfossReadDateTimeYear;
String danfossReadDateTimeMonth;
String danfossReadDateTimeDay;
String danfossReadDateTimeHour;
String danfossReadDateTimeMinute;
String danfossReadDateTimeSecond;
String danfossReadDateTimeEpoch;
String danfossReadDateTimeTimeZone;
String danfossReadDateTimeDayLightSavings;
Connection conn;
PreparedStatement prepStat;
Statement stat;
ResultSet rs = null;
/**
*
* #throws ServletException
*/
#Override
public void init() throws ServletException
{
String connectionUrl ="jdbc:sqlserver://localhost:***;" +
"databaseName=*******************;user=**;password=*****";
try{
// establishing the connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(connectionUrl);
System.out.println("You are connected to SQLServer 2014");
// stat = (Statement) conn.createStatement();
// retrieve data
/* Statement st = (Statement) conn.createStatement();
ResultSet rs1 = st.executeQuery("select * from danfossDateTime");
while(rs1.next()){
danfossReadDateTimeYear = rs1.getString(1);
danfossReadDateTimeMonth = rs1.getString(2);
danfossReadDateTimeDay = rs1.getString(3);
danfossReadDateTimeHour = rs1.getString(4);
danfossReadDateTimeMinute = rs1.getString(5);
danfossReadDateTimeSecond = rs1.getString(6);
danfossReadDateTimeEpoch = rs1.getString(7);
danfossReadDateTimeTimeZone = rs1.getString(8);
danfossReadDateTimeDayLightSavings = rs1.getString(9);
System.out.println("danfossReadDateTimeYear = " + danfossReadDateTimeYear + "\n"
+ "danfossReadDateTimeMonth = " + danfossReadDateTimeMonth + "\n"
+ "danfossReadDateTimeDay = " + danfossReadDateTimeDay
+ "danfossReadDateTimeHour = " + danfossReadDateTimeHour + "\n"
+ "danfossReadDateTimeMinute = " + danfossReadDateTimeMinute + "\n"
+ "danfossReadDateTimeSecond = " + danfossReadDateTimeSecond + "\n"
+ "danfossReadDateTimeEpoch = " + danfossReadDateTimeEpoch + "\n"
+ "danfossReadDateTimeTimeZone = " + danfossReadDateTimeTimeZone + "\n"
+ "danfossReadDateTimeDayLightSavings = " + danfossReadDateTimeDayLightSavings + "\n");
}
System.out.println("Data retrieved from MS SQL");
*/
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}// end of init method// end of init method// end of init method// end of init method
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Cookie cookie = null;
Cookie cookiesArray[] = null;
//get an array of cookies associated with this domain
cookiesArray = request.getCookies();
if(cookiesArray != null)
{
for(int i = 0; i<cookiesArray.length; i++)
{
cookie = cookiesArray[i];
switch (cookie.getName()) {
case "userName":
userName = cookie.getValue();
break;
case "userPassword":
userPassword = cookie.getValue();
break;
case "siteAddress":
siteAddress = cookie.getValue();
siteAddress = ("http:\\").concat(siteAddress);
break;
}
}
}
//Code requesting that data from the danfoss unit
XPath path;
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<cmd action=\"read_date_time\" node =\"1\"/>\r\n\r\n";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType, xmlString);
Request danfossRequest = new Request.Builder()
.url(siteAddress)
.post(body)
.build();
System.out.println("danfossRequest = " + danfossRequest);
Response danfossResponse = client.newCall(danfossRequest).execute();
System.out.println("danfossResponse = " + danfossResponse);
// converting string to xml and parsing
danfossResponseXMLReturned = danfossResponse.body().string();
System.out.println("danfossResponseXMLReturned = " + danfossResponseXMLReturned);
XMLReader parser;
try {
Document dbfactory =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new ByteArrayInputStream(danfossResponseXMLReturned.getBytes("utf-8"))));
XPathFactory xpfactory = XPathFactory.newInstance();
path = xpfactory.newXPath();
danfossReadDateTimeYear = path.evaluate("/resp/year", dbfactory);
danfossReadDateTimeMonth = path.evaluate("/resp/month", dbfactory);
danfossReadDateTimeDay = path.evaluate("/resp/day", dbfactory);
danfossReadDateTimeHour = path.evaluate("/resp/hour", dbfactory);
danfossReadDateTimeMinute = path.evaluate("/resp/minute", dbfactory);
danfossReadDateTimeSecond = path.evaluate("/resp/second", dbfactory);
danfossReadDateTimeEpoch = path.evaluate("/resp/epoch", dbfactory);
danfossReadDateTimeTimeZone = path.evaluate("/resp/timezone", dbfactory);
danfossReadDateTimeDayLightSavings = path.evaluate("/resp/daylightsavings", dbfactory);
//print results
System.out.println("danfossReadDateTimeYear = " + danfossReadDateTimeYear);
System.out.println("danfossReadDateTimeMonth = " + danfossReadDateTimeMonth);
} catch (FactoryConfigurationError err) {
System.err.println ("can't create JAXP SAXParserFactory, "
+ err.getMessage ());
} catch (ParserConfigurationException err) {
System.err.println ("can't create XMLReader with namespaces, "
+ err.getMessage ());
} catch (SAXException err) {
System.err.println ("Hmm, SAXException, " + err.getMessage ());
} catch (XPathExpressionException ex) {
Logger.getLogger(DanfossDeviceReadDevices.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(danfossReadDateTimeYear);
System.out.println(danfossReadDateTimeMonth);
System.out.println(danfossReadDateTimeDay);
System.out.println(danfossReadDateTimeHour);
System.out.println(danfossReadDateTimeMinute);
System.out.println(danfossReadDateTimeSecond);
System.out.println(danfossReadDateTimeEpoch);
System.out.println(danfossReadDateTimeTimeZone);
System.out.println(danfossReadDateTimeDayLightSavings);
// submit data to database
/* try{
String query = "INSERT INTO danfossDateTime VALUES (?,?,?,?,?,?,?,?,?)";
prepStat = (PreparedStatement) conn.prepareStatement(query);
prepStat.setString(1,danfossReadDateTimeYear);
prepStat.setString(2,danfossReadDateTimeMonth);
prepStat.setString(3,danfossReadDateTimeDay);
prepStat.setString(4,danfossReadDateTimeHour);
prepStat.setString(5,danfossReadDateTimeMinute);
prepStat.setString(6,danfossReadDateTimeSecond);
prepStat.setString(7,danfossReadDateTimeEpoch);
prepStat.setString(8,danfossReadDateTimeTimeZone);
prepStat.setString(9,danfossReadDateTimeDayLightSavings);
prepStat.executeUpdate();
}catch(Exception e)
{
}
*/
//html page output
response.setContentType("text/html;charset=UTF-8");
// out = response.getWriter();
String title = "***";
String docType = "<!doctype html>";
out.println(docType + "<html>\n" +
"<head>\n" +
" <title>***</title>\n" +
" <link rel=\"stylesheet\" type=\"text/css\" href=\"***RemoteSiteDataCheckerCSS2.css\"/>\n" +
"</head>\n" +
"<body>\n" +
" \n" +
" \n" +
" <section id=\"logo\">\n" +
" <!-- Introduction on the company -->\n" +
" <header>\n" +
" <center><h1>**************</h1></center>\n" +
" \n" +
" <center><h3>Remote Site Data Checker</h3></center>\n" +
" </header>\n" +
" </section>\n" +
" \n" +
" \n" +
" \n" +
" <section>\n" +
" <form action=\"SubmitTestData\" method=\"POST\">\n" +
" <label>User Name</label> <input type=\"text\" name=\"userName\" value=\"" + userName + "\">\n" +
" <br>\n" +
" <label>Password</label> <input type=\"password\" name=\"userPassword\" value=\"" + userPassword + "\">\n" +
" <br>\n" +
" <label>Site Address</label> <input type=\"text\" name=\"siteAddress\" value=\"" + siteAddress + "\">\n" +
" <br>\n" +
" <label></label><input type=\"submit\" value=\"Submit Test Data\"/>\n" +
" \n" +
" </form>\n" +
" </section> \n" +
" \n" +
" <section>\n" +
" <form>\n" +
" <label>Results:</label>\n" +
" \n" +
" <textarea name=\"resultsTextBox\" rows=\"10\" cols=\"80\" wrap=\"hard\">\n" +
" Results now here...\n" + danfossResponseXMLReturned +
" \nFrom XML Dom BUilder - year = " + danfossReadDateTimeYear +
" \nFrom XML Dom BUilder - month = " + danfossReadDateTimeMonth +
" \nFrom XML Dom BUilder - day = " + danfossReadDateTimeDay +
" \nFrom XML Dom BUilder - hour = " + danfossReadDateTimeHour +
" \nFrom XML Dom BUilder - minute = " + danfossReadDateTimeMinute +
" \nFrom XML Dom BUilder - second = " + danfossReadDateTimeSecond +
" \nFrom XML Dom BUilder - epoch = " + danfossReadDateTimeEpoch +
" \nFrom XML Dom BUilder - timezone = " + danfossReadDateTimeTimeZone +
" \nFrom XML Dom BUilder - daylightsavings = " + danfossReadDateTimeDayLightSavings +
" </textarea>\n" +
" </form>\n" +
" </section> \n" +
" \n<section>\n" +
" <button onclick=\"location.href='index.html'\">Home Page</button>\n" +
" <button onclick=\"location.href='DanfossDeviceHome.html'\">Generate New Report</button>\n" +
" \n" +
" </section>" +
" \n" +
" <footer>\n" +
" <!-- Footer -->\n" +
" <hr>\n" +
" \n" +
" <p>**********************</p>\n" +
" </footer>\n" +
" \n" +
"</body>\n" +
"</html>\n" +
"\n");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Related

Problem converting HTML with Japanese character To PDF using java with YaHP Html to Pdf Converter

I'm trying to convert html string with Japanese character to PDF using YaHP Html to Pdf Converter.
I am using Eclipse Photon Release (4.8.0)
Here is my main class that invokes the YaHP Html :
public static void main(String[] args) {
String pdfOutFileName = "C:\\test\\JP-Test.pdf";
double pageHeight = 80;
String htmlContent = "<html>\r\n" +
" <head>\r\n" +
" <meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">\r\n" +
" <style type=\"text/css\">\r\n" +
" span.cls_005hr{font-family:Arial,serif;font-size:16.8px;color:rgb(50,50,50);font-weight:normal;font-style:normal;text-decoration: none}\r\n" +
" div.cls_005hr{font-family:Arial,serif;font-size:14.8px;color:rgb(50,50,50);font-weight:normal;font-style:normal;text-decoration: none}\r\n" +
" </style>\r\n" +
" </head>\r\n" +
" <body>\r\n" +
" <table border=0 cellpadding=0 cellspacing=0 width=720>\r\n" +
" <col width=10 >\r\n" +
" <col width=710 >\r\n" +
" <tr>\r\n" +
" <td valign=\"middle\" height=\"80\" bgcolor=\"#f0f0f0\">\r\n" +
" <div><span class=\"cls_005hr\">JPTesting</span></div>\r\n" +
" </td>\r\n" +
" <td valign=\"middle\" height=\"80\" bgcolor=\"#f0f0f0\">\r\n" +
" <div><span class=\"cls_005hr\">株式会社 ビー・エス・デーインフォメーションテクノロジー</span></div>\r\n" +
" </td>\r\n" +
" </span>\r\n" +
" </tr>\r\n" +
" </table>\r\n" +
" </body>\r\n" +
"</html>";
System.out.println("htmlContent: [" + htmlContent + "]");
try {
ByteArrayOutputStream outFormPDF = new ByteArrayOutputStream();
outFormPDF = PDFUtil.convertHtmlToPDF(htmlContent, pageHeight);
byte[] bOutFormPDF = outFormPDF.toByteArray();
OutputStream os = new FileOutputStream(pdfOutFileName);
os.write(bOutFormPDF);
System.out.println("Successfully Finished writing PDF to output file");
os.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
and here is the PDFUtil class method that calls YaHP Converter
public static ByteArrayOutputStream convertHtmlToPDF (String htmlContent, double pageHeight) throws CConvertException, IOException {
ByteArrayOutputStream outFormPDF = new ByteArrayOutputStream();
Scanner scanner = new Scanner(htmlContent).useDelimiter("\\Z");
String htmlContents = scanner.next();
CYaHPConverter converter = new CYaHPConverter();
Map properties = new HashMap();
List headerFooterList = new ArrayList();
URL resource = PDFUtil.class.getClassLoader().getResource("fonts");
String fontDirectory = resource.getPath() ;
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS, IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontDirectory);
PageSize pageSize = IHtmlToPdfTransformer.LEGALP;
if (pageHeight>0) {
String sHeight = Double.toString(pageHeight);
sHeight = sHeight.substring(0,sHeight.indexOf("."));
pageHeight = Double.parseDouble(sHeight);
System.out.println ("pageHeight : " + pageHeight);
pageSize = new PageSize(21.6d, pageHeight, 0.7d, 0.5d, 1.5d, 1.5d);
}
System.out.println ("Calling converter.convertToPdf");
converter.convertToPdf(htmlContents,
pageSize,
headerFooterList,
"file://tmp/Html2PdfConvertTemp",
outFormPDF,
properties);
System.out.println ("Successfully Called converter.convertToPdf");
scanner.close();
return outFormPDF;
}
For some reason, the output PDF file contains "JPTesting", but does not contain the Japanese letters : "株式会社 ビー・エス・デーインフォメーションテクノロジー" .
Any help would be much appreciated.
Found the solution. Posting my solution here in case anyone else may struggle with the same issue that I had.
I have added Japanese font from google : https://fonts.google.com/?subset=japanese (I Picked Shippori Mincho B1), added to my font resource directory.
Updated my html CSS to pick up those new fonts :
span.cls_005jp{font-family:Shippori Mincho B1, Arial,serif;...
Update my html to use those new fonts for tags that may contain Japanese letters :
株式会社 ビー・エス・デーインフォメーションテクノロジー\r\n"
Thank you, #g00se, for pointing me to the right direction!

getting wrong arabic translation in PDF iText

I am generating PDF file from my HTML string, But when PDF file getting generated the content in HTML and PDF does not match. The content is PDF is some random content. I read about the issue on google and they suggest using Unicode notation like %u0627%u0646%u0627%20%u0627%u0633%u0645%u0649%20%u0639%u0628%u062F%u0627%u0644%u0644%u0647. But I am putting this into my HTML it is getting printing as it is.
related issue: Writing Arabic in pdf using itext
package com.example.demo;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.css.media.MediaType;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(DemoApplication.class, args);
String htmlSource = getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ConverterProperties converterProperties = new ConverterProperties();
FontProvider dfp = new DefaultFontProvider(true, false, false);
dfp.addFont("/Library/Fonts/Arial.ttf");
converterProperties.setFontProvider(dfp);
converterProperties.setMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));
HtmlConverter.convertToPdf(htmlSource, outputStream, converterProperties);
byte[] bytes = outputStream.toByteArray();
File pdfFile = new File("java19.pdf");
FileOutputStream fos = new FileOutputStream(pdfFile);
fos.write(bytes);
fos.flush();
fos.close();
}
private static String getContent() {
return "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
" <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n" +
" <title>Document</title>\n" +
" <style>\n" +
" #page {\n" +
" margin: 0;\n" +
" font-family: arial;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"\n" +
"<body\n" +
" style=\"margin: 0;padding: 0;font-family: arial, sans-serif;font-size: 14px;line-height: 125%;width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #222222;\">\n" +
" <table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background: white; direction: rtl;\">\n" +
" <tbody>\n" +
" <tr>\n" +
" <td style=\"padding: 0 35px;\">\n" +
" <p> انا اسمى عبدالله\n" +
" </p>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
"\n" +
"</body>\n" +
"\n" +
"</html>";
}
}
It's difficult to determine what the issue is exactly without seeing the faulty output. But your "random content" sounds like an encoding issue.
Since you have your Arabic content directly in your source code, you have to be careful about encoding. For example, using ISO-8859-1, the resulting PDF output is:
Using Unicode escape sequences (\uXXXX), you can indeed avoid some of these encoding issues. Replacing
" <p> انا اسمى عبدالله\n" +
with
" <p>\u0627\u0646\u0627 \u0627\u0633\u0645\u0649 \u0639\u0628\u062F\u0627\u0644\u0644" +
results in Arabic glyphs, even when using ISO-8859-1 encoding. Alternatively, you can use UTF-8 to get the correct content regardless of the use of Unicode escape sequences.
When your encoding issues are solved, you will likely get output like this:
For correct rendering of certain writing systems, an optional module pdfCalligraph is needed for iText 7. With this module enabled, the resulting output looks like this:
The code used for the tests above:
public static void main(String[] args) throws IOException {
// Needed for pdfCalligraph
LicenseKey.loadLicenseFile("all-products.xml");
File pdfFile = new File("java19.pdf");
OutputStream outputStream = new FileOutputStream(pdfFile);
String htmlSource = getContent();
ConverterProperties converterProperties = new ConverterProperties();
FontProvider dfp = new DefaultFontProvider(true, false, false);
dfp.addFont("/Library/Fonts/Arial.ttf");
converterProperties.setFontProvider(dfp);
converterProperties.setMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));
HtmlConverter.convertToPdf(htmlSource, outputStream, converterProperties);
}
private static String getContent() {
return "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
" <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n" +
" <title>Document</title>\n" +
" <style>\n" +
" #page {\n" +
" margin: 0;\n" +
" font-family: arial;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"\n" +
"<body\n" +
" style=\"margin: 0;padding: 0;font-family: arial, sans-serif;font-size: 14px;line-height: 125%;width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #222222;\">\n" +
" <table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"background: white; direction: rtl;\">\n" +
" <tbody>\n" +
" <tr>\n" +
" <td style=\"padding: 0 35px;\">\n" +
// Arabic content
// " <p> انا اسمى عبدالله\n" +
// Arabic content with Unicode escape sequences
" <p>\u0627\u0646\u0627 \u0627\u0633\u0645\u0649 \u0639\u0628\u062F\u0627\u0644\u0644\u0647" +
" </p>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
"\n" +
"</body>\n" +
"\n" +
"</html>";
}
Please check to make sure that your sourcefile and compiler use the same encoding, e.g. UTF-8. I sometimes check that by including characters that are only available in unicode and not in other classic codepages.
I tried to reproduce the issue and I got the following warning in the logging when running the example code:
Cannot find pdfCalligraph module, which was implicitly required by one of the layout properties
This was already mentioned by Alexsey Subach and can cause the following issue:
Problems with text direction (I am no expert on Arabic but the text was aligned to the right)
Wrong combination of characters (For the details see this document: https://itextpdf.com/sites/default/files/2018-12/iText_pdfCalligraph_4pager.pdf )
This is the output I got without pdfCalligraph:
pdf result without calligraph
Created with the codebase on this repository
So in order to get everything to work perfectly like your browser does with the HTML for Arabic you will also need:
A commercial license for https://itextpdf.com/en/products/itext-7/pdfcalligraph
Code to load the license file (or you will get a LicenseFileNotLoadedException )
This dependency https://repo.itextsupport.com/releases/com/itextpdf/typography/2.0.6/
Your question is tagged as regarding iText7 but there may be other possible free alternatives depending on your requirements like Apache FOP that should work with Arabic Ligatures according to this source but probably require rework as it is based on XSL-FO. In theory you could generate the XSL-FO with any templating mechanism that you currently use e.g.: JSP/JSF/Thymeleaf etc. and use something like a ServletFilter to convert the XSL-FO to a PDF on the fly during a request (in a web application)
Make sure your fonts support the characters you need and if you use Maven resource directory to include extra fonts during the build check that the font file is not filtered (properties replacement) as that corrupts the file: Maven corrupting binary files in source/main/resources when building jar

IBM Maximo - sending HTML email

I need to send HTML e-mail from Maxima, but as a result, only text without tags and without a table comes to the mail, how I can do it true?
Code example:
package com.vetasi.testPackage;
import psdi.server.MXServer;
import psdi.server.SimpleCronTask;
import psdi.util.logging.MXLogger;
import psdi.util.logging.MXLoggerFactory;
public class Test1 extends SimpleCronTask{
MXLogger logger = MXLoggerFactory.getLogger("com.test.TestReportCron");
#Override
public void cronAction(){
String message1 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n" +
" <head>\r\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\r\n" +
" <title>Title</title>\r\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\r\n" +
"</head>\r\n" +
"<body style=\"margin: 0; padding: 0;\">\r\n" +
" <table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\r\n" +
" <tr>\r\n" +
" <td>\r\n" +
" Hello!\r\n" +
" </td>\r\n" +
" </tr>\r\n" +
" </table>\r\n" +
"</body>\r\n" +
"</html>" ;
try{
MXServer.sendEMail("Misha89uatest#gmail.com", "maxadmin#us.ibm.com", "Hello my friend", message1);
}catch (Exception e) {
logger.error(e.getStackTrace());
e.printStackTrace();
}
}
}
Result:
Comes e-mail
When I using the Java Mail API, everything works fine, but there is much more code, and it is preferable to do in Maximo methods Anybody has any ideas?

Why does the crawler4j example give an error? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to use the Basic crawler example in crawler4j. I took the code from the crawler4j website here.
package edu.crawler;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.Header;
public class MyCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
}
}
Above is the code for the crawler class from the example.
public class Controller {
public static void main(String[] args) throws Exception {
String crawlStorageFolder = "../data/";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(MyCrawler.class, numberOfCrawlers);
}
}
Above is the class for the controller class for the web crawler.
When I try to run the Controller class from my IDE (Intellij) I get the following error:
Exception in thread "main" java.lang.UnsupportedClassVersionError: edu/uci/ics/crawler4j/crawler/CrawlConfig : Unsupported major.minor version 51.0
Is there something about the maven config that is found here that I should know? Do I have to use a different version or something?
The problem wasn't with crawler4j. The problem was that the version of Java that I was using was different from the latest version of Java that is used in crawler4j. I switched the version right before they updated to Java 7 and everything worked fine. I'm guessing that upgrading my version of Java to 7 would have the same effect.

Building Wikipedia query forms in java using jena

#!/usr/local/bin/python
import sys
sys.path.append('/usr/home/bobd/lib/python/') # needed for hosted version
from SPARQLWrapper import SPARQLWrapper, JSON
import string
import urllib
import cgi
def main():
form = cgi.FieldStorage()
dir1name = form.getvalue('dir1')
dir2name = form.getvalue('dir2')
sparql = SPARQLWrapper("http://data.linkedmdb.org/sparql")
queryString = """
PREFIX m: <http://data.linkedmdb.org/resource/movie/>
SELECT DISTINCT ?actorName WHERE {
?dir1 m:director_name "DIR1-NAME".
?dir2 m:director_name "DIR2-NAME".
?dir1film m:director ?dir1;
m:actor ?actor.
?dir2film m:director ?dir2;
m:actor ?actor.
?actor m:actor_name ?actorName.
}
"""
queryString = queryString.replace("DIR1-NAME",dir1name)
queryString = queryString.replace("DIR2-NAME",dir2name)
sparql.setQuery(queryString)
sparql.setReturnFormat(JSON)
try:
ret = sparql.query()
results = ret.convert()
requestGood = True
except Exception, e:
results = str(e)
requestGood = False
print """Content-type: text/html
<html>
<head>
<title>results</title>
<link href="simple.css" type="text/css" rel="stylesheet" />
</head>
<body>
"""
if requestGood == False:
print "<h1>Problem communicating with the server</h1>"
print "<p>" + results + "</p>"
elif (len(results["results"]["bindings"]) == 0):
print "<p>No results found.</p>"
else:
for result in results["results"]["bindings"]:
print "<p>" + result["actorName"]["value"] + "</p>"
print "</body></html>"
main()
i got the above code from http://www.ibm.com/developerworks/xml/library/x-wikiquery/#download
Now,i want to do the same thing in java with servlets instead of cgi script.
so,how do i pass the query from servlet to http://data.linkedmdb.org/sparql endpoint using jena ?
and how should i get the result back and display it in a html form ?
PLease,HELP
Here's some example code. Note that I wouldn't actually do it this way for real: the presentation code and the back-end query handling are all mixed up in one class. Real apps don't do this! The example is faithful to your sample, except that rather than string-bash the query, I use Jena's facility to pre-bind some of the query variables (so DIR1-NAME becomes ?dir-1-name). I think this is much cleaner, and gives you more flexibility as to which of the query parameters are passed in from the client.
package example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.*;
public class ServletExample
extends HttpServlet
{
/***********************************/
/* Constants */
/***********************************/
private static final long serialVersionUID = 1L;
public static final String SPARQL_ENDPOINT = "http://data.linkedmdb.org/sparql";
public static final String QUERY = "PREFIX m: <http://data.linkedmdb.org/resource/movie/>\n" +
"SELECT DISTINCT ?actorName WHERE {\n" +
" ?dir1 m:director_name %dir_name_1%.\n" +
" ?dir2 m:director_name %dir_name_2%.\n" +
" ?dir1film m:director ?dir1;\n" +
" m:actor ?actor.\n" +
" ?dir2film m:director ?dir2;\n" +
" m:actor ?actor.\n" +
" ?actor m:actor_name ?actorName.\n" +
"}\n" +
"";
private static final String HEADER = "<html>\n" +
" <head>\n" +
" <title>results</title>\n" +
" <link href=\"simple.css\" type=\"text/css\" rel=\"stylesheet\" />\n" +
" </head>\n" +
" <body>\n" +
"";
private static final String FOOTER = "</body></html>";
/**
* Respond to HTTP GET request. Will need to be mounted against some URL
* pattern in web.xml
*/
#Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
String dir1 = req.getParameter( "dir1" );
String dir2 = req.getParameter( "dir2" );
if (dir1 == null || dir2 == null || dir1.isEmpty() || dir2.isEmpty()) {
noInput( resp );
}
else {
runQuery( resp, dir1, dir2 );
}
}
protected void noInput( HttpServletResponse resp )
throws IOException
{
header( resp );
resp.getWriter().println( "<p>Please select director names as query params <code>dir1</code> and <code>dir2</code></p>" );
footer( resp );
}
protected void footer( HttpServletResponse resp ) throws IOException {
resp.getWriter().println( FOOTER );
}
protected void header( HttpServletResponse resp ) throws IOException {
resp.getWriter().println( HEADER );
}
protected void runQuery( HttpServletResponse resp, String dir1, String dir2 )
throws IOException
{
PrintWriter out = resp.getWriter();
// Set up the query
String q = QUERY.replace( "%dir_name_1%", "\"" + dir1 + "\"" )
.replace( "%dir_name_2%", "\"" + dir2 + "\"" );
Query query = QueryFactory.create( q ) ;
QueryExecution qexec = QueryExecutionFactory.sparqlService( SPARQL_ENDPOINT, query );
// perform the query
ResultSet results = qexec.execSelect();
// generate the output
header( resp );
if (!results.hasNext()) {
out.println( "<p>No results, sorry.</p>" );
}
else {
out.println( "<h1>Results</h1>" );
while (results.hasNext()) {
QuerySolution qs = results.next();
String actorName = qs.getLiteral( "actorName" ).getLexicalForm();
out.println( String.format( "<div>Actor named: %s</div>", actorName ) );
}
}
footer( resp );
}
}
This code works as far as I can tell, but I don't know which queries you're using that should return some results.

Categories