Get user info from database - database

I am trying to validate a user login info with what I have in my database but when I try to run my code I keep on getting errors
This is my login.jsp page where I am working on the vaildation of the username and password In my table I have CID which I am using as the username any modification can be done to my code to make it run?
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
Connection con;
PreparedStatement ps1, ps2;
public void jspInit()
{
try
{
//loading the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//establish the connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/ProjectDB", "admin1", "1234");
//create statement object
ps1 = con.prepareStatement("select count(*) from customers where username = ? and password=?");
ps2 = con.prepareStatement("select * from customers");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
<%
String param = request.getParameter("s1");
if(param =="link")
{
ResultSet rs = ps2.executeQuery();
out.println("<table>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td");
out.println("</tr>");
}
out.println("</table>");
rs.close();
}
else
{
//write jdbc code for authentication
String user = request.getParameter("uname");
String pass = request.getParameter("pwd");
//set form data as param value
ps1.setString(1,user);
ps1.setString(2,pass);
//excute the query
ResultSet rs = ps1.executeQuery();
int cnt = 0;
if (rs.next())
cnt = rs.getInt(1);
if(cnt == 0)
out.println("<b><i><font color=red>Invalid credential</fonr></i></b>");
else
{
out.println("<form><fieldset style= width:25%; >");
out.println("<b><i><font color=red>valid credential..</fonr></i></b><br>");
out.println("<b><i><font size=6 color=blue>Welcome to My Page</fonr></i></b>");
out.println("</fieldset></form>");
}
}
%>
<%!
public void jspDestroy()
{
try
{
//colse
ps1.close();
ps2.close();
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
</body>
</html>

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) + "]";
}
}

HTTP Status 500 - Unable to compile class for JSP with Tomcat 9.0

Apache Tomcat/9.0.0.M1
THIS IS MY PROGRAM ::::::::::::::::::::
<table border=27>
<%# page import="java.sql.*;"%>
<%!
Connection con;
Statement st;
public void jspInit()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","shah");
st=con.createStatement();
}
catch(Exception e)
{
System.err.println(e);
}
}
%>
<%
ResultSet rs=st.executeQuery("select *from student");
ResultSetMetaData rm=rs.getMetaData();
int n=rm.getColumnCount();
out.println("<tr>");
for(int i=1;i<=n;i++)
{
out.println("<th>"+rm.getColumnName(i)+"</th>");
}
out.println("</tr>");
while(rs.next())
{
out.println("<tr>");
for(int i=1;i<=n;i++)
{
out.println("<td>"+rs.getString(i)+"</td>");
}
out.println("</tr>");
}
%>
<%!
public void destroy()
{
try
{
con.close();
}
catch(Exception e)
{
System.err.println(e);
}
}
%>
</tr>
</table>
</body>
HTTP Status 500 - Unable to compile class for JSP
type Exception report
message Unable to compile class for JSP
description The server encountered an internal error that prevented it from fulfilling this request.
<%# page import="java.sql.*;" %>
that ; in import is not valid in a jsp .if you want to import more then one package seperate them with ,.
ex:
<%# page import="java.sql.*,java.io.*" %>

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.

program data randomizes only when run with break point

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)

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.

Resources