So I managed to make Jtable working one way, from table1 to table2. but I don't really know how to make it work both ways(from table2 to table1). I was trying putting transferhandler on both Jtables, but I guess that they interfere with each other. So I'm pretty much stuck. Can someone explain how should I do it?
Here is the implementation (when I'm trying to do the same with the second Jtable it is not working):
table1.setDragEnabled(true);
table2.setTransferHandler(new TransferHandler() {
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
int row2 = table1.getSelectedRow();
int rows[] = table1.getSelectedRows();
if (rows.length > 1){
Object strings2[][] = new String[rows.length][2];
for (int i=0; i<rows.length; i++) {
for (int j = 0; j < 2; j++)
strings2[i][j] = table1.getValueAt(rows[i], j);
}
String pathToCopy, pathToPaste;
for (int k=0; k<strings2.length; k++) {
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings2[k][0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings2[k][0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings2[k][0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings2[k][0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
}
return true;
}
else {
if (row2 != -1) {
for (int i = 0; i < 2; i++)
strings[i] = table1.getValueAt(row2, i);
}
String pathToCopy, pathToPaste;
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings[0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings[0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings[0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings[0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
return true;
}
}
});
Related
I have already uploaded the excel file in my local directory but the problem is that I can't read it from that location.
I am using struts 1.1 ,db2.
package mj.eps.action;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.mj.eps.dto.business.auction.UploadObject;
import com.mj.eps.dto.training.IndexValueReportObject;
import com.mj.eps.framework.util.FileScaner;
import com.mj.eps.framework.util.IConstant;
public class IndexValueAction extends EPSBaseAction{
public IndexValueAction() {
super();
}
#SuppressWarnings("unchecked")
#Override
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Vector<String> vector = new Vector<String>();
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
try{
String contentType = request.getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in =
new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead =
in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary =
contentType.substring(
lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos =
(
(file.substring(0, boundaryLocation))
.getBytes())
.length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd-MM-yy hh-mm-ss");
saveFile = saveFile.substring(0, saveFile.indexOf("."))+ "-"+ df.format(dt)+ ".xls";
String uploadFilePath = "";
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if(endPos > dataBytes.length )
endPos = dataBytes.length;
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String[]> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId=0;
try {
File outFile = new File(uploadFilePath + saveFile);
ServletConfig config = getServlet();
ServletContext sc = config.getServletContext();
boolean retVal = false;
boolean exists = true;
String filepath = outFile.getAbsolutePath();
String realPath = sc.getRealPath("virusCheck.properties");
exists = FileScaner.loadProperty(realPath);
if (exists) {
retVal = FileScaner.checkVirus(realPath, filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>Virus found!!"));
}
if (retVal) {
retVal = FileScaner.checkFileSign(filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>File type not supported!!"));
}
}
}
else {
}
if (retVal) {
}
if (errors.isEmpty())
{
***FileInputStream inputStream=new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows=read_sheet.getRows();
for (int j=1;j<rows;j++){
String[] fields=new String[4];
for(int i=0;i<fields.length;i++)
{
Cell cell=read_sheet.getCell(i,j);
fields[i]=cell.getContents().trim();
if(fields[0] != null ){
try{
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
}else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
}
catch(Exception e1)
{
int k=i+1;
errorVector.add("Invalid data at field "+k);
System.out.println(" err1 :" + e1.toString());
errorId = 1;
}
}
}
if(!(fields[0] == null || (fields[0].trim().equals(""))))
{
rowVector.add(fields);
}
else{
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
if (errorId == 0) {
int row = 0;
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
IndexValueReportObject indexValueReportObj =
new IndexValueReportObject();
String[] fields =
rowVector.elementAt(i);
System.out.println("abc>>>>>"+fields[0]);
System.out.println("abc>>>>>>>>>>>>>"+fields[1]);
System.out.println("abc>>>>>>>>>>>>>>>>>"+fields[2]);
System.out.println("abc>>>>>>>>>>>>>>>>>>>>>>>"+fields[3]);
try{
indexValueReportObj
.setDate(
Timestamp.valueOf(fields[0]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Date at row " + (row+1));
}
try{
indexValueReportObj
.setPlatts(
new BigDecimal(fields[1]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Platts Value at row " + (row+1));
}
try{
indexValueReportObj
.setArgus(
new BigDecimal(fields[2]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Argus Value at row " + (row+1));
}
try{
indexValueReportObj
.setTsi(
new BigDecimal(fields[3]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid TSI value at row " + (row+1));
}
indexObjectVector.add(
indexValueReportObj);
}
} else {
vector.add(
"No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
String filePathAndName=uploadFilePath + saveFile;
System.out.println("indexObjectVector"+indexObjectVector);
request.setAttribute(
IConstant.INDEX_OBJECT_VECTOR,
indexObjectVector);
request.getSession().setAttribute(
IConstant.FILE_NAME,
filePathAndName);
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
} else {
vector.add("File Type mismatch ");
}
} catch (Exception e) {
vector.add("No excel has been selected ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
forward = mapping.findForward("failureUpload");
} else {
forward = mapping.findForward("success");
}
return forward;
}
}
In Workbook portion I want to read the excel file from local directory. When I run this code in debug mode, the control is going into exception block and forward it in my success page. So can some one please help me with this? I put sysout in that portion but nothing shows. I am using JXl for excel read and write. My confusion is in 3 star portion.
Not an answer, but a partial refactoring.
This is an abomination of an action. There is zero way this should have ever passed any code review:
Actions and business logic should be completely separate.
Methods should be responsible for a single responsibility. This method:
Checks content type (arguably reasonable since that's web-related)
Manually parses the form (inexcusable; use a library)
Processes an Excel file (inexcusable; extract) which in turn:
Validates against business logic
Converts Excel values to BO values
The amount of un-equivalent work the action does defies explanation. This makes it essentially impossible to reason about, debug, fix, or anything. The below is a very rough start of refactoring, but you have another day or two of work to properly isolate levels of functionality and error handling (which is wrong, by the way, because you never check vector, possibly the worst-named variable in history, for errors, it's just thrown away?!?!?!)
public class IndexValueAction extends EPSBaseAction {
public IndexValueAction() {
super();
}
boolean isValidContentType(contentType) {
return (contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)
}
String readContent(request) throws Exception {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
totalBytesRead += in.read(dataBytes, totalBytesRead, formDataLength);
}
return new String(dataBytes);
}
void scanFile(realPath, outFilePath, errors) throws Exception {
if (!FileScanner.loadProperty(realPath)) {
return false;
}
if (!FileScanner.cleanFile(outFilePath)) {
FileScaner.cleanFile(outFilePath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>Virus found!!"));
return;
}
if (!FileScanner.checkFileSign(outFilePath)) {
FileScaner.cleanFile(filepath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>File type not supported!!"));
}
}
IndexValueReportObject loadIndexValueReportObject(String[] fields, int i, Vector<String> vector) {
IndexValueReportObject indexValueReportObj = new IndexValueReportObject();
try {
indexValueReportObj.setDate(Timestamp.valueOf(fields[0]));
} catch (Exception e) {
vector.add("Invalid Date at row " + (i + 2));
}
try {
indexValueReportObj.setPlatts(new BigDecimal(fields[1]));
} catch (Exception e) {
vector.add("Invalid Platts Value at row " + (i + 2));
}
try {
indexValueReportObj.setArgus(new BigDecimal(fields[2]));
} catch (Exception e) {
vector.add("Invalid Argus Value at row " + (i + 2));
}
try {
indexValueReportObj.setTsi(new BigDecimal(fields[3]));
} catch (Exception e) {
vector.add("Invalid TSI value at row " + (i + 2));
}
return indexValueReportObj;
}
#Override
#SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Vector<String> vector = new Vector<String>();
if (!isValidContentType(request.getContentType())) {
vector.add("File Type mismatch");
return mapping.findForward("failureUpload");
}
String file;
try {
file = readContent(request);
} catch (Exception e) {
vector.add("No excel has been selected");
return mapping.findForward("failureUpload");
}
ActionErrors errors = new ActionErrors();
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = file.substring(0, boundaryLocation).getBytes().length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy hh-mm-ss");
String fileSuffix = "-" + df.format(new Date()) + ".xls";
saveFile = saveFile.substring(0, saveFile.indexOf(".")) + fileSuffix;
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
String uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if (endPos > dataBytes.length) {
endPos = dataBytes.length;
}
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String []> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId = 0;
try {
ServletContext sc = getServlet().getServletContext();
String realPath = sc.getRealPath("virusCheck.properties");
File outFile = new File(uploadFilePath + saveFile);
String outFilePath = outFile.getAbsolutePath();
scanFile(realPath, outFilePath, errors);
if (errors.isEmpty()) {
FileInputStream inputStream = new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows = read_sheet.getRows();
for (int j = 1; j < rows; j++) {
String[] fields = new String[4];
for(int i = 0; i < fields.length; i++) {
Cell cell = read_sheet.getCell(i, j);
fields[i] = cell.getContents().trim();
if (fields[0] != null) {
try {
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
} else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
} catch(Exception e1) {
int k = i+1;
errorVector.add("Invalid data at field " + k);
errorId = 1;
}
}
}
if (!(fields[0] == null || (fields[0].trim().equals("")))) {
rowVector.add(fields);
} else {
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
if (errorId == 0) {
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
String[] fields = rowVector.elementAt(i);
indexObjectVector.add(loadIndexValueReportObject(loadIndexValueReportObject(fields, i, vector)));
}
} else {
vector.add("No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
request.setAttribute(IConstant.INDEX_OBJECT_VECTOR, indexObjectVector);
request.getSession().setAttribute(IConstant.FILE_NAME, uploadFilePath + saveFile);
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
return mapping.findForward("failureUpload");
}
return mapping.findForward("success");
}
}
I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
The background info here is that I have a working Indexer and Search (in java) that indexes and searches a file directory for the filenames and then copies the files to a "Results" Directory.
What I need/ don't have much experience in is writing jsp files. I need the jsp file to have a search bar for the text and then a search button. When text is entered in the bar, and the button is clicked, I need it to run my search program with the entered text as an arg.
I have added the IndexFiles and the SearchFiles classes for reference.
Please explain with a good example if you can help out!
public class SearchFiles {
static File searchDirectory = new File(
"C:\\Users\\flood.j.2\\Desktop\\IndexSearch\\Results");
static String v = new String();
static String path = null;
String title = null;
File addedFile = null;
OutputStream out = null;
String dirName = "C:\\Users\\flood.j.2\\Desktop\\IndexSearch\\Results";
public static void main(String[] args) throws Exception {
String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string]";
if (args.length > 0
&& ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.exit(0);
}
for (int j = 5; j < args.length; j++) {
v += args[j] + " ";
}
String index = "index";
String field = "contents";
String queries = null;
boolean raw = false;
String queryString = null;
int hits = 100;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
index = args[i + 1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i + 1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i + 1];
i++;
} else if ("-query".equals(args[i])) {
queryString = v;
i++;
}
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
index)));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(
queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_40, field, analyzer);
for (int m = 0; m < 2; m++) {
if (queries == null && queryString == null) {
System.out.println("Enter query: ");
}
String line = queryString != null ? queryString : in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
Query query = parser.parse(line);
System.out.println("Searching for: " + query.toString(field));
doPagingSearch(in, searcher, query, hits, raw, queries == null
&& queryString == null);
if (queryString == null) {
break;
}
}
reader.close();
}
public static void doPagingSearch(BufferedReader in,
IndexSearcher searcher, Query query, int hitsPerPage, boolean raw,
boolean interactive) throws IOException {
// Collect enough docs to show 500 pages
TopDocs results = searcher.search(query, 5 * hitsPerPage);
ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
System.out.println(numTotalHits + " total matching documents");
int start = 0;
int end = Math.min(numTotalHits, hitsPerPage);
FileUtils.deleteDirectory(searchDirectory);
while (true) {
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
path = doc.get("path");
if (path != null) {
System.out.println((i + 1) + ". " + path);
File addFile = new File(path);
try {
FileUtils.copyFileToDirectory(addFile, searchDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (!interactive || end == 0) {
break;
}
System.exit(0);
}
}
}
public class IndexFiles {
private IndexFiles() {
}
public static void main(String[] args) {
String usage = "java org.apache.lucene.demo.IndexFiles"
+ " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
+ "This indexes the documents in DOCS_PATH, creating a Lucene index"
+ "in INDEX_PATH that can be searched with SearchFiles";
String indexPath = null;
String docsPath = null;
boolean create = true;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
indexPath = args[i + 1];
i++;
} else if ("-docs".equals(args[i])) {
docsPath = args[i + 1];
i++;
} else if ("-update".equals(args[i])) {
create = false;
}
}
if (docsPath == null) {
System.err.println("Usage: " + usage);
System.exit(1);
}
final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out
.println("Document directory '"
+ docDir.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(new File(indexPath));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
if (create) {
iwc.setOpenMode(OpenMode.CREATE);
} else {
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
}
IndexWriter writer = new IndexWriter(dir, iwc);
indexDocs(writer, docDir);
writer.close();
Date end = new Date();
System.out.println(end.getTime() - start.getTime()
+ " total milliseconds");
} catch (IOException e) {
System.out.println(" caught a " + e.getClass()
+ "\n with message: " + e.getMessage());
}
}
static void indexDocs(IndexWriter writer, File file) throws IOException {
if (file.canRead()) {
if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
indexDocs(writer, new File(file, files[i]));
}
}
} else {
FileInputStream fis;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException fnfe) {
return;
}
try {
Document doc = new Document();
Field pathField = new StringField("path",
file.getAbsolutePath(), Field.Store.YES);
doc.add(pathField);
doc.add(new LongField("modified", file.lastModified(),
Field.Store.NO));
doc.add(new TextField("title", file.getName(), null));
System.out.println(pathField);
if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
System.out.println("adding " + file);
writer.addDocument(doc);
} else {
System.out.println("updating " + file);
writer.updateDocument(new Term("path", file.getPath()),
doc);
}
} finally {
fis.close();
}
}
}
}
}
First, you should definitely do this in a servlet rather than a JSP. Putting lots of logic in JSP is bad practice. (See the servlets info page).
Second, it would probably be better on performance to make a cronjob (Linux) or Task (Windows) to run the search program every hour and store the results in a database and just have your servlet pull from there rather than allow the user to initiate the search program.
Okay following is my Simmulation.java file and I am supposed to write main method for it to work. But I have no idea how to do it.
I have tried like following, but it didn't work!
public static void main(String args[])
{
new Simmulation(args[0]);
}
Any help is much appreciated. Thank you in advance
This is my Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation
{
Queue < CashewPallet > inputQueue = new LinkedList < CashewPallet > ();
Stack < CashewPallet > stBay1 = new Stack < CashewPallet > ();
Stack < CashewPallet > stBay2 = new Stack < CashewPallet > ();
FileOutputStream fout4;
PrintWriter pw;
static int tick = 0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index = 0;
String nutType = "";
int id = 0;
Scanner s2;
try
{
sc = new Scanner(new File(fn));
fout4 = new FileOutputStream("nuts.txt");
pw = new PrintWriter(fout4, true);
String eol = System.getProperty("line.separator"); // Reading string line by line
while (sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if (s2.hasNext())
{
while (s2.hasNext())
{
String s = s2.next();
if (index == 0)
{
nutType = s;
}
else
{
id = Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype " + nutType + " Id is " + id + "tick " + tick);
if ((nutType.equalsIgnoreCase("A") || nutType.equalsIgnoreCase("P") || nutType.equalsIgnoreCase("C") || nutType.equalsIgnoreCase("W")) && id != 0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(), id));
System.out.println("Size of Queue " + inputQueue.size());
int k = 0;
if (!inputQueue.isEmpty())
{
while (inputQueue.size() > k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index = 0;
if (!stBay2.isEmpty())
{
while (!stBay2.isEmpty())
{
c1 = stBay2.pop();
temp = tick + " " + c1.getNutType() + " " + c1.getId() + eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp = tick + eol;
fout4.write(temp.getBytes());
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
closeStream();
}
public CashewPallet process(CashewPallet c)
{
// CashewPallet c=new CashewPallet();
int k = 0;
// while(stBay.size()>k)
// {
// c=stBay.pop();
String operation = c.getNutType();
if (c.getPriority() == 1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch (operation)
{
case "A":
shelling(c);
washing(c);
packing(c);
break;
case "C":
washing(c);
packing(c);
break;
case "W":
washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch (Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for " + c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for " + c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for " + c.getNutType());
}
stBay2.push(c);
return true;
}
The problem is that you are not passing any parameters to the program. So the length of the args is 0. What you can try is to check for the length of the args passed before using it.
if (args.length > 0)
new Simulation(args[0]);
else
new Simulation("Default value");
That should solve your problem.