call java command from cloud foundry node app - java

In my app, I want to convert PDF file to images, but it looks like there is not a module in node.js. So i want to use the java application do the work.
Can we call java command in the cloud foundry node app?
Thanks.
Hong

OK, so I have built an express app that does the job;
app.js looks like this;
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, util = require('util')
, fs = require('fs')
, exec = require('child_process').execFile
, http = require('http');
process.env.MAGICK_TMPDIR = __dirname + '/tmp'
var app = express();
app.configure(function(){
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir:__dirname + "/uploads"}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.post('/convert', function(req, res) {
var pdf_file = req.files.pdf.path;
var uploadsPath = __dirname + "/uploads"
var filename = pdf_file.split("/")[pdf_file.split('/').length - 1]
var out = __dirname + '/public/images/' + filename + '.png';
exec('convert', [pdf_file, '-append', out], function(err, stdout, stderr) {
res.redirect('/images/' + filename + '.png');
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
The index view looks like this (just a simple multipart form);
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form action="/convert" method="post" enctype="multipart/form-data">
<label>PDF File</label>
<input type="file" name="pdf" />
<input type="submit" />
</form>
</body>
</html>
This all works fine on my private instance of Cloud Foundry (VCAP) but not on CloudFoundry.com, I think this is due to permissions issues. I will chase this up with the engineering team and find out if it is possible to call ImageMagick with the correct permissions.
=========
UPDATE
I have fixed the problem for CloudFoundry.com, it appears to stop ImageMagick from using /tmp as a temp dir the env var MAGICK_TMPDIR has to be set, you can see this in the top of app.js file now.
Am also redirecting to the image now rather then reading it in, works like a charm! - http://pdf2png.cloudfoundry.com
====

Related

How can I use jsp variables in another jsp file?

I have two jsp file, one is NewFile.jsp and another is index.jsp
I want to use variables(defined in index.jsp) in NewFile.jsp.
So I put this line in "NewFile.jsp":
<%# include file = "index.jsp" %>
But page loaded HTTP Status 500 Internal Server Error and it said, :
org.apache.jasper.JasperException: 행 [13]에서 [/index.jsp]을(를) 처리하는 중 예외 발생
10: out.println("can't access");
11: }
12: else {
13: int age = Integer.parseInt(request.getParameter("age"));
14: double height = Double.parseDouble(request.getParameter("height"));
15: boolean sex = Boolean.parseBoolean(request.getParameter("female"));
16:
It said : row [13] is wrong.(It is wrote in Korean but I think you can understand.)
and I have these lines in NewFile.jsp :
function doAction(){
var req = createRequest();
if (req == null){
alert("실행이 되지 않는다!");
return ;
}
var hei = document.getElementById("height").value;
var ag = document.getElementById("age").value;
var fem = document.getElementById("female").checked;
req.open("GET", "index.jsp?female=" + encodeURI(fem) + "&age=" + encodeURI(ag) + "&height=" + encodeURI(hei));
req.setRequestHeader("User-Agent", "XMLHttpRequest");
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
var msg = document.getElementById('msg');
msg.innerHTML = this.responseText;
}
}
req.send();
}
I think it has an error while files interact in request.
And when I erase <%# include file = "index.jsp" %>, it worked well (but not use index.jsp variables in NewFile.jsp).
But I don't know how to modify it.
How can I do to use variables defined in index.jsp in NewFile.jsp?
It's not clear from the description what you are trying to do. It seems that you got a null reference at line 13. If you pass the age as a request parameter than it does not make sense at all "sharing the variables".Here's a working example which demonstrates how to share variables:
<!-- hello.jsp -->
<%
String hi = "Hello from hello.jsp";
request.setAttribute("hi", hi);
%>
<!-- index.jsp -->
<jsp:include page="hello.jsp"/>
<%=request.getAttribute("hi") %>
Keep in mind that the usage of JSP scriptlets is highly discoureged. Check this post for more in-depth details.

Flow.js and Java Servlet upload file 0 bytes

I added flow.js in my proyect following the instructions and the call to my java servlet:
localhost:8080/WebExample/UploadImgServlet?flowChunkNumber=1&flowChunkSize=1048576&flowCurrentChunkSize=693916&flowTotalSize=693916&flowIdentifier=693916-image2png&flowFilename=image2.png&flowRelativePath=image2.png&flowTotalChunks=1`
In my servlet I get all parameters of the url (flowChuckNumber, flowChuckSize, etc) but when I try to get the file (request.getInputStream()), it's empty and upload 0 bytes.
Where is the problem? Any Idea?
I found a similar question but it was with PHP...
My code:
HTML(the image is displayed):
...
...
<div flow-init="{singleFile:true}"
flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
flow-files-submitted="$flow.upload()"
flow-file-success="$file.msg = $message">
<div class="drop" flow-drop ng-class="dropClass">
<md-button class="md-raised md-primary" type="file" flow-btn>Upload Image</md-button>
<b>OR</b>
Drag And Drop your image here
</div>
<div class="thumbnail" ng-show="!$flow.files.length">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="Image"/>
</div>
<div class="thumbnail" ng-show="$flow.files.length">
<img flow-img="$flow.files[0]" />
</div>
<table>
<tr ng-repeat="file in $flow.files">
<td>{{$index+1}}</td>
<td>{{file.name}}</td>
<td>{{file.msg}}</td>
</tr>
</table>
</div>
...
...
App AngularJs:
var app = angular.module("webexample", ['ngMaterial', 'ngNotify','uiGmapgoogle-maps','flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: '/WebExample/UploadImgServlet',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 1
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}])
.directive('appDownloadUrl', [function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('dragstart', function (event) {
var config = scope.$eval(attrs.appDownloadUrl);
if (!config.disabled) {
var data = config.mime + ':' + config.name + ':' + window.location.href + config.url;
console.log("data: "+data);
event.dataTransfer.setData('DownloadURL', data);
}
});
}
};
}])
.directive("appDragstart", [function () {
return function(scope, element, attrs) {
element.bind('dragstart', function (event) {
scope.$eval(attrs.appDragstart);
});
}
}]).directive("appDragend", [function () {
return function(scope, element, attrs) {
element.bind('dragend', function (event) {
scope.$eval(attrs.appDragend);
});
}
}]).run(function ($rootScope) {
$rootScope.dropEnabled = true;
});
My Servlet (I followed this example):
protected void doService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
LOGGER.debug("[UploadImgServlet - doService] - init");
int resumableChunkNumber = getResumableChunkNumber(request);
ResumableInfo info = getResumableInfo(request);
//info contains all flow parameters of the url.
RandomAccessFile raf = new RandomAccessFile(info.resumableFilePath, "rw");
//Seek to position
raf.seek((resumableChunkNumber - 1) * info.resumableChunkSize);
//Save to file
InputStream is = request.getInputStream();
long readed = 0;
long content_length = request.getContentLength();
//**PROBLEM: request.getContentLength return -1 so read 0 bytes**
byte[] bytes = new byte[1024 * 100];
while(readed < content_length) {
int r = is.read(bytes);
if (r < 0) {
break;
}
raf.write(bytes, 0, r);
readed += r;
}
raf.close();
...
...
The input stream will be empty because flowjs posts the content using MultiPart by default.
The author of the Java code specified that "Octet" should be used for uploads, not multi-part.
UploadServlet accepts Resumable.js Upload with 'octet'
You need to add "method:octet" to your init,
<div flow-init="{singleFile:true, method:octet}"
I am using Spring, so I just used MultipartHttpServletRequest to get the posted data with MultiPart instead because MultiPart is more common.
This is how I received the contents of the file:
Iterator<String> itr = request.getFileNames();
/* Iterate each file, there should only be one/one chunk */
while (itr.hasNext()) {
fileUploaded = request.getFile(itr.next());
raf.write(fileUploaded.getBytes());
}
raf.close();
I had to do more fixes to the java code provided because it was estimating the number of chunks to receive wrong, so I just used the "flowTotalChunks" parameter.
You don't need to worry about content length. The HttpServletRequest will terminate the input stream at the correct point. Just read until end of stream.
I wanted a lib to upload images with more options and visually appealing (drop file from a folder, thumbnail, etc) than the default html input and I have not been able to do with Flowjs and Java Servlet, so I looked for another lib:
https://github.com/danialfarid/ng-file-upload
https://angular-file-upload.appspot.com/
With this lib, I found it easy to use with Java Servlet.
I don't mark this post as solved for if someone finds a way to do it with Flowjs.

How to pass user entered data in a web form and pass it into a Java Script function

I am trying to take the inputed value from here:
index.html
<form name="ytenter" action="youtbe.html" method="get">
url: <input type="text" id="url"name="url">
stop <input type="text" id="stop" name="stop">
<input type="submit" value="Submit" onclick="ytstop(this.stop)">
</form>
and take the entered value in id=url and id=stop
and run it to youtbe.html here:
<head>
<script>
(function ytstop() {
var stopPlayAt=10; // Stop play at time in seconds
var stopPlayTimer; // Reference to settimeout call
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubeIframeAPIReady = function () {
player = new YT.Player("player", {
"height": "315",
"width": "560",
"videoId": "L6cVcbkx8l8",
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
// This automatically starts the video playback when the player is loaded.
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
var time, rate, remainingTime;
clearTimeout(stopPlayTimer);
if (event.data == YT.PlayerState.PLAYING) {
time = player.getCurrentTime();
// Add .4 of a second to the time in case it's close to the current time
// (The API kept returning ~9.7 when hitting play after stopping at 10s)
if (time + .4 < stopPlayAt) {
rate = player.getPlaybackRate();
remainingTime = (stopPlayAt - time) / rate;
stopPlayTimer = setTimeout(pauseVideo, remainingTime * 1000);
}
}
}
function pauseVideo() {
player.pauseVideo();
}
})();
</script>
</head>
<body>
<div id="player">
</div>
</html>
I need to take the "stop" from the form and put it into stopPlayAt VAR at the top
Then I need to take "url" entered from the form and put it into "videoID":
Thanks for your help. Just want the end product to allow youtube link to be entered and a time to be entered and it runs it until that time entered in seconds.
I would like to refer you to the top answer on this page:
How to get the value from the GET parameters?
This enables you to get the value of the GET-parameters in the URL.

Detect java version using deployJava.js ,pops up java upgrade menu

I have a need to know the java version installed on client machine, have come up with the solution here
How to write JavaScript function to check JRE version
When I tried, got with the answer:
console.log(deployJava.getJREs());
But at the address bar, pop up menu is displayed like this
How to hide this?.
If this can not be achieved, please suggest any other idea to implement, as this can not be used,if this popup is not suppressed
I am pretty sure from recent experiments that there is no way to suppress it. For the script to detect the plug-in versions, it must invoke the plug-in itself.
After those experiments I worked to create a script that could detect a variety of things out about the Java plug-in without invoking the plug-in itself. They relied on examining the mime-types info.
This still shows a warning in IE if opened from the local file-system. But I hope it will be more forgiving if loaded from the internet. Please report back.
But note this is what it reports for IE when the 'allow scripts' check is OK'd.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java Information - Non Deployment Toolkit Script</title>
<meta name='author' content='Andrew Thompson'>
<meta name='description' content='Non Deployment Toolkit Script'>
<script src='mimetypes.js'></script>
<style type='text/css'>
.true {
background-color: #6F6;
}
.false {
background-color: #FB0;
}
.undefined {
background-color: #FF0;
}
.datum {
font-family: monospace;
}
td {
padding: 4px;
}
</style>
</head>
<body>
<h1>Java on this PC</h1>
<h2>Overview</h2>
<p>This page endeavors to ascertain the installation, availability
& version of the Java installed on the client PC.
More importantly, it attempts to discover the information <b>without
invoking the Java Plug-In</b> itself.
The last part is what makes it different
to the Deployment Toolkit Script supplied by Oracle.
</p>
<script type='text/javascript'>
document.write("<h2>Browser Info.</h2>");
document.write(getBrowserInfo());
document.write("<h2>Basic Info.</h2>");
document.write("<table border='1'>");
document.write(get3CellRow('<b>Enabled</b>', isJava(), 'Java is enabled (1.1+) - IE info. (short of ActiveX) stops here'));
document.write(get3CellRow('<b>Version</b>', getVersion(), 'Maximum version reliably <em>known</em> to be available'));
if (isIE()) {
document.write(get3CellRow('<b>MSIE</b>', getIEVersion(), 'Maximum version reliably known to be available in IE, tested using ActiveX'));
}
document.write(get3CellRow('<b>JWS</b>', isJWS(), 'Java Web Start available (1.4.2+)'));
document.write(get3CellRow('<b>Plug-In 2</b>', isPlugin2(), 'Plug-In 2 available (1.6.0_10+)'));
document.write("</table>");
if (plugins.length>0) {
document.write("<h2>Navigator Plug-Ins</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Name</th><th>Version</th><th>File Name</th><th>Description</th></tr>");
for (var ii=0; ii<plugins.length; ii++) {
var t = plugins[ii].name;
if (t.indexOf("Java")>-1) {
document.write("<tr>");
document.write("<td>" + plugins[ii].name + "</td>");
document.write(getDataStyledCell(plugins[ii].version));
document.write("<td>" + plugins[ii].filename + "</td>");
document.write("<td>" + plugins[ii].description + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
if (mimes.length>0) {
document.write("<h2>Navigator Mime-Types</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Mime</th><th>Description</th><th>Types</th></tr>");
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
((t.indexOf("jpi")>0 || t.indexOf("deploy")>0 || t.indexOf("jnlp")>0 || t.indexOf("vm")>0) ||
mimes[ii].description.length>0)
) {
document.write("<tr>");
document.write("<td>" + mimes[ii].type + "</td>");
document.write("<td>" + mimes[ii].description + "</td>");
document.write("<td>" + mimes[ii].suffixes + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
</script>
<hr>
<h2>Description</h2>
<p>In order (if available) the information is:
<ul>
<li><b>Browser info. Table:</b> Not strictly related to Java - the
information in the other tables is determined without
further reference to any information shown in this table (except for the <code>appName</code> used for
identifying IE).
OTOH it is an helpful guide
as to what we should be <em>expecting</em>
from the other information. E.G. IE
will not show the Plug-In or Mime Type tables. <em>Only</em>
FF displays the plug-in version numbers.
</li>
<li><b>Basic info. Table</b>
<ul>
<li><b>Enabled</b>: Java is known to this browser and enabled, according to JavaScript <code>navigator.javaEnabled()</code>.</li>
<li><b>Version</b>: The maximum Java version known to be supported in this browser/PC.
It is set to <code>1.1</code> if the previous check is <code>true</code>, since the MSVM
was the first Java version the public could get in a browser, and the MSVM
implemented Java 1.1. Goes on to check
<code>application/x-java-applet;jpi-version</code>
in the mime types if available
(i.e. typically browsers that are <em>not</em> IE).
</li>
<li><b>MSIE</b> (IE Only): The maximum Java version known to be supported by this instance of Internet Explorer
as determined using ActiveX. It runs from 1.4.2, 1.5.0.. through 1.9.0.
</li>
<li><b>JWS</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was co-bundled.</li>
<li><b>Plug-In 2</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was introduced.</li>
</ul>
</li>
<li><b>Navigator Object Tables:</b>
<em>The rest of the info. is gleaned from the <code>navigator</code> object.
IE does not include this information.</em>
<ul>
<li><b>Plug-Ins</b>: More details of the Java related plugins.
Filtered for <code>Java</code> in the <code>name</code>.
A <code>description</code> showing "Next Generation Java Plug-in" or <code>name</code>
"Java Deployment Toolkit" should be 1.6.0_10+.</li>
<li><b>Mime-Types</b>: More information on the Java related Mime-Types.
Filtered in <code>mime</code> field for <code>'java'</code> + <code>('jpi'||'vm'||'deploy')</code>
or a non-empty <code>description</code>.
The value <code>java-deployment-toolkit</code> in the <code>mime</code>
is a good indicator of 1.6.0_10+.
</li>
</ul>
</li>
</ul>
</body>
</html>
mimetypes.js
// As a version string, this might be '1.4.2_31'.
// I.E. it is not a 'number' but a 'string' and therefore must be treated as a string.
var highestVersion = 'undefined';
var mimes = window.navigator.mimeTypes;
var plugins = window.navigator.plugins;
function isJava() {
return (
typeof(navigator.javaEnabled) !== 'undefined' &&
navigator.javaEnabled());
}
function getVersion() {
var version = 0;
if (isJava()) {
version = 1.1;
}
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
t.indexOf("jpi")>0 &&
t.indexOf("applet")>0
) {
var parts = t.split("=");
version = parts[parts.length-1];
}
}
if (highestVersion=='undefined') highestVersion = version;
return version;
}
function isJWS() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.4.2') {
className = true;
}
return className;
}
function isPlugin2() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.6.0_10') {
className = true;
}
return className;
}
var versionFamily = [
'1.9.0', '1.8.0', '1.7.0',
'1.6.0', '1.5.0', '1.4.2'
];
function getIEVersion() {
for (var i=0; i<versionFamily.length; i++) {
if (testUsingActiveX(versionFamily[i])) {
return versionFamily[i];
}
}
return false;
}
if (isIE() && getVersion()=='1.1') {
highestVersion = getIEVersion();
}
function isIE() {
return navigator.appName=='Microsoft Internet Explorer';
}
function testUsingActiveX(version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
// we need the typeof check here for this to run on FF/Chrome
// the check needs to be in place here - cannot even pass ActiveXObject
// as arg to another function
if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
alert('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
}
function get3CellRow(cell1, cell2, cell3) {
var s = "" +
"<tr>" +
"<td class='" +
getClassName(cell1) +
"'>" +
cell1 +
"</td>" +
getDataStyledCell(cell2) +
"<td class='" +
getClassName(cell3) +
"'>" +
cell3 +
"</td>" +
"</tr>" +
"";
return s;
}
function getDataStyledCell(value) {
var s = "<td class='datum " +
getClassName(value) +
"'>" +
value +
"</td>";
return s;
}
function getClassName(val) {
var className = undefined;
if (
(val) ||
(!val) ||
(val!=="undefined")
) {
className = val;
}
return className;
}
function getBrowserInfo() {
var s = "";
var props = [
'appCodeName','appName','appVersion',
'userAgent',
'platform','cookieEnabled'
];
s += "<table border='1'>";
for (var i=0; i<props.length; i++) {
s+= "<tr>";
s+= "<td><b>";
s+= props[i];
s+= "</b></td>";
s+= "<td>";
s+= navigator[props[i]];
s+= "</td>";
s+= "</tr>";
}
s += "</table>";
return s;
}
Please note (be warned) this script was written by me, a Java programmer. Java programmers are typically the absolute worst people on the planet for writing JS, since we foolishly tend to presume. "It's JavaScript, how hard can it be?".
To write really good JavaScript is indeed an art.
Even worse, this was experimental code that was 'hacked out' with the intention of improving it later, but the project was abandoned and 'later' never arrived.
Caveat emptor.

JAVA Applet Loading Issue

We have developed an applet in JAVA which is mainly used for accessing Digital Certificate from keystore.
The applet works fine in most of the cases, but in some secure networks of banks the applet behaviour becomes unpredictable.
We are using applet tag in HTML to access applet.
My first question is do we need to deploy using JNLP for this?
Secondly, I prepared one test application in past where by I was simply calling one method of applet, which was loading all the certificate public details and printing it on console. It used to work perfectly ok.
Following is the code for the same.
Applet Method
public void init() {
printMessageToConsole("Applet Initialized Version : " + appletVersion);
browserName = "Internet Explorer";
try {
String osName = System.getProperty("os.name");
printMessageToConsole("Operating system name =>" + osName);
} catch (Exception e) {
printMessageToConsole("Error in Get OS Init.");
e.printStackTrace();
}
}
public List<String> getCertificateAllDetails() throws NoSuchFieldException,
SecurityException, IllegalArgumentException,
IllegalAccessException, NoSuchMethodException,
InvocationTargetException {
printMessageToConsole("Get All Certificate Details");
String certString = "";
int count =0;
String pubKey = "";
KeyStore browserKeyStore = null;
String certDetails = "";
browserKeyStore = initializeBrowserKeyStore();
List<String> resultValues = new ArrayList<String>();
String aliasnew = null;
printMessageToConsole(browserName);
if (browserKeyStore != null) {
printMessageToConsole("INSIDE IE CERTIFICATE READING");
Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi");
spiField.setAccessible(true);
KeyStoreSpi spi = (KeyStoreSpi) spiField.get(browserKeyStore);
Field entriesField = spi.getClass().getSuperclass().getDeclaredField("entries");
entriesField.setAccessible(true);
#SuppressWarnings("rawtypes")
Collection entries = (Collection) entriesField.get(spi);
resultValues.add("Total Certificates in Browser : " + entries.size() + "<br><br><br>");
printMessageToConsole("Total Certificates in Browser : " + entries.size());
for (Object entry : entries) {
aliasnew = (String) invokeGetter(entry, "getAlias");
PrivateKey privateKey = (PrivateKey) invokeGetter(entry,"getPrivateKey");
X509Certificate[] certificateChain = (X509Certificate[]) invokeGetter(entry, "getCertificateChain");
for (X509Certificate current : certificateChain) {
certString = "";
if (certDetails != null && getkeyUsage(current.getKeyUsage()) != "") {
count ++;
pubKey = this.bASE64Encoder.encode(current.getPublicKey().getEncoded());
certDetails = getX509CertificateDetails(current);
Map<String, String> valueMap = new HashMap<String, String>();
valueMap = getMetadata(certDetails);
certString += "====================== Certificate Details for Certificate No : " + count + "======================<br>";
certString += "Alias : " + aliasnew + " <br>";
certString += "Name : "+ valueMap.get(CERT_DETAILS.NAME) + " <br>";
certString += "Key Usage : " + getkeyUsage(current.getKeyUsage()) + "<br>";
certString += "CNName : "+ valueMap.get(CERT_DETAILS.CN_NAME) + "<br>";
printMessageToConsole(certString);
resultValues.add(certString);
break;
} else {
printMessageToConsole("Cert Details is NULL");
}
}
}
}
else {
printMessageToConsole("Keystore is NULL");
}
return resultValues;
}
HTML Page
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<SCRIPT LANGUAGE="JavaScript">
function getAllCertificates()
{
document.write("Certificate Reading Started.")
var certificates = document.securityApplet.getCertificateAllDetails();
document.write(certificates);
}
</SCRIPT>
<body>
<div>Digital Certificate Test Application</div>
<script src="http://www.java.com/js/deployJava.js"></script>
<applet name="securityApplet" code="SecurityApplet.class"
archive="securityApplet.jar" width="0" height="0" MAYSCRIPT="true"
scriptable="true" > </applet>
<button type="button" onclick="getAllCertificates()">Load Certificates!</button>
</body>
I recently opened up this page and now in my local network the applet is getting initialised properly but then it is unable to call anything further on click of button.
Console Output on loading of page.
Applet Initialized Version : 30
Operating system name =>Windows 7
basic: Applet initialized
basic: Starting applet
basic: completed perf rollup
basic: Applet made visible
basic: Applet started
basic: Told clients applet is started
Everything is ok till above on loading
When I click on Load Certificate Button, following is the console log and then nothing happens. And in the secured network the last two line even does not come.
basic: Starting applet teardown
basic: Finished applet teardown
basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter#1b9bbe8
plugin2manager.parentwindowDispose
Following is the console output, where it goes in loop.
Looking forward for an answer on the same. Thanks in Advance.
I have found out the problem.
There is nothing to do JNLP here.
The only problem is I have done document.write which is blocking and getting applet to dispose.
I have removed the document.write from HTML and with following HTML the code works completely ok.
<html>
<head>
<title> Digital Certificate Test Application </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script src="http://www.java.com/js/deployJava.js"></script>
<applet name="securityApplet" code="SecurityApplet.class"
archive="securityApplet.jar" width="0" height="0" MAYSCRIPT="true"
scriptable="true" > </applet>
<SCRIPT LANGUAGE="JavaScript">
function getAllCertificates()
{
alert("Certificate Reading Started");
var certificates = document.securityApplet.getCertificateAllDetails();
document.getElementById("displaymessage").innerHTML = certificates;
}
</SCRIPT>
<body>
<div>Digital Certificate Test Application</div>
<div id="displaymessage">
</div>
<button type="button" onclick="getAllCertificates()">Load Certificates!</button>
</body>

Categories