How to read HTML DOM inside the applet - html

I have embedded the signed applet in following html page,
<input type="hidden" name="xmldata" id="xmldata" value=""/>
<APPLET CODE="com.syntel.upload.readFileApplet.class" ARCHIVE="sign-upload.jar" HEIGHT="200" WIDTH="475" ALIGN="bottom">
This browser does not appear to support Applets.
</APPLET>
Following readFileApplet class read the xml file from client filesystem ,
public class readFileApplet extends Applet {
StringBuffer strBuff;
public void init() {
add(txtArea, "center");
readFile();
String xmldata = strBuff.toString();
//TODO: set the xmldata string to html hidden variable
}
public void readFile() {
String line;
try {
InputStream in = new FileInputStream("c:\\ftlmb\\finstmt.xml");
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
strBuff = new StringBuffer();
while ((line = bf.readLine()) != null) {
strBuff.append(line + "\n");
}
} catch (IOException e) {
txtArea.append(e.getMessage());
}
}
}
I am able to read the xml using applet but unable to set the xmldata string to hidden variable "xmldata" which is in html page.
Is there any API which i can use to get the DOM so that i can set the value to hidden variable.
Please help me out to solve this problem.

com.sun.java.browser.dom.DOMService
See http://www.javaworld.com/javaworld/jw-06-2005/jw-0627-plugin.html?page=3

Related

How to send data from libgdx project to web?

I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}

Convert raw HTML codes to PDF File

I want to convert the raw html code to pdf file.
This is my Controller code
#RequestMapping("getpdf")
public void doGet(HttpServletRequest request,
HttpServletResponse response,String ref){
OutputStream out = null;
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
java.util.List items = null;
ArticalBean abean=serviceLayer.getArtical(Integer.parseInt(ref));
items = new ArrayList();
items.add(abean.getArticle());
try {
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
Paragraph paragraph = new Paragraph("Microweb Systems");
document.add(paragraph);
ListItem listItem;
com.lowagie.text.List list = new com.lowagie.text.List(true, 15);
Iterator i = items.iterator();
while(i.hasNext()) {
listItem = new ListItem((String)i.next(),
FontFactory.getFont(FontFactory.TIMES_ROMAN, 12));
list.add(listItem);
}
document.add(list);
} catch (Exception e) {
} finally {
document.close();
}
document.close();
}
It converts the HTML codes to PDF but that pdf also contains the tags
Like
<h1>Hello World</h1>
Is there is any way to remove these tags and show only Data.
I am providing the data from database via DTO.
If I understand your question, you want to remove the tags.
This can be done with String.replaceAll(String regex, String replacement).
For example myString.replaceAll("^<[.]*>$" , ""); would remove any tags.
This, however, does not make the pdf look like the page does in a browser.

iframe doesn't display dynamically generated html file

I'm dynamically creating an HTML file using HTMLTEXTWRITER, I can view it in browsers but when I try to view this html in an iframe, nothing is displayed! what is wrong what dynamically generated htmls? also iframe doesn't display some HTMLs in firefox, here is how I create my html:
static string GetDivElements()
{
// Initialize StringWriter instance.
StringWriter stringWriter = new StringWriter();
// Put HtmlTextWriter in using block because it needs to call Dispose.
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
// Loop over some strings.
foreach (var word in _words)
{
// Some strings for the attributes.
string classValue = "ClassName";
string urlValue = "http://www.dotnetperls.com/";
string imageValue = "image.jpg";
// The important part:
writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
...my html
writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
writer.RenderEndTag(); // End #3
writer.Write(word);
writer.RenderEndTag(); // End #2
writer.RenderEndTag(); // End #1
}
}
// Return the result.
string pre = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
pre += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>";
pre += "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>";
return stringWriter.ToString();// +"</body></html>";
}
private void Form1_Load(object sender, EventArgs e)
{
using (StreamWriter outfile =
new StreamWriter(#"d:\myFile.htm"))
{
outfile.Write(GetDivElements());
}
}

FlyingSaucer: convert an HTML document to PDF ignoring external CSS?

I'm using the following to convert HTML to PDF:
InputStream convert(InputStream fileInputStream) {
PipedInputStream inputStream = new PipedInputStream()
PipedOutputStream outputStream = new PipedOutputStream(inputStream)
new Thread({
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fileInputStream)
ITextRenderer renderer = new ITextRenderer()
renderer.setDocument(document, "")
renderer.layout()
renderer.createPDF(outputStream)
}).start()
return inputStream
}
From the documentation, apparently I should be able to set a "User Agent" resolver somewhere, but I'm not sure where, exactly. Anyone know how to ignore external CSS in a document?
Not the same question but my answer for that one will work here too: Resolving protected resources with Flying Saucer (ITextRenderer)
Override this method:
public CSSResource getCSSResource(String uri) {
return new CSSResource(resolveAndOpenStream(uri));
}
with
public CSSResource getCSSResource(String uri) {
return new CSSResource(new ByteArrayInputStream([] as byte[]));
}

Ant task to extract image dimensions (height, width) from PNG and JPEG files?

Per the Google Page Speed recommendations, I want to Specify image dimensions to "Optimize browser rendering."
Specifying a width and height for all
images allows for faster rendering by
eliminating the need for unnecessary
reflows and repaints.
I am investigating ways to traverse through the image files (PNG, JPEG) in my static content project and output a file with the path and filename of each image file as well as the height and width in pixels. I would then use that to help me construct the tags by using the src attribute data to lookup the values to use for the height and width attributes.
\images\logo.png,100,25
My first ideas was looking for an ANT task, since our static content build uses Ant for other purposes (like using YUI Compressor on JavaScript and CSS files). I am open to other ideas as well, including other methods to solve this problem. I would prefer to not have to manually do this work.
You could try this https://github.com/mattwildig/image-size-report-task, which I've made just for this question.
Here was what I implemented so far (needs testing and clean up). Basically, used Tutorial: Tasks using Properties, Filesets & Paths to get me started in an Ant task and How to get image height and width using java? to extract the image dimensions. I'm going to compare against matt's answer before I deploy.
The test build script from my project:
<project name="ImagesTask" basedir="." default="test">
<target name="init">
<taskdef name="images" classname="ImageInfoTask" classpath="..\dist\ImageTask.jar"/>
</target>
<target name="test" depends="init">
<images outputFile="data/images.xml">
<fileset dir="data" includes="images/**/*.jpg"/>
<fileset dir="data" includes="images/**/*.gif"/>
<fileset dir="data" includes="images/**/*.png"/>
</images>
</target>
</project>
The Java source (without imports):
public class ImageInfoTask extends Task {
private String outputFile;
private List fileSetList = new ArrayList();
private PrintStream outputFileStream;
public void setOutputFile(String outputFile) {
this.outputFile = outputFile.replace("/", File.separator);
}
public void addFileset(FileSet fileset) {
fileSetList.add(fileset);
}
protected void validate() {
if (outputFile == null) {
throw new BuildException("file not set");
}
if (fileSetList.size() < 1) {
throw new BuildException("fileset not set");
}
}
protected void openOutputFile() throws IOException {
FileOutputStream out = new FileOutputStream(this.outputFile);
// Connect print stream to the output stream
this.outputFileStream = new PrintStream(out, true, "UTF-8");
this.outputFileStream.println("<images>");
}
protected void writeImgToOutputFile(String filename, Dimension dim) {
String imgTag = " <img src=\"/" + filename.replace("\\", "/")
+ "\" height=\"" + dim.height + "\" width=\"" + dim.width
+ "\" />";
this.outputFileStream.println(imgTag);
}
protected void closeOutputFile() {
this.outputFileStream.println("</images>");
this.outputFileStream.close();
}
#Override
public void execute() {
validate();
try {
openOutputFile();
for (Iterator itFSets = fileSetList.iterator(); itFSets.hasNext();) {
FileSet fs = (FileSet) itFSets.next();
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
String[] includedFiles = ds.getIncludedFiles();
for (int i = 0; i < includedFiles.length; i++) {
String filename = includedFiles[i];
Dimension dim = getImageDim(ds.getBasedir() + File.separator + filename);
if (dim != null) {
writeImgToOutputFile(filename, dim);
}
}
}
closeOutputFile();
} catch (IOException ex) {
log(ex.getMessage());
}
}
private Dimension getImageDim(final String path) {
Dimension result = null;
String suffix = this.getFileSuffix(path);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
if (iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(new File(path));
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
result = new Dimension(width, height);
} catch (IOException e) {
log(path + ": " + e.getMessage());
} finally {
reader.dispose();
}
}
return result;
}
private String getFileSuffix(final String path) {
String result = null;
if (path != null) {
result = "";
if (path.lastIndexOf('.') != -1) {
result = path.substring(path.lastIndexOf('.'));
if (result.startsWith(".")) {
result = result.substring(1);
}
}
}
return result;
}
}
I'm not aware of such ant task readily available but it should be relatively simple to write one. In PNG format image size is stored right at the beginning of the file in IHDR header. There are numerous samples of PNG parsers on Google - for example this. Wrap it up in ant task and you're done.