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?
Related
i developed android app and i used HTML code to Print the result in formatted form.
the code will be like this :
String adress = editText1.getText().toString();
String phone = editText2.getText().toString();
String licenseNo = editText3.getText().toString();
"\n" +
" <div class=\"down\">\n" +
" <div class=\"EASY\">\n" +
" <img src=\"" + image + "\" alt=\"QR\" >\n" +
" </div>\n" +
" <table class=\" info_table\">\n" +
" <tbody>\n" +
" <tr>\n" +
" <td class=\"info\">" + phone + "</td>\n" +
" <td class=\"info\"> " + licenseNo + "</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td class=\"info_A\" colspan=\"2\"> " + adress + "</td>\n" +
" </tr>\n" +
" </tbody>\n" +
" </table>\n" +
" </div>";
as you see it should contain \n and + because its inside a string object contained variable values from user input.
i faced some difficulty when i need to Edit this Piece of code cose i will test it inside the application.
my question is what is the best way to get this code to edit and preview it outside android studio and reinsert it again.
i used find and replace but it make some problems.
hope i explained enough
You can create a XML file in the resources folder, read it and then use format in order to change the values there.
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
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>
}
I don't know what's going on with the FileWriter, because it only writes out the HTML part, but nothing from the String array content. content stores a lot of long Strings. Is it because of Java's garbage collector?
I print out the content and everything is there, but FileWrter did not write anything from content to that file except the HTML part. I added System.out.println(k); inside the enhanced for-loop. content array is not null though.
public void writeHtml(String[] content) {
File file = new File("final.html");
try {
try (FileWriter Fw = new FileWriter(file)) {
Fw.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+ "<html>\n"
+ "<head>\n"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\n"
+ "<title>" + fileName +" for The Delinquent</title>\n"
+ "<style type = \"text/css\">\n"
+ "body {font-family: \"Times New Roman, serif\"; font-size: 14 or 18; text-align: justify;};\n"
+ "p { margin-left: 1%; margin-right: 1%; }\n"
+ "</style>\n"
+ "</head><body>");
for (String k : content) {
Fw.write(k+"\n");
}
Fw.write("</body></html>");
}
} catch (Exception e) {
e.printStackTrack();
}
}
How the final.html looks like after running the program:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title>the_delinquent.txt for The Delinquent</title>
<style type = "text/css">
body {font-family: "Times New Roman, serif"; font-size: 14 or 18; text-
align: justify;};
p { margin-left: 1%; margin-right: 1%; }
</style>
</head><body>
</body></html>
I know content is not empty because I did this:
for (String k: content) {
System.out.println(k + "\n");
bw.write(k + "\n");
}
Everything printed out. so weird : (
You code is working. The only thing that prevents content to be written - empty content. It has no elements.
Your code iis basically correct, maybe the content array is empty.
The following is in modernized java style.
public void writeHtml(String[] content) {
Path file = Paths.get("final.html");
try (BufferedWriter fw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
fw.write("<!DOCTYPE html>\n"
+ "<html>\n"
+ "<head>\n"
+ "<meta charset=UTF-8\">\n"
+ "<title>" + fileName + " for The Delinquent</title>\n"
+ "<style type = \"text/css\">\n"
+ "body {font-family: \"Times New Roman, serif\";"
+ " font-size: 14 or 18; text-align: justify;};\n"
+ "p { margin-left: 1%; margin-right: 1%; }\n"
+ "</style>\n"
+ "</head><body>");
fw.write("Content has: " + content.length + " strings.<br>\n");
for (String k : content) {
fw.write("* " + k + "<br>\n");
}
fw.write("</body></html>\n");
} catch (IOException e) {
System.out.println("Error " + e.getMessage());
}
}
FileWriter is an old utility class that uses the default charset, so not portable. Better specify the charset to correspond to the charset in HTML.
The encoding UTF-8 allows full Unicode range of characters, like comma like quotes (typical to MS Word). Java internally also uses Unicode, so it is a fine match.
HTML 5 is the latest HTML version, now generally disposable.
At one spot a typo /n entered.
Multiple spaces and line breaks are converted to a single space. So I added <br> for a line break.
Normally one would add to the method header throws IOException to let the caller handle any irregularities.
I am working on Java RestFul WebProjects. In my Project I have one util package that uses JavaMail.java class. In this project I am sending mails to our requirement for that purpose I am adding HTML tags at my String body variable and passing my html code.
My doubt is i need to place html code at one file in my localhost and I need to give the html file path to that string body variable. Is it possible and can anybody help me?
Here i am placing my JavaMail.Java class code:
public static void sendEmailForProfileActivation(int activationCode, String to) throws AddressException, MessagingException {
/**
* Sender's credentials
* */
String from = "helloworld#gmail.com";
String password = "888888";
String sub = "Activate Your Profile using activation code";
//String body = "Activate Profile Using the active Code: <b>" + activationCode + "</b>.";
String body="<html>"
+ "<body>"
+ "<table width=\"100%"+"\" cellpadding=\"0"+"\" cellspacing=\"0"+"\" bgcolor=\"e4e4e4"+"\">"
+ "<tr>"
+ "<td>"
+ "<table id=\"top-message"+"\" cellpadding=\"20"+"\" cellspacing=\"0"+"\" width=\"600"+"\" align=\"center"+"\">"
+ "<tr>"
+ "<td align=\"center"+"\">"
+ "<p>Trouble viewing this email? View in Browser</p>"
+ "</td>"
+ "</tr>"
+ "</table><!-- top message -->"
+ "<table id=\"main"+"\" width=\"570"+"\" align=\"center"+"\" cellpadding=\"0"+"\" cellspacing=\"15"+"\" bgcolor=\"ffffff"+"\">"
+ "<tr>"
+ "<td>"
+ "<table id=\"header"+"\" cellpadding=\"10"+"\" cellspacing=\"0"+"\" align=\"center"+"\" bgcolor=\"8fb3e9"+"\">"
+ "<tr>"
+ "<td width=\"570"+"\" bgcolor=\"#7EB646"+"\">"
+ "<h1><font color=\"white"+"\">HelloWorld Services 15 July 2015</font></h1>"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "</tr>"
+ "</table><!-- header -->"
+ "</td>"
+ "</tr><!-- header -->"
+ " <!--tr>"
+ "<td height=\"30"+"\">"
+ "<img src=\"http://dummyimage.com/570x30/fff/fff"+"\" />"
+ "</td>"
+ "</tr For spacing pupose one image to another where you want space you add this image-->"
+ "<tr>"
+ "<td>"
+ "<table id=\"content-6"+"\" cellpadding=\"0"+"\" cellspacing=\"0"+"\" align=\"center"+"\">"
+ "<p align=\"center"+"\">Activate Profile Using the active Code: <b>" + activationCode + "</b>.</p>"
+ "<p align=\"center"+"\">Activate Your Account</p>"
+ "</table>"
+ "</td>"
+ "</tr>"
+ "</table><!-- main -->"
+ "<table id=\"bottom-message"+"\" cellpadding=\"20"+"\" cellspacing=\"0"+"\" width=\"600"+"\" align=\"center"+"\">"
+ "<tr>"
+ "<td align=\"center"+"\">"
+ "<p>You are receiving this email because you signed up for updates</p>"
+ "<p>Unsubscribe instantly | Forward to a friend | View in Browser</p>"
+ "<p> <img src=\"file:///home/yavat6/Downloads/manDoctor.png"+"\" style=\"width:50px;float:left;height:35px;"+"\"/>If you have any queries contact to us via mail 24*7CONTACT US</p>"
+ "</td>"
+ "</tr>"
+ "</table><!-- bottom message -->"
+ "</table><!-- 100% -->"
+ "</body>"
+ "</html>";
sendMessage(from, password, to,sub, body);
}
Yes you can send the HTML file in your java code. You can make use of getResourceAsStream() to read your .html file and then get the content of this .html file in a String and send this content as a message like :-
InputStream is = Sum.class.getClassLoader().getResourceAsStream("test.html"); // read file as stream, add this html file in yur class path.
BufferedReader br = new BufferedReader(new InputStreamReader(is)) ;
StringBuilder sb = new StringBuilder();
String str = null;
while((str=br.readLine()) != null)
sb.append(str);
String send_to = "test#gmail.com"; // add sender here
Message msg = new MimeMessage(mailSession);
try{
msg.setSubject("Test Email");
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(send_to, false));
String message = sb.toString(); // your html message as string
msg.setContent(message, "text/html; charset=utf-8");
msg.setSentDate(new Date());
Transport.send(msg);
}catch(MessagingException me){
// catch exception here
}