program data randomizes only when run with break point - database

i have a program that generates a 2 question test from an SQL DB by question and by answers, the questions are selected randomly by a question id. the problem I'm having is when run normally from net beans the the questions don't randomize in fact on a new system that hasn't run before it doesn't show any questions. but when it is debugged with break points it works perfectly fine. i had something like this happen to another program a while ago and not sure how i fixed it, i believe it was an issue between caching and the math Random.
welcome page load to the quizzical controller which on init generates a test in TestDA servlet
package org.citatscc.quiz.controller;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.citatscc.quiz.business.*;
import org.citatscc.quiz.business.TestTaker;
import org.citatscc.quiz.data.TestDA;
public class Quizzical extends HttpServlet {
//the test will be available to all threads
//eventually each TestTaker will store their Test in a Session
private Test myQuiz=null;
#Override
public void init(){
String testName = getServletConfig().getInitParameter("QuizName");
//generate the basic Test which will be used to create each TestTaker's myQuiz
myQuiz = TestDA.generateTest(testName);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("myQuiz", myQuiz);
//here we are simply showing the test generated from the database
String action = request.getParameter("action");
String url = "/QuizView.jsp";
if(action == null)
{
url = "/QuizMain.jsp";
}
else if(action.equals("AddTest"))
{
url = "/QuizAdd.jsp";
}
else if(action.equals("addNewTest"))
{
addNewTest(request);
}
RequestDispatcher dispatch = getServletContext().getRequestDispatcher(url);
dispatch.forward(request, response);
}
public boolean addNewTest(HttpServletRequest request)
{
return false;
}
// <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
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
TestDA
package org.citatscc.quiz.data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.citatscc.quiz.business.Question;
import org.citatscc.quiz.business.Test;
public class TestDA{
public static Test generateTest(String testName) {
List<Question> questions = new ArrayList<Question>();
Test test = null;
boolean sameNum = true;
int randNum1 = 0;
int randNum2 = 0;
while(sameNum == true)
{
randNum1 = getRandomNumber();
randNum2 = getRandomNumber();
if(randNum1 == 0 || randNum2 == 0 || randNum1 > 7 || randNum2 > 7 ||
randNum1 == 6 || randNum2 == 6)
{
sameNum = true;
}
else
{
if(randNum1 != randNum2)
{
sameNum = false;
}
}
}
String questionID1 = getQuestionID(randNum1);
String questionID2 = getQuestionID(randNum2);
try {
String questionTxt1 = getQuestionStringByQID(questionID1);
String questionTxt2 = getQuestionStringByQID(questionID2);
questions.add(getAnswers(questionTxt1, questionID1));
questions.add(getAnswers(questionTxt2, questionID2));
test = new Test(testName,questions);
} catch (Exception ex) {
String message = ex.getMessage();
}
return test;
}
public static Question getAnswers(String questionTxt, String questionID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
int counter = 0;
int correctAnswer = 0;
ArrayList<String> answers = new ArrayList<String>();
String preparedQuery = "SELECT * FROM `answers` WHERE `qID` = " + questionID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
while (resultSet.next())
{
answers.add(resultSet.getString(2));
if(resultSet.getInt(3) == 1)
{
correctAnswer = counter;
}
else
{
counter++;
}
}
Question question = new Question(questionTxt, answers, correctAnswer);
return question;
}
public static String getQuestionStringByQID(String qID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
String preparedQuery = "SELECT `question` FROM `questions` WHERE `qID` = " + qID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
String questionText = "";
while (resultSet.next())
{
questionText = resultSet.getString(1);
}
connection.close();
return questionText;
}
public static int getRandomNumber()
{
Random rnd = new Random();
int randomNum = rnd.nextInt(8);
return randomNum;
}
public static String getQuestionID(int randNum)
{
int intqID = randNum * 111;
String qID = "" + intqID;
return qID;
}
public static void insertQuestion(String qID, String qText, List<String>qChoices, int correct)throws SQLException{
String preparedQuestion = "INSERT INTO questions VALUES(?,?)";
}
public static void upDateQuestion(String qID, String qText, List<String>qChoices, int correct) throws SQLException{
}
}
after init is finished it redirects to a menu jsp, after a link to take a test is clicked it hits the quizzical controller before being redirected to QuizView.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Quiz View</title>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="cit" uri="/WEB-INF/tld/test.tld" %>
<%#taglib prefix="includes" tagdir="/WEB-INF/tags/" %>
<%# page import="org.citatscc.quiz.business.Test, org.citatscc.quiz.business.Question" %>
<%# page import="java.util.*" %>
<link href="quiz.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="top"><includes:Header image="cit_logo.jpg" alt="cit logo image" tagline="${myQuiz.testName}"/></div>
<div id="leftnav">
</div>
<div id="content">
<form action="Quiz" method="post">
<c:forEach var="question" items="${myQuiz.questionList}" varStatus="qCount">
<h2>${qCount.count}. ${question.questionText} </h2>
<c:forEach var="choice" items="${question.choices}" varStatus="choiceCount" >
<!-- custom tag here -->
<cit:quiz_choiceButton groupName="choice${qCount.count}" text="${choice}" value="${choiceCount.index}" />
</c:forEach>
<br />
</c:forEach>
<input type="submit" name="done" value="Submit" />
</form>
</div>
<div id="footer"><includes:Footer /></div>
</div>
</body>
</html>
any help is appreciated.

The servlet method init() is called once during servlet initialisation. So, you have the same Test for all your following requests.
private Test myQuiz=null;
has the same value for all requests.
More in docs: http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)

Related

Data from array is not getting displayed on JSP page its is printing on console though?

I am working on a Spring project in eclipse. Here I'm taking data from the user and storing it in an array. I want the data stored in an array to display on a JSP page. I have used MVC, but the data is not displaying. When I run the project and call the url for JSP page the array gets displayed in the console but not on the webpage.
console output:
JSP Output:
Controller class
#Controller
public class WebController {
#Autowired
public StoreService service;
List<Store> allStore=new ArrayList<Store>();
#GetMapping( value = "/")
public String home()
{
return "index";
}
#RequestMapping(value="/addstore", method=RequestMethod.GET)
String addStore(#ModelAttribute("store") Store s)
{
System.out.println("Display add store details page");
return "addStore";
}
#RequestMapping(value="/saveStore", method=RequestMethod.POST)
public String addinStore(#ModelAttribute("store") Store s) {
service.saveStore(s);
System.out.println(s);
return "redirect:/";
}
#RequestMapping(value="/viewStore",method=RequestMethod.GET)
public ModelAndView listallStore()
{
allStore=service.showAllStore();
System.out.println(allStore);
return new ModelAndView("listStore","Yves",allStore);
}
JSP page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="dd" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 style="padding-left: 45%; ">Store Details</h1>
<Table class="user-detail">
<thead>
<tr>
<th>Store Name</th>
<th>Store Contact Number</th>
<th>Store Address</th>
</tr>
</thead>
<tbody>
<dd:forEach var="lone" items="${Yves}">
<tr><td>${lone.name}</td><td>${lone.contactNumber}</td><td>${lone.localities}</td></tr>
</dd:forEach>
</tbody>
</Table>
</body>
</html>
Service
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class StoreService {
#Autowired
private StoreDAO sd;
public Store saveStore(Store s) {
return sd.saveStore(s);
}
public List<Store> showAllStore(){
return sd.showAllStore();
}
}
DAO
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class StoreDAO {
List<Store> store = new ArrayList<Store>();
public Store saveStore(Store s) {
store.add(s);
return s;
}
public List<Store> showAllStore(){
return store;
}
}
Bean/Model
import java.util.Arrays;
public class Store {
String name;
String contactNumber;
String[] localities;
public Store() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String[] getLocalities() {
return localities;
}
public void setLocalities(String[] localities) {
this.localities = localities;
}
public Store(String name, String contactNumber, String[] localities) {
super();
this.name = name;
this.contactNumber = contactNumber;
this.localities = localities;
}
#Override
public String toString() {
return "Store [name=" + name + ", contactNumber=" + contactNumber + ", localities="
+ Arrays.toString(localities) + "]";
}
}

Using OkHttp client via OKClient on Google App Engine throws a "java.lang.NoClassDefFoundError: java.net.ProxySelector" is a restricted class error

I am trying to use OKHTTP (version 2.4.0) along retrofit (1.9.0) on google app engine (1.9.22).
Here is the how i use it:
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(COMPOSER_MODULE_CONNECTION_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(COMPOSER_MODULE_SOCKET_TIMEOUT, TimeUnit.SECONDS);
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new JacksonConverter())
.setEndpoint(ENDPOINT_PATH)
.setClient(new OkClient(okHttpClient))
.build();
This throws the following error:
java.lang.NoClassDefFoundError: java.net.ProxySelector is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.apphosting.runtime.security.shared.stub.java.net.ProxySelector.<clinit>(ProxySelector.java)
at com.squareup.okhttp.OkHttpClient.copyWithDefaults(OkHttpClient.java:614)
at com.squareup.okhttp.Call.<init>(Call.java:50)
at com.squareup.okhttp.OkHttpClient.newCall(OkHttpClient.java:595)
at retrofit.client.OkClient.execute(OkClient.java:53)
I gather from the error that "java.net.ProxySelector" is not white-listed for use on google appengine.
Question 1)
Is it possible to use OKHTTP (version 2.4.0) along retrofit (1.9.0) on google app engine (1.9.22)? i.e, is there a work around for this error
if not,
Question 2)
Are there any other way to:
(a) use async HTTP calls with google appengine (with URLFetchService, for instance) ?
(b) set connection and socket timeouts for the client used from (a) ?
The links i have come across via search:
(1) Retrofit timeout configuration for clients
(2) Google App Engine URL Fetch Java API
You can use HttpUrlConnection with Retrofit2 to use it in Google APP Engine
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
public class RetrofitCall implements Call {
Request request;
RetrofitCall(Request request) {
this.request = request;
}
#Override
public Request request() {
return request;
}
#Override
public Response execute() throws IOException {
URL url = request.url().url();
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestMethod(request.method());
Headers headers = request.headers();
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
String name = headers.name(i);
connection.setRequestProperty(name, headers.get(name));
}
}
if (request.body() != null) {
BufferedSink outbuf;
outbuf = Okio.buffer(Okio.sink(connection.getOutputStream()));
request.body().writeTo(outbuf);
outbuf.close();
}
connection.connect();
final BufferedSource source = Okio.buffer(Okio.source(connection.getInputStream()));
if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
throw new IOException("Fail to call " + " :: " + source.readUtf8());
}
Response response = new Response.Builder()
.code(connection.getResponseCode())
.message(connection.getResponseMessage())
.request(request)
.protocol(Protocol.HTTP_1_1)
.body(new ResponseBody() {
#Override
public MediaType contentType() {
return MediaType.parse(connection.getContentType());
}
#Override
public long contentLength() {
return connection.getContentLengthLong();
}
#Override
public BufferedSource source() {
return source;
}
})
.build();
return response;
}
#Override
public void enqueue(Callback responseCallback) {
}
#Override
public void cancel() {
}
#Override
public boolean isExecuted() {
return false;
}
#Override
public boolean isCanceled() {
return false;
}
public static class Factory implements Call.Factory {
#Override
public Call newCall(Request request) {
return new RetrofitCall(request);
}
}
}
You can use the following code snippet to run Retorifit2 with GAE limitations. It contains a lot of debugging stuffs free to remove in production and does not implement real async call.
okhttp3.Call.Factory gaeCallFactory = new okhttp3.Call.Factory() {
#Override
public okhttp3.Call newCall(final Request request) {
final URL url = request.url().url();
final String method = url.toString();
return new okhttp3.Call() {
#Override
public Request request() {
return request;
}
#Override
public Response execute() throws IOException {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
if (request.body() != null) {
//TODO ajust for different needs
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
BufferedSink outbuf;
ByteArrayOutputStream out = new ByteArrayOutputStream();
outbuf = Okio.buffer(Okio.sink(out));
request.body().writeTo(outbuf);
outbuf.close();
logger.info("Calling " + method + "\n" + new String(out.toByteArray()));
outbuf = Okio.buffer(Okio.sink(connection.getOutputStream()));
request.body().writeTo(outbuf);
outbuf.close();
} else {
logger.info("Calling " + method);
}
final BufferedSource source = Okio.buffer(Okio.source(connection.getInputStream()));
if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
throw new IOException("Fail to call " + method + " :: " + source.readUtf8());
}
Response response = new Response.Builder()
.code(connection.getResponseCode())
.message(connection.getResponseMessage())
.request(request)
.protocol(Protocol.HTTP_1_1)
.body(new ResponseBody() {
#Override
public MediaType contentType() {
return MediaType.parse(connection.getContentType());
}
#Override
public long contentLength() {
return connection.getContentLengthLong();
}
#Override
public BufferedSource source() {
return source;
}
})
.build();
logger.info("Call response code: " + response.code() + " message: " + response.message());
return response;
}
#Override
public void enqueue(Callback responseCallback) {
try {
responseCallback.onResponse(this, execute());
} catch (IOException e) {
responseCallback.onFailure(this, e);
}
}
#Override
public void cancel() {
}
#Override
public boolean isExecuted() {
return false;
}
#Override
public boolean isCanceled() {
return false;
}
};
}
};
Retrofit retrofit = new Retrofit.Builder()
.callFactory(gaeCallFactory)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ENDPOINT_URI)
.build();
You need to use the Appengine URLFetchClient instead of the OkHttpClient. Like this:
import retrofit.appengine.UrlFetchClient;
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new JacksonConverter())
.setEndpoint(ENDPOINT_PATH)
.setClient(new UrlFetchClient())
.build();
Please note this only works with Retrofit1, this will not work with Retrofit2 because it's coupled directly to OkHttp as explained by Jake Wharton here

How to load the files displayed in a Kendo treeview

I need to display the files & folders hierarchically in a Kendo UI treeview which gets loaded from the file system using Java on the back end. I also need to load the contents of the files when they are clicked.
Can anyone suggest how to accomplish this?
I accomplished loading the hierarchy structure by creating two java files.
I got some folders and files inside D:/sampleFileExplorer.Using java file Api we read the file and subdirectories structure and put it inside the ArrayList of Type .In TestJava.java getFileExplorer(folder,finalList) is the method which construct the Arraylist and return it.you need to call this method from Kendo jsp and we get the result as json format.
FileExplorer.java
import java.util.ArrayList;
import java.util.List;
public class FileExplorer {
private String id;
private String text;
private boolean hasFiles;
private List<FileExplorer> items = new ArrayList<FileExplorer>();
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public List<FileExplorer> getItems() {
return this.items;
}
public void setItems(List<FileExplorer> items) {
this.items = items;
}
public boolean isHasFiles() {
return this.hasFiles;
}
public void setHasFiles(boolean hasFiles) {
this.hasFiles = hasFiles;
}
}
TestJava.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class TestJava {
public static void main(String[] args) {
TestJava t=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
t.getFileExplorer(folder,finalList);
t.displayFileExplorer(folder,finalList);
}
public List<FileExplorer> getFileExplorer(File folder,List<FileExplorer> finalList){
finalList = getFileOrDirectoryList(folder,finalList);
return finalList;
}
public void displayFileExplorer(File folder,List<FileExplorer> finalList){
finalList = getFileOrDirectoryList(folder,finalList);
for(FileExplorer file : finalList){
System.out.println(file.getId()+" "+file.getText()+" "+file.getItems().size()+" ");
displaySubLevels(file.getItems());
}
}
public void displaySubLevels(List<FileExplorer> subList){ //display subdirectory's content
if(subList != null){
for(FileExplorer subFile : subList){
System.out.println(subFile.getId()+" "+subFile.getText()+" "+subFile.getItems().size()+" ");
if(subFile.getItems().size()>0){
displaySubLevels(subFile.getItems());
}
}
}
}
public List<FileExplorer> getFileOrDirectoryList(File folder, List<FileExplorer> fileList){
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if(file.isDirectory()){
FileExplorer d1 = new FileExplorer();
d1.setId(file.getPath());
d1.setText(file.getName());
if(file.list().length>0)
{
d1.setHasFiles(true);
}
else
{
d1.setHasFiles(false);
}
File folder1 = new File(d1.getId());
List<FileExplorer> subList = new ArrayList<FileExplorer>();
subList = getFileOrDirectoryList(folder1, subList);
d1.setItems(subList);
fileList.add(d1);
}else{
FileExplorer f1 = new FileExplorer();
f1.setId(file.getPath());
f1.setText(file.getName());
f1.setHasFiles(false);
fileList.add(f1);
}
}
return fileList;
}
}
hello.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5.1">
<html>
<head>
<title></title>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value="/resources/styles/kendo.common.min.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/styles/kendo.default.min.css"/>" rel="stylesheet"/>
<script src="<c:url value="/resources/js/jquery.min.js"/>"></script>
<script src="<c:url value="/resources/js/kendo.all.min.js"/>"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="example" class="k-content">
<div id="treeview" class="demo-section"></div>
<script>
(function($) {
var homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: '<c:url value="/welcome/list/"/>',
dataType: "json"
}
},
schema: {
model: {
hasChildren: "hasFiles",
children: "items"
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous
,
dataTextField: "text"
});
})(jQuery);
</script>
</div>
<div>
</div>
</body>
</html>
My Spring Controller
HelloWorld.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/welcome/")
public class HelloWorld {
#RequestMapping(value = { "fileExplorer/"}, method = RequestMethod.GET )// , produces = "application/json")
public String readScenarioDateSetup(#ModelAttribute("userId")String userId,BindingResult result,Model model)throws Exception{
TestJava remote=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
Iterable<FileExplorer> fileExp= remote.getFileExplorer(folder,finalList);
model.addAttribute("fileExp",fileExp);
return "hello";
}
#RequestMapping(value = {"/list/"}, method = RequestMethod.GET )
public #ResponseBody Iterable<FileExplorer> readScenarioDateSetup()throws Exception{
TestJava remote=new TestJava();
List<FileExplorer> finalList = new ArrayList<FileExplorer>();
File folder = new File("D:/SampleFileExplorer");
Iterable<FileExplorer> fileExp= remote.getFileExplorer(folder,finalList);
return fileExp;
}
}
After Deployed into your server ..Type url
http://://welcome/fileExplorer/ you get the result..
There may be better ways to achieve this but this is how I achieved this.

Failed to a create file through Tomcat

I made a certificate generation software.
However, it can't save files sucessfully.
I mean that the code in the 'RootCertGenerator.java' should generate a 'rootCertificate.cer' file. which is successfully work on pure java.
But when I run 'generateRootCert.jsp' on tomcat it it fails to generate the file
please help me
--generateRootCert.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR"%>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.PreparedStatement" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="myPackage.Utils" %>
<%# page import="myPackage.RootCertGenerator" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Make root Certificate</title>
</head>
<%
RootCertGenerator.execute();
%>
<body>
</body>
</html>
--RootCertGenerator.java
package myPackage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V1CertificateGenerator;
//add 20130424
//import org.bouncycastle.jce.provider.BouncyCastleProvider;
//add 20130427
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
/**
* Basic X.509 V1 Certificate creation.
*/
public class RootCertGenerator
{
public static X509Certificate generateV1Certificate(KeyPair pair)
throws InvalidKeyException, NoSuchProviderException, SignatureException
{
//add 20130424
//Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// generate the certificate
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000))); //1 week
certGen.setNotAfter(new Date(System.currentTimeMillis() + (7 * 24 * 60 * 60 * 1000)));
certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
//return certGen.generateX509Certificate(pair.getPrivate(), "BC");
return certGen.generateX509Certificate(pair.getPrivate());
}
//////////added by jeon
public static void pemEncodeToFile(String filename, Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new FileWriter(filename));
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
pw.flush();
pw.close();
}
//////////add 20130427
public static String pemEncodeToString(Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new StringWriter(1));
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
String str=null;
pw.write(str);
return str;
//pw.flush();
//pw.close();
}
//////////add 20130427
public static void rootCertUpdate(String rootCert)
{
String sql = "update testca.testca_init set certificate = '"+rootCert+"' where user_id='root'";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
//PreparedStatement pstmt = null;
Statement stmt = null;
//ResultSet rs = null;
String jdbcDriver = "jdbc:mysql://localhost:3306/";
String dbUser = "root";
String dbPass = "forgetmenot";
try{
conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
}catch(Exception ex){System.out.println("Error 2: " +ex);}
}
//////////added by jeon
public static void execute()
throws Exception
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// create the keys
KeyPair pair = Utils.generateRSAKeyPair();
////private key
PrivateKey key = (PrivateKey)pair.getPrivate();
// generate the certificate
X509Certificate cert = generateV1Certificate(pair);
byte[] a = cert.getEncoded();
//System.out.println(a);
//System.out.println(cert);
////////////////////writing root certificate
PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
pemWrt.writeObject(cert);
pemEncodeToFile("rootCertificate.cer", cert, null);
//20130428
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
System.out.println(cert);
//System.out.flush();
pemWrt.flush();
System.setOut(old);
System.out.println("Here: " + baos.toString());
pemWrt.close();
rootCertUpdate(baos.toString());
// show some basic validation
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
System.out.println("valid certificate generated");
}
}
You should not only provide the filename of the certificate (rootCertificate.cer), but also the full path where it should be created if you use this class within Tomcat.
You can edit the following line. Instead
pemEncodeToFile("rootCertificate.cer", cert, null);
write something like
pemEncodeToFile("C:/servers/rootCertificate.cer", cert, null);
or
pemEncodeToFile("C:\\servers\\rootCertificate.cer", cert, null);
The file should be created in the mentioned path. Make sure that the folder (in this example "servers") already exists. You could also enhance your method signature by the filename and edit the filename in the JSP.

popupPanel not show in rich:dataTable

Base on the sample from:
http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=dataTable&sample=dataTableEdit&skin=blueSky
I did a bit modify on the xhtml page and CarBean to include a button to display the result. Result display as expected but the popup panel not working (ie. no popup).
Software version I use:
richface 4.3.0 Final
GAE 1.7.2
Note: It work fine on my local notebook and problem mention above apply when deploy online.
Here the online url
http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
Any help?
[CarsBean.java]
package test.faces.bean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.richfaces.demo.common.data.RandomHelper;
import org.richfaces.demo.tables.model.cars.InventoryItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorList;
#ManagedBean(name = "carsBean2")
#SessionScoped
public class CarsBean2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3832235132261771583L;
private static final int DECIMALS = 1;
private static final int CLIENT_ROWS_IN_AJAX_MODE = 15;
private static final int ROUNDING_MODE = BigDecimal.ROUND_HALF_UP;
private List<InventoryItem> allInventoryItems = null;
private List<InventoryVendorList> inventoryVendorLists = null;
private int currentCarIndex;
private InventoryItem editedCar;
private int page = 1;
private int clientRows;
public void switchAjaxLoading(ValueChangeEvent event) {
this.clientRows = (Boolean) event.getNewValue() ? CLIENT_ROWS_IN_AJAX_MODE : 0;
}
public void remove() {
allInventoryItems.remove(allInventoryItems.get(currentCarIndex));
}
public void store() {
allInventoryItems.set(currentCarIndex, editedCar);
}
public List<SelectItem> getVendorOptions() {
List<SelectItem> result = new ArrayList<SelectItem>();
result.add(new SelectItem("", ""));
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(new SelectItem(vendorList.getVendor()));
}
return result;
}
public List<String> getAllVendors() {
List<String> result = new ArrayList<String>();
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(vendorList.getVendor());
}
return result;
}
public List<InventoryVendorList> getInventoryVendorLists() {
synchronized (this) {
if (inventoryVendorLists == null) {
inventoryVendorLists = new ArrayList<InventoryVendorList>();
List<InventoryItem> inventoryItems = getAllInventoryItems();
Collections.sort(inventoryItems, new Comparator<InventoryItem>() {
public int compare(InventoryItem o1, InventoryItem o2) {
return o1.getVendor().compareTo(o2.getVendor());
}
});
Iterator<InventoryItem> iterator = inventoryItems.iterator();
InventoryVendorList vendorList = new InventoryVendorList();
vendorList.setVendor(inventoryItems.get(0).getVendor());
while (iterator.hasNext()) {
InventoryItem item = iterator.next();
InventoryVendorItem newItem = new InventoryVendorItem();
itemToVendorItem(item, newItem);
if (!item.getVendor().equals(vendorList.getVendor())) {
inventoryVendorLists.add(vendorList);
vendorList = new InventoryVendorList();
vendorList.setVendor(item.getVendor());
}
vendorList.getVendorItems().add(newItem);
}
inventoryVendorLists.add(vendorList);
}
}
return inventoryVendorLists;
}
private void itemToVendorItem(InventoryItem item, InventoryVendorItem newItem) {
newItem.setActivity(item.getActivity());
newItem.setChangePrice(item.getChangePrice());
newItem.setChangeSearches(item.getChangeSearches());
newItem.setDaysLive(item.getDaysLive());
newItem.setExposure(item.getExposure());
newItem.setInquiries(item.getInquiries());
newItem.setMileage(item.getMileage());
newItem.setMileageMarket(item.getMileageMarket());
newItem.setModel(item.getModel());
newItem.setPrice(item.getPrice());
newItem.setPriceMarket(item.getPriceMarket());
newItem.setPrinted(item.getPrinted());
newItem.setStock(item.getStock());
newItem.setVin(item.getVin());
}
public String queryRec(){
String result = "";
synchronized (this) {
getAllInventoryItems();
}
return result;
}
public String initQuery(){
String result = "";
synchronized (this) {
allInventoryItems = null;
}
return result;
}
public List<InventoryItem> getInventoryItems() {
return allInventoryItems;
}
public List<InventoryItem> getAllInventoryItems() {
synchronized (this) {
if (allInventoryItems == null) {
allInventoryItems = new ArrayList<InventoryItem>();
for (int k = 0; k <= 5; k++) {
try {
switch (k) {
case 0:
allInventoryItems.addAll(createCar("Chevrolet", "Corvette", 5));
allInventoryItems.addAll(createCar("Chevrolet", "Malibu", 8));
allInventoryItems.addAll(createCar("Chevrolet", "Tahoe", 6));
break;
case 1:
allInventoryItems.addAll(createCar("Ford", "Taurus", 12));
allInventoryItems.addAll(createCar("Ford", "Explorer", 11));
break;
case 2:
allInventoryItems.addAll(createCar("Nissan", "Maxima", 9));
allInventoryItems.addAll(createCar("Nissan", "Frontier", 6));
break;
case 3:
allInventoryItems.addAll(createCar("Toyota", "4-Runner", 7));
allInventoryItems.addAll(createCar("Toyota", "Camry", 15));
allInventoryItems.addAll(createCar("Toyota", "Avalon", 13));
break;
case 4:
allInventoryItems.addAll(createCar("GMC", "Sierra", 8));
allInventoryItems.addAll(createCar("GMC", "Yukon", 10));
break;
case 5:
allInventoryItems.addAll(createCar("Infiniti", "G35", 6));
allInventoryItems.addAll(createCar("Infiniti", "EX35", 5));
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return allInventoryItems;
}
public List<InventoryItem> createCar(String vendor, String model, int count) {
ArrayList<InventoryItem> iiList = null;
try {
int arrayCount = count;
InventoryItem[] demoInventoryItemArrays = new InventoryItem[arrayCount];
for (int j = 0; j < demoInventoryItemArrays.length; j++) {
InventoryItem ii = new InventoryItem();
ii.setVendor(vendor);
ii.setModel(model);
ii.setStock(RandomHelper.randomstring(6, 7));
ii.setVin(RandomHelper.randomstring(17, 17));
ii.setMileage(new BigDecimal(RandomHelper.rand(5000, 80000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setMileageMarket(new BigDecimal(RandomHelper.rand(25000, 45000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrice(new Integer(RandomHelper.rand(15000, 55000)));
ii.setPriceMarket(new BigDecimal(RandomHelper.rand(15000, 55000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setDaysLive(RandomHelper.rand(1, 90));
ii.setChangeSearches(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setChangePrice(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setExposure(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setActivity(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrinted(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setInquiries(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
demoInventoryItemArrays[j] = ii;
}
iiList = new ArrayList<InventoryItem>(Arrays.asList(demoInventoryItemArrays));
} catch (Exception e) {
e.printStackTrace();
}
return iiList;
}
public int getCurrentCarIndex() {
return currentCarIndex;
}
public void setCurrentCarIndex(int currentCarIndex) {
this.currentCarIndex = currentCarIndex;
}
public InventoryItem getEditedCar() {
return editedCar;
}
public void setEditedCar(InventoryItem editedCar) {
this.editedCar = editedCar;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getClientRows() {
return clientRows;
}
public void setClientRows(int clientRows) {
this.clientRows = clientRows;
}
}
[testPopup5.xhtml]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition>
<h:head>
<title>RichFaces Showcase</title>
</h:head>
<h:body>
<h:outputStylesheet>
a.no-decor>img {
border: none;
}
</h:outputStylesheet>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<h:panelGrid columns="2">
<a4j:commandButton id="search" action="#{carsBean2.queryRec}"
value="Search" render="table" />
<a4j:commandButton id="reset" action="#{carsBean2.initQuery}"
value="Reset" type="reset" render="table" />
</h:panelGrid>
</h:form>
<h:form>
<rich:dataTable value="#{carsBean2.inventoryItems}" var="car"
id="table" rows="5">
<rich:column>
<f:facet name="header">Model</f:facet>
<h:outputText value="#{car.model}" />
</rich:column>
<rich:column>
<f:facet name="header">Price</f:facet>
<h:outputText value="#{car.price}" />
</rich:column>
<rich:column>
<a4j:commandLink styleClass="no-decor" render="editGrid"
execute="#this" oncomplete="#{rich:component('editPanel')}.show()">
<h:graphicImage value="/images/icons/common/edit.gif" alt="edit" />
<f:setPropertyActionListener target="#{carsBean2.editedCar}"
value="#{car}" />
</a4j:commandLink>
</rich:column>
</rich:dataTable>
<rich:popupPanel id="statPane" autosized="true" rendered="true">
<h:graphicImage value="/images/common/ai.gif" alt="ai" />
Please wait...
</rich:popupPanel>
<rich:popupPanel header="Edit Car Details" id="editPanel">
<h:panelGrid columns="3" id="editGrid">
<h:outputText value="Model" />
<h:outputText value="#{carsBean2.editedCar.model}" />
<h:panelGroup />
<h:outputText value="Price" />
<h:outputText value="#{carsBean2.editedCar.price}" />
<h:panelGroup />
</h:panelGrid>
<a4j:commandButton value="Cancel"
onclick="#{rich:component('editPanel')}.hide(); return false;" />
</rich:popupPanel>
</h:form>
</h:body>
</ui:composition>
</html>
Using firebug, I manage discover few diff between local and online GAE version.
1) editPanel # local change it style stage from 'visibility hidden' to 'display none' and then 'display block' when click on edit icon.
However editPanel # GAE still remain unchange with 'visibility hidden'
[Local]
<div id="j_idt9:editPanel" style="visibility: hidden;">
<div id="j_idt9:editPanel" style="display: none;">
<div id="j_idt9:editPanel" style="display: block;">
[GAE]
<div id="j_idt9:editPanel" style="visibility: hidden;">
2) under , local version contain value in table tag
3) Shown in firebug's script tab, when click on edit link, local version display as: and follow by table values.
However online version display it as and without any table values
p/s: Online: http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
By the way the GAE display below warning when page first load. Don't know is related to the problem or not.
[s~cloudenterpriseapps/0.365021621033424561].: SystemId Unknown; Line #57; Column #31; Failed calling setMethod method
[FireBug Script tab, Local. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="j_idt9:editGrid"><![CDATA[<table id="j_idt9:editGrid">
<tbody>
<tr>
<td>Model</td>
<td>Corvette</td>
<td></td>
</tr>
<tr>
<td>Price</td>
<td>47405</td>
<td></td>
</tr>
</tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAEUTEh...EUXAkFAAA]]></update></changes><extension id="org.richfaces.extension"><complete>RichFaces.$('j_idt9:editPanel').show();</complete><render>j_idt9:editGrid</render></extension></partial-response>
[FireBug Script tab, GAE. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAAAANVYbW....KBTUkFAAA]]></update></changes></partial-response>
Solved after upgrade JSF api and implementation jar from 2.0 to 2.1

Resources