How to export data from struts2 to Excel - struts2

I am expecting data to export in Excel format. I have a problem in writing data to Excel file and when I download that it is not in Excel format.
In the below first method I am getting data from a database and sending it as a list to a second method that expects a filename. In the second method I am trying to write the database data to an Excel file.
I have done coding for exporting to PDF also. It gets correctly downloaded, but in the URL bar downloadTeacherListINExcel.action. I have given a file path like this: String fileName = "f:\\teachersList.pdf". When it is downloaded in the browser the filename comes over like f-teachersList.
public String exportInExcel() {
// getting data from data base
listOfTeachers = reportService.getlistOfTeachers();
for (TeacherDTO teacherDTO : listOfTeachers) {
System.out.println(teacherDTO.getTeacherEmailID());
}
// sending a list data export in excel
String excelFileName = reportService.exportInExcel(listOfTeachers);
System.out.println(excelFileName);
try {
fileInputStream = new FileInputStream(excelFileName);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Execl Download Method");
return SUCCESS;
}
Code written for Excel
#Override
public String exportInExcel(List<TeacherDTO> listOfTeachers) {
String fileName = "f:\\test\\teachersList.xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Products List");
// create heading
Row rowHeading = sheet.createRow(0);
rowHeading.createCell(0).setCellValue("Id");
rowHeading.createCell(1).setCellValue("Name");
for (int i = 0; i < 6; i++) {
CellStyle stylerowHeading = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short) 11);
stylerowHeading.setFont(font);
stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
rowHeading.getCell(i).setCellStyle(stylerowHeading);
}
int r = 1;
for (TeacherDTO teacher : listOfTeachers) {
Row row = sheet.createRow(r);
// Id column
Cell cellID = row.createCell(0);
cellID.setCellValue(teacher.getTeacherFirstName());// (run after
// this line
// once)
// name column
Cell cellName = row.createCell(1);
cellName.setCellValue(teacher.getTeacherEmailID());// (run after
// this line
// once)
r++;
}
// Auto fit
for (int i = 0; i < 6; i++) {
sheet.autoSizeColumn(i);
}
FileOutputStream fout = new FileOutputStream(new File(fileName));
workbook.write(fout);
fout.close();
System.out.println("Excel Written Success");
} catch (Exception e) {
System.out.println("%%%%%%%%%%%%%%%%%%"+e.getMessage());
}
return fileName;
}
Struts config
<action name="downloadTeacherListINExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
Error
Hibernate: select
pradeepkumarhe1989#gmail.com
%%%%%%%%%%%%%%%%%%null
f:\test\teachersList.xls
java.io.FileNotFoundException: f:\test\teachersList.xls (The system cannot find the file specified)

In action class
public String exportInExcel() {
//getting List of teachers
listOfTeachers = reportServiceExcel.getlistOfTeachers();
// sending list data to write in excel sheet
HSSFWorkbook workbook = reportServiceExcel.exportInExcel(listOfTeachers);
// code to download
try {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
workbook.write(boas);
setInputStream(new ByteArrayInputStream(boas.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}
Excel class
public HSSFWorkbook exportInExcel(List<TeacherDTO> listOfTeachers) {
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Products List");
// create heading
Row rowHeading = sheet.createRow(0);
rowHeading.createCell(0).setCellValue("Name");
rowHeading.createCell(1).setCellValue("Mobile Number");
rowHeading.createCell(2).setCellValue("Email ID");
rowHeading.createCell(3).setCellValue("Designation");
for (int i = 0; i < 4; i++) {
CellStyle stylerowHeading = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short) 11);
stylerowHeading.setFont(font);
stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
rowHeading.getCell(i).setCellStyle(stylerowHeading);
}
int r = 1;
for (TeacherDTO t : listOfTeachers) {
String teacherName = t.getTeacherFirstName() + "" + t.getTeacherMiddleName() + ""
+ t.getTeacherLastName();
Row row = sheet.createRow(r);
// Name column
Cell cellName = row.createCell(0);
cellName.setCellValue(teacherName);// (run after this line once)
// Mobile Number column
Cell cellMobileNumber = row.createCell(1);
cellMobileNumber.setCellValue(t.getTeacherMobileNumber());
// Email column
Cell cellEmail = row.createCell(2);
cellEmail.setCellValue(t.getTeacherEmailID());
// Designation column
Cell cellDesignation = row.createCell(3);
cellDesignation.setCellValue(t.getTeacherDesignation());
r++;
}
// Auto fit columns in excel sheet
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
System.out.println("Excel Written Success");
} catch (Exception e) {
e.printStackTrace();
}
return workbook;
}
Struts configuration
<action name="downloadTeacherListExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="teachersList.xls"</param>
<param name="bufferSize">4096</param>
</result>
</action>

package com.download2excel;
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.opensymphony.xwork2.ActionSupport;
public class Excelwritinginjava extends ActionSupport { private InputStream fileInputStream;
public String createExcelFile() throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("January"); HSSFRow rowhead = sheet.createRow((short) 0); rowhead.createCell(0).setCellValue("S.No."); rowhead.createCell(1).setCellValue("Customer Name"); rowhead.createCell(2).setCellValue("Account Number"); rowhead.createCell(3).setCellValue("e-mail"); rowhead.createCell(4).setCellValue("Balance"); HSSFRow row = sheet.createRow((short) 1); row.createCell(0).setCellValue("1"); row.createCell(1).setCellValue("subodh"); row.createCell(2).setCellValue("7644864977"); row.createCell(3).setCellValue("subodh.orcl#gmail.com"); row.createCell(4).setCellValue("700000.00"); HSSFRow row1 = sheet.createRow((short) 2); row1.createCell(0).setCellValue("2"); row1.createCell(1).setCellValue("subodh sharma"); row1.createCell(2).setCellValue("22222222"); row1.createCell(3).setCellValue("subodh.orcl#gmail.com"); row1.createCell(4).setCellValue("200000.00"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); setFileInputStream(new ByteArrayInputStream(baos.toByteArray())); return SUCCESS; }
public InputStream getFileInputStream() { return fileInputStream; }
public void setFileInputStream(InputStream fileInputStream) { this.fileInputStream = fileInputStream; }
}
======================struts.xml ====
application/octet-stream fileInputStream attachment;filename="Download.xls" 1024

Related

How to keep the hyperlink in an pdf merge in ITextSharp? [duplicate]

How to merge multiple pdf files (generated on run time) through ItextSharp then printing them.
I found the following link but that method requires the pdf names considering that the pdf files stored and this is not my case .
I have multiple reports i'll convert them to pdf files through this method :
private void AddReportToResponse(LocalReport followsReport)
{
string mimeType;
string encoding;
string extension;
string[] streams = new string[100];
Warning[] warnings = new Warning[100];
byte[] pdfStream = followsReport.Render("PDF", "", out mimeType, out encoding, out extension, out streams, out warnings);
//Response.Clear();
//Response.ContentType = mimeType;
//Response.AddHeader("content-disposition", "attachment; filename=Application." + extension);
//Response.BinaryWrite(pdfStream);
//Response.End();
}
Now i want to merge all those generated files (Bytes) in one pdf file to print it
If you want to merge source documents using iText(Sharp), there are two basic situations:
You really want to merge the documents, acquiring the pages in their original format, transfering as much of their content and their interactive annotations as possible. In this case you should use a solution based on a member of the Pdf*Copy* family of classes.
You actually want to integrate pages from the source documents into a new document but want the new document to govern the general format and don't care for the interactive features (annotations...) in the original documents (or even want to get rid of them). In this case you should use a solution based on the PdfWriter class.
You can find details in chapter 6 (especially section 6.4) of iText in Action — 2nd Edition. The Java sample code can be accessed here and the C#'ified versions here.
A simple sample using PdfCopy is Concatenate.java / Concatenate.cs. The central piece of code is:
byte[] mergedPdf = null;
using (MemoryStream ms = new MemoryStream())
{
using (Document document = new Document())
{
using (PdfCopy copy = new PdfCopy(document, ms))
{
document.Open();
for (int i = 0; i < pdf.Count; ++i)
{
PdfReader reader = new PdfReader(pdf[i]);
// loop over the pages in that document
int n = reader.NumberOfPages;
for (int page = 0; page < n; )
{
copy.AddPage(copy.GetImportedPage(reader, ++page));
}
}
}
}
mergedPdf = ms.ToArray();
}
Here pdf can either be defined as a List<byte[]> immediately containing the source documents (appropriate for your use case of merging intermediate in-memory documents) or as a List<String> containing the names of source document files (appropriate if you merge documents from disk).
An overview at the end of the referenced chapter summarizes the usage of the classes mentioned:
PdfCopy: Copies pages from one or more existing PDF documents. Major downsides: PdfCopy doesn’t detect redundant content, and it fails when concatenating forms.
PdfCopyFields: Puts the fields of the different forms into one form. Can be used to avoid the problems encountered with form fields when concatenating forms using PdfCopy. Memory use can be an issue.
PdfSmartCopy: Copies pages from one or more existing PDF documents. PdfSmartCopy is able to detect redundant content, but it needs more memory and CPU than PdfCopy.
PdfWriter: Generates PDF documents from scratch. Can import pages from other PDF documents. The major downside is that all interactive features of the imported page (annotations, bookmarks, fields, and so forth) are lost in the process.
I used iTextsharp with c# to combine pdf files. This is the code I used.
string[] lstFiles=new string[3];
lstFiles[0]=#"C:/pdf/1.pdf";
lstFiles[1]=#"C:/pdf/2.pdf";
lstFiles[2]=#"C:/pdf/3.pdf";
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage;
string outputPdfPath=#"C:/pdf/new.pdf";
sourceDocument = new Document();
pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
//Open the output file
sourceDocument.Open();
try
{
//Loop through the files list
for (int f = 0; f < lstFiles.Length-1; f++)
{
int pages =get_pageCcount(lstFiles[f]);
reader = new PdfReader(lstFiles[f]);
//Add pages of current file
for (int i = 1; i <= pages; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
reader.Close();
}
//At the end save the output file
sourceDocument.Close();
}
catch (Exception ex)
{
throw ex;
}
private int get_pageCcount(string file)
{
using (StreamReader sr = new StreamReader(File.OpenRead(file)))
{
Regex regex = new Regex(#"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
Here is some code I pulled out of an old project I had. It was a web application but I was using iTextSharp to merge pdf files then print them.
public static class PdfMerger
{
/// <summary>
/// Merge pdf files.
/// </summary>
/// <param name="sourceFiles">PDF files being merged.</param>
/// <returns></returns>
public static byte[] MergeFiles(List<Stream> sourceFiles)
{
Document document = new Document();
MemoryStream output = new MemoryStream();
try
{
// Initialize pdf writer
PdfWriter writer = PdfWriter.GetInstance(document, output);
writer.PageEvent = new PdfPageEvents();
// Open document to write
document.Open();
PdfContentByte content = writer.DirectContent;
// Iterate through all pdf documents
for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
{
// Create pdf reader
PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
int numberOfPages = reader.NumberOfPages;
// Iterate through all pages
for (int currentPageIndex = 1; currentPageIndex <=
numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize(
reader.GetPageSizeWithRotation(currentPageIndex));
// Create page
document.NewPage();
PdfImportedPage importedPage =
writer.GetImportedPage(reader, currentPageIndex);
// Determine page orientation
int pageOrientation = reader.GetPageRotation(currentPageIndex);
if ((pageOrientation == 90) || (pageOrientation == 270))
{
content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
reader.GetPageSizeWithRotation(currentPageIndex).Height);
}
else
{
content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception exception)
{
throw new Exception("There has an unexpected exception" +
" occured during the pdf merging process.", exception);
}
finally
{
document.Close();
}
return output.GetBuffer();
}
}
/// <summary>
/// Implements custom page events.
/// </summary>
internal class PdfPageEvents : IPdfPageEvent
{
#region members
private BaseFont _baseFont = null;
private PdfContentByte _content;
#endregion
#region IPdfPageEvent Members
public void OnOpenDocument(PdfWriter writer, Document document)
{
_baseFont = BaseFont.CreateFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
_content = writer.DirectContent;
}
public void OnStartPage(PdfWriter writer, Document document)
{ }
public void OnEndPage(PdfWriter writer, Document document)
{ }
public void OnCloseDocument(PdfWriter writer, Document document)
{ }
public void OnParagraph(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnParagraphEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnChapter(PdfWriter writer, Document document,
float paragraphPosition, Paragraph title)
{ }
public void OnChapterEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnSection(PdfWriter writer, Document document,
float paragraphPosition, int depth, Paragraph title)
{ }
public void OnSectionEnd(PdfWriter writer,
Document document, float paragraphPosition)
{ }
public void OnGenericTag(PdfWriter writer, Document document,
Rectangle rect, string text)
{ }
#endregion
private float GetCenterTextPosition(string text, PdfWriter writer)
{
return writer.PageSize.Width / 2 - _baseFont.GetWidthPoint(text, 8) / 2;
}
}
I didn't write this, but made some modifications. I can't remember where I found it. After I merged the PDFs I would call this method to insert javascript to open the print dialog when the PDF is opened. If you change bSilent to true then it should print silently to their default printer.
public Stream addPrintJStoPDF(Stream thePDF)
{
MemoryStream outPutStream = null;
PRStream finalStream = null;
PdfDictionary page = null;
string content = null;
//Open the stream with iTextSharp
var reader = new PdfReader(thePDF);
outPutStream = new MemoryStream(finalStream.GetBytes());
var stamper = new PdfStamper(reader, (MemoryStream)outPutStream);
var jsText = "var res = app.setTimeOut('this.print({bUI: true, bSilent: false, bShrinkToFit: false});', 200);";
//Add the javascript to the PDF
stamper.JavaScript = jsText;
stamper.FormFlattening = true;
stamper.Writer.CloseStream = false;
stamper.Close();
//Set the stream to the beginning
outPutStream.Position = 0;
return outPutStream;
}
Not sure how well the above code is written since I pulled it from somewhere else and I haven't worked in depth at all with iTextSharp but I do know that it did work at merging PDFs that I was generating at runtime.
Tested with iTextSharp-LGPL 4.1.6:
public static byte[] ConcatenatePdfs(IEnumerable<byte[]> documents)
{
using (var ms = new MemoryStream())
{
var outputDocument = new Document();
var writer = new PdfCopy(outputDocument, ms);
outputDocument.Open();
foreach (var doc in documents)
{
var reader = new PdfReader(doc);
for (var i = 1; i <= reader.NumberOfPages; i++)
{
writer.AddPage(writer.GetImportedPage(reader, i));
}
writer.FreeReader(reader);
reader.Close();
}
writer.Close();
outputDocument.Close();
var allPagesContent = ms.GetBuffer();
ms.Flush();
return allPagesContent;
}
}
To avoid the memory issues mentioned, I used file stream instead of memory stream(mentioned in ITextSharp Out of memory exception merging multiple pdf) to merge pdf files:
var parentDirectory = Directory.GetParent(SelectedDocuments[0].FilePath);
var savePath = parentDirectory + "\\MergedDocument.pdf";
using (var fs = new FileStream(savePath, FileMode.Create))
{
using (var document = new Document())
{
using (var pdfCopy = new PdfCopy(document, fs))
{
document.Open();
for (var i = 0; i < SelectedDocuments.Count; i++)
{
using (var pdfReader = new PdfReader(SelectedDocuments[i].FilePath))
{
for (var page = 0; page < pdfReader.NumberOfPages;)
{
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, ++page));
}
}
}
}
}
}
****/*For Multiple PDF Print..!!*/****
<button type="button" id="btnPrintMultiplePdf" runat="server" class="btn btn-primary btn-border btn-sm"
onserverclick="btnPrintMultiplePdf_click">
<i class="fa fa-file-pdf-o"></i>Print Multiple pdf</button>
protected void btnPrintMultiplePdf_click(object sender, EventArgs e)
{
if (ValidateForMultiplePDF() == true)
{
#region Declare Temp Variables..!!
CheckBox chkList = new CheckBox();
HiddenField HidNo = new HiddenField();
string Multi_fofile, Multi_listfile;
Multi_fofile = Multi_listfile = "";
Multi_fofile = Server.MapPath("PDFRNew");
#endregion
for (int i = 0; i < grdRnew.Rows.Count; i++)
{
#region Find Grd Controls..!!
CheckBox Chk_One = (CheckBox)grdRnew.Rows[i].FindControl("chkOne");
Label lbl_Year = (Label)grdRnew.Rows[i].FindControl("lblYear");
Label lbl_No = (Label)grdRnew.Rows[i].FindControl("lblCode");
#endregion
if (Chk_One.Checked == true)
{
HidNo .Value = llbl_No .Text.Trim()+ lbl_Year .Text;
if (File.Exists(Multi_fofile + "\\" + HidNo.Value.ToString() + ".pdf"))
{
#region Get Multiple Files Name And Paths..!!
if (Multi_listfile != "")
{
Multi_listfile = Multi_listfile + ",";
}
Multi_listfile = Multi_listfile + Multi_fofile + "\\" + HidNo.Value.ToString() + ".pdf";
#endregion
}
}
}
#region For Generate Multiple Pdf..!!
if (Multi_listfile != "")
{
String[] Multifiles = Multi_listfile.Split(',');
string DestinationFile = Server.MapPath("PDFRNew") + "\\Multiple.Pdf";
MergeFiles(DestinationFile, Multifiles);
Response.ContentType = "pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + DestinationFile + "\"");
Response.TransmitFile(DestinationFile);
Response.End();
}
else
{
}
#endregion
}
}
private void MergeFiles(string DestinationFile, string[] SourceFiles)
{
try
{
int f = 0;
/**we create a reader for a certain Document**/
PdfReader reader = new PdfReader(SourceFiles[f]);
/**we retrieve the total number of pages**/
int n = reader.NumberOfPages;
/**Console.WriteLine("There are " + n + " pages in the original file.")**/
/**Step 1: creation of a document-object**/
Document document = new Document(reader.GetPageSizeWithRotation(1));
/**Step 2: we create a writer that listens to the Document**/
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(DestinationFile, FileMode.Create));
/**Step 3: we open the Document**/
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
/**Step 4: We Add Content**/
while (f < SourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
/**Console.WriteLine("Processed page " + i)**/
}
f++;
if (f < SourceFiles.Length)
{
reader = new PdfReader(SourceFiles[f]);
/**we retrieve the total number of pages**/
n = reader.NumberOfPages;
/**Console.WriteLine("There are"+n+"pages in the original file.")**/
}
}
/**Step 5: we Close the Document**/
document.Close();
}
catch (Exception e)
{
string strOb = e.Message;
}
}
private bool ValidateForMultiplePDF()
{
bool chkList = false;
foreach (GridViewRow gvr in grdRnew.Rows)
{
CheckBox Chk_One = (CheckBox)gvr.FindControl("ChkSelectOne");
if (Chk_One.Checked == true)
{
chkList = true;
}
}
if (chkList == false)
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Check At Least On CheckBox.";
grdRnew.Focus();
set_timeout();
return false;
}
return true;
}

How to extract date from tweets with lucene?

I have some tweets that I have already indexed "TweetIndexer" with lucene knowing that each tweet contains an ID, USER, TEXT, and DATE.
I want to only retrieve the date with another class "TweetSearcher" how to proceed?
Example of tweet:
"0","1467811372","Mon Apr 06 22:20:00 PDT 2009","NO_QUERY","joy_wolf","#Kwesidei not the whole crew ".
This my class TweetIndexer:
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TweetIndexer {
protected static final String COMMA = "\",\"";
protected static final String POLARITY = "polarity";
protected static final String ID = "id";
protected static final String DATE = "date";
protected static final String QUERY = "query";
protected static final String USER = "user";
protected static final String TEXT = "text";
public static void main(String[] args) throws Exception {
try {
String indexDir = "D:\\tweet\\index";
String dataFile = "D:\\tweet\\collection\\tweets.csv";
TweetIndexer tweetIndexer = new TweetIndexer();
long start = System.currentTimeMillis();
int count = tweetIndexer.index(new File(indexDir), new File(dataFile));
System.out.print(String.format("Indexed %d documents in %d seconds", count, (System.currentTimeMillis() - start) / 1000));
}
catch (Exception e) {
System.out.println("Usage: java TweetIndexer <index directory> <csv data file>");
}
}
private int index(File indexDir, File dataFile) throws Exception {
IndexWriter indexWriter = new IndexWriter(
FSDirectory.open(indexDir),
new IndexWriterConfig(Version.LUCENE_44, new KeywordAnalyzer()));
int count = indexFile(indexWriter, dataFile);
indexWriter.close();
return count;
}
private int indexFile(IndexWriter indexWriter, File dataFile) throws IOException {
FieldType fieldType = new FieldType();
fieldType.setStored(true);
fieldType.setIndexed(true);
BufferedReader bufferedReader = new BufferedReader(new FileReader(dataFile));
String line = "";
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
// Hack to ignore commas within elements in csv (so we can split on "," rather than just ,)
line = line.substring(1, line.length() - 1);
String[] tweetInfo = line.split(COMMA);
Document document = new Document();
document.add(new Field(POLARITY, tweetInfo[0], fieldType));
document.add(new Field(ID, tweetInfo[1], fieldType));
document.add(new Field(DATE, tweetInfo[2], fieldType));
document.add(new Field(QUERY, tweetInfo[3], fieldType));
document.add(new StringField(USER, tweetInfo[4], Field.Store.YES));
document.add(new StringField(TEXT, tweetInfo[5], Field.Store.YES));
indexWriter.addDocument(document);
count++;
}
return count;
}
}
And this is short java code for my class TweetSearcher:
public class TweetSearcher {
public static void main(String[] args) throws Exception {
try {
String indexDir = "D:\\tweet\\index";
int numHits = Integer.parseInt("3");
TweetSearcher tweetSearcher = new TweetSearcher();
tweetSearcher.dateSearch(new File(indexDir), numHits);
private void dateSearch(File indexDir, int numHits) throws Exception {
System.out.println("Find dates:");
Directory directory = FSDirectory.open(indexDir);
DirectoryReader directoryReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(directoryReader);

Getting total Records in database

public ResultSet getRecordsCount(){
ResultSet result = null;
try {
result = statement.executeQuery("Select count(word) from records");
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
I'm trying to get total number of rows in my database but it is returning garbage value.
I'm Using SQL Server 2012 and there is no exception in the code.
Is my code correct?
I would use this code:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public static void main(String[] args) {
int numRows = 0;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String userName = "user"; //in case you need
String password = "password"; // in case you need
String url = "jdbc:microsoft:sqlserver://localhost:1433"+";databaseName=THE_NAME_OF_MY_DB";
Connection con = DriverManager.getConnection(url, userName, password);
// if you don't need user and password then
// Connection con = DriverManager.getConnection(url);
String SQL = "SELECT * FROM table_name";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
ResultSetMetaData rsMetaData = rs.getMetaData();
// This while loop is to loop over each row and the for loop
// is to loop over each field
while (rs.next()) {
for(int i=1; i <= rs.getColumnCount(); i++){
numRows ++;
System.out.println(rs.getString(i));
//This prints field by field
}
}
System.out.println(Total column number"+rs.getColumnCount());
System.out.println(Total row number"+Integer.toString(numRows));
rs.close();
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

Get data only one folder not for all folders in treeview - Blackberry

i want to show all folders(images, videos,files) with directories/files, currently only show images folder with files, but other folder are not show. I try to find solution but not found. Here is the code & its screenshot(http://postimg.org/image/wm5ypbk9d/).
FileManager.java
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
public class FilesManager extends MainScreen {
FTPMessages _ftp = null;
String[] fileList;
// ..................
private final Bitmap openIcon = Bitmap.getBitmapResource("open.png");
private final Bitmap closedIcon = Bitmap.getBitmapResource("closed.png");
private final Bitmap movieIcon = Bitmap.getBitmapResource("movie.png");
private final Bitmap songIcon = Bitmap.getBitmapResource("song.png");
private final Bitmap playIcon = Bitmap.getBitmapResource("play.png");
private final Bitmap imgIcon = Bitmap.getBitmapResource("images.png");
String nodeTen;
int node10;
TreeField myTree;
String[] nodeData;
// ListField to be displayed - null - no Field displayed
// List of entries to be displayed - null or length = 0 means no entries
// protected so that another Thread can update this list....
protected ListDirectory[] _resultsList = null; // entries available for
// display
private ListDirectory _selectedEntry = null;
public FilesManager(FTPMessages ftp) {
super();
_ftp = ftp;
// Setting starting directory
try {
/*
* fileList = _ftp.list(); for (int i = 0; i < fileList.length; i++)
* { _ftp.cwd(fileList[i]); }
*/
_ftp.cwd("images");
_ftp.cwd("files");
_ftp.cwd("videos");
} catch (Exception e) {
}
this.setTitle("Server File List");
TreeCallback myCallback = new TreeCallback();
myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0
&& (status & KeypadListener.STATUS_SHIFT) == 0) {
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node. Do some default action or
// else fall through.
// Note: this will also detect empty folders, which
// might or
// might not be something your app has to handle
Dialog.alert("clicked " + getCookie(node));
// TODO: open player screen, etc.
return true;
}
}
return super.navigationClick(status, time);
}
};
myTree.setDefaultExpanded(false);
myTree.setRowHeight(openIcon.getHeight());
try {
node10 = myTree.addChildNode(0, _ftp.pwd());
} catch (Exception e) {
}
this.add(myTree);
refreshList();
}
private void refreshList() {
// TODO Auto-generated method stub
_resultsList = null;
String[] directory = null;
try {
directory = _ftp.list();
} catch (Exception e) {
}
if (directory != null && directory.length > 0) {
_resultsList = new ListDirectory[directory.length];
for (int i = 0; i < directory.length; i++) {
_resultsList[i] = new ListDirectory(directory[i],
ListDirectory.UNIX_SERVER);
}
}
if (_resultsList != null && _resultsList.length > 0) {
// we have some results
for (int i = 0; i < _resultsList.length; i++) {
String bb = directory[i];
String nodeFive = new String(bb);
this.myTree.addChildNode(node10, nodeFive);
}
} else {
}
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
final int PAD = 8;
String text = (String) _tree.getCookie(node);
Bitmap icon = closedIcon;
if (text.endsWith(".mp3")) {
icon = songIcon;
} else if (text.endsWith(".avi")) {
icon = movieIcon;
} else if (text.endsWith(".png") || text.endsWith(".jpg")) {
icon = imgIcon;
} else if (_tree.getExpanded(node)) {
icon = openIcon;
}
g.drawBitmap(indent, y, icon.getWidth(), icon.getHeight(), icon, 0,
0);
// This assumes filenames all contain '.' character!
if (text.indexOf(".") > 0) {
// Leaf node, so this is a playable item (movie or song)
g.drawBitmap(_tree.getWidth() - playIcon.getWidth() - PAD, y
+ PAD, playIcon.getWidth(), playIcon.getHeight(),
playIcon, 0, 0);
}
int fontHeight = getFont().getHeight();
g.drawText(text, indent + icon.getWidth() + PAD,
y + (_tree.getRowHeight() - fontHeight) / 2);
}
}
}
The other classes that used with this code, download from that link(complete project classes)
http://remote.offroadstudios.com/files/filemanager.zip
you can also check files on server, ip:64.207.150.31:21, username:remote, password:123456789

generate different charts in the same activity using a spinner and achartEngine library

I am a novice in android and I am using achartEngine library to draw line Graph. what I want to do is to update the graph by using a spinner. For exmaple, if I chose the first option I will get a yellow graph and when
I swich to the second option in my spinner, the graph changes and becomes white with new title and data
for the moment I can only update the data but not the rest of the graph
package com.example.test2;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.test2.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Graphique extends Activity {
private GraphicalView mChart1;
private GraphicalView mChart2;
private TimeSeries glecimieSeries ;
private TimeSeries pressionSeries;
private XYMultipleSeriesDataset dataset;
private XYSeriesRenderer glecimieRenderer;
private XYSeriesRenderer pressionRenderer;
private XYMultipleSeriesRenderer multiRenderer;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listeappareil;
// url to get all products list
private static String url_liste_appareil ;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static String TAG_APPAREIL;
private static final String TAG_PID = "pid";
private static final String TAG_NOM = "nom";
private static final String TAG_J = "jour";
private static final String TAG_Y = "Y";
// products JSONArray
JSONArray appareil = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphique);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String pid = in.getStringExtra(TAG_PID);
String nom = in.getStringExtra(TAG_NOM);
// Displaying all values on the screen
TextView lblNom = (TextView) findViewById(R.id.nom_patient);
lblNom.setText(nom);
Spinner mySpinner = (Spinner)findViewById(R.id.mesure);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.appareils, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
OnItemSelectedListener selectedGraph = new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> spinner, View container,
int position, long id) {
String graph = spinner.getItemAtPosition(position).toString().toLowerCase();
if(graph == "tensiometre"){
url_liste_appareil = "http://10.0.2.2/connexion_android/"+graph+".php";
TAG_APPAREIL = graph;
// Setting up chart
setupChart2();
// Start plotting chart
new ChartTask2().execute();
}else{
url_liste_appareil = "http://10.0.2.2/connexion_android/"+graph+".php";
TAG_APPAREIL = graph;
// Setting up chart
setupChart1();
// Start plotting chart
new ChartTask1().execute();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
// Setting ItemClick Handler for Spinner Widget
mySpinner.setOnItemSelectedListener(selectedGraph);
}
private void setupChart1(){
// Creating TimeSeries for Glecimie
glecimieSeries = new TimeSeries("Glecimie");
// Creating a dataset to hold each series
dataset = new XYMultipleSeriesDataset();
// Adding Glecimie Series to the dataset
dataset.addSeries(glecimieSeries);
// Creating XYSeriesRenderer to customize glecimieSeries
glecimieRenderer = new XYSeriesRenderer();
glecimieRenderer.setColor(Color.YELLOW);
glecimieRenderer.setPointStyle(PointStyle.CIRCLE);
glecimieRenderer.setFillPoints(true);
glecimieRenderer.setLineWidth(2);
glecimieRenderer.setDisplayChartValues(true);
// Creating a XYMultipleSeriesRenderer to customize the whole chart
multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setZoomButtonsVisible(true);
// Adding glecimieRenderer and pressionRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(glecimieRenderer);
// Getting a reference to LinearLayout of the MainActivity Layout
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);
// Creating a Time Chart
mChart1 = (GraphicalView) ChartFactory.getTimeChartView(getBaseContext(), dataset, multiRenderer,"dd-MMM-yyyy");
multiRenderer.setClickEnabled(true);
multiRenderer.setSelectableBuffer(10);
// Setting a click event listener for the graph
mChart1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Format formatter = new SimpleDateFormat("dd-MMM-yyyy");
SeriesSelection seriesSelection = mChart1.getCurrentSeriesAndPoint();
if (seriesSelection != null) {
int seriesIndex = seriesSelection.getSeriesIndex();
String selectedSeries="Glecimie";
if(seriesIndex==0)
selectedSeries = "Glecimie";
else
selectedSeries = "Pression";
// Getting the clicked Date ( x value )
long clickedDateSeconds = (long) seriesSelection.getXValue();
Date clickedDate = new Date(clickedDateSeconds);
String strDate = formatter.format(clickedDate);
// Getting the y value
int amount = (int) seriesSelection.getValue();
// Displaying Toast Message
Toast.makeText(
getBaseContext(),
"Prélèvement au " + strDate + " : " + amount ,
Toast.LENGTH_SHORT).show();
}
}
});
chartContainer.removeAllViews();
// Adding the Line Chart to the LinearLayout
chartContainer.addView(mChart1);
}
private class ChartTask1 extends AsyncTask<String, String, String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Graphique.this);
pDialog.setMessage("Loading data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Generates dummy data in a non-ui thread
protected String doInBackground(String... params) {
// Building Parameters
List<NameValuePair> param = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_liste_appareil, "GET", param);
// Check your log cat for JSON reponse
Log.d("Tous les appareil: ", json.toString());
try{
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
appareil = json.getJSONArray(TAG_APPAREIL);
Date[] dt = new Date[appareil.length()];
// looping through All Products
for (int j = 0; j < appareil.length(); j++) {
JSONObject p = appareil.getJSONObject(j);
// Storing each json item in variable
GregorianCalendar gc = new GregorianCalendar(2012, 10, j+1);
dt[j] = gc.getTime();
String y = p.getString(TAG_Y);
String jr = p.getString(TAG_J);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(jr);
// Adding data to Glecimie and Pression Series
glecimieSeries.add(d,Double.parseDouble(y));
multiRenderer.setXTitle("Dates");
multiRenderer.setYTitle("Prélèvements");
}
}
}catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Plotting generated data in the graph
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into the graph
* */
mChart1.repaint();
}
});
}
}
private void setupChart2(){
// Creating TimeSeries for Pression
pressionSeries = new TimeSeries("Pression");
// Creating a dataset to hold each series
dataset = new XYMultipleSeriesDataset();
// Adding Glecimie Series to dataset
dataset.addSeries(pressionSeries);
// Creating XYSeriesRenderer to customize pressionSeries
pressionRenderer = new XYSeriesRenderer();
pressionRenderer.setColor(Color.YELLOW);
pressionRenderer.setPointStyle(PointStyle.CIRCLE);
pressionRenderer.setFillPoints(true);
pressionRenderer.setLineWidth(2);
pressionRenderer.setDisplayChartValues(true);
// Creating a XYMultipleSeriesRenderer to customize the whole chart
multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setZoomButtonsVisible(true);
// Adding glecimieRenderer and pressionRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(pressionRenderer);
// Getting a reference to LinearLayout of the MainActivity Layout
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);
// Creating a Time Chart
mChart2 = (GraphicalView) ChartFactory.getTimeChartView(getBaseContext(), dataset, multiRenderer,"dd-MMM-yyyy");
multiRenderer.setClickEnabled(true);
multiRenderer.setSelectableBuffer(10);
// Setting a click event listener for the graph
mChart2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Format formatter = new SimpleDateFormat("dd-MMM-yyyy");
SeriesSelection seriesSelection = mChart2.getCurrentSeriesAndPoint();
if (seriesSelection != null) {
int seriesIndex = seriesSelection.getSeriesIndex();
String selectedSeries="Glecimie";
if(seriesIndex==0)
selectedSeries = "Glecimie";
else
selectedSeries = "Pression";
// Getting the clicked Date ( x value )
long clickedDateSeconds = (long) seriesSelection.getXValue();
Date clickedDate = new Date(clickedDateSeconds);
String strDate = formatter.format(clickedDate);
// Getting the y value
int amount = (int) seriesSelection.getValue();
// Displaying Toast Message
Toast.makeText(
getBaseContext(),
" Prélèvement au" + strDate + " : " + amount ,
Toast.LENGTH_SHORT).show();
}
}
});
chartContainer.removeAllViews();
// Adding the Line Chart to the LinearLayout
chartContainer.addView(mChart2);
}
private class ChartTask2 extends AsyncTask<String, String, String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Graphique.this);
pDialog.setMessage("Loading data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Generates dummy data in a non-ui thread
protected String doInBackground(String... params) {
// Building Parameters
List<NameValuePair> param = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_liste_appareil, "GET", param);
// Check your log cat for JSON reponse
Log.d("Tous les appareil: ", json.toString());
try{
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
appareil = json.getJSONArray(TAG_APPAREIL);
Date[] dt = new Date[appareil.length()];
// looping through All Products
for (int j = 0; j < appareil.length(); j++) {
JSONObject p = appareil.getJSONObject(j);
// Storing each json item in variable
GregorianCalendar gc = new GregorianCalendar(2012, 10, j+1);
dt[j] = gc.getTime();
String y = p.getString(TAG_Y);
String jr = p.getString(TAG_J);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(jr);
// Adding data to Glecimie and Pression Series
pressionSeries.add(d,Double.parseDouble(y));
multiRenderer.setChartTitle("la pression");
multiRenderer.setXTitle("Dates");
multiRenderer.setYTitle("Prélèvements");
}
}
}catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Plotting generated data in the graph
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into the graph
* */
mChart2.repaint();
}
});
}
}
// Initiating Menu XML file (menu.xml)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_graphique, menu);
return (super.onCreateOptionsMenu(menu));
}
}
Please help
In order to refresh both charts, you need to call repaint on both:
mChart1.repaint();
mChart2.repaint();
You can update the color and other values of the chart by passing values.
In openChart() method you can pass the values.
private void openChart(final String[] code, final int[] distribution,final int color){
defaultRenderer.setBackgroundColor(color);
}

Resources