How do I get two input values compared to my query records?
For example, I enter 500 Double, and I want everyone who has over 500 Double on my list.
if I enter 300 Doubles and 150 Triples. Only display everybody who has more than 300 Doubles and more than 150 Triples. Right now, displays the doubles that are more than the input value.
namespace SQLiteIntegration
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (HasValidInput())
{
int doubles = int.Parse(DoublesTextBox.Text);
int triples = int.Parse(TriplesTextBox.Text);
//MARKER - Probably an error here
DataTable dt = new DataTable();
string datasource = #"Data Source=../../lahman2016.sqlite;";
//Batting.'2B' is the number of doubles a player hit in a season
//Batting.'3B' is the number of triples a player hit in a season
string sql = $"SELECT namefirst, namelast, sum(Batting.'2B'), sum(Batting.'3B') from Master JOIN Batting on Master.playerID = Batting.playerID GROUP BY Master.playerid HAVING SUM(Batting.'2B') AND SUM(Batting.'3B') > {doubles};";
using (SQLiteConnection conn = new SQLiteConnection(datasource))
{
conn.Open();
SQLiteDataAdapter da = new SQLiteDataAdapter(sql, conn);
da.Fill(dt);
conn.Close();
}
playerList.Clear();
foreach (DataRow row in dt.Rows)
{
// MARKER: Making something different show up
string playerRow = $"{row[0].ToString()} {row[1].ToString()} - 2B = {row[2].ToString()}, 3B = {row[3].ToString()}";
playerList.Add(playerRow);
}
populateList();
}
}
private List<string> playerList = new List<string>();
private void populateList()
{
ListView.Items.Clear();
foreach (string s in playerList)
{
ListView.Items.Add(s);
}
}
private string ValidateTextBox(TextBox box, string name)
{
string message = "";
string text = box.Text;
int amount = 0;
if (text == "")
box.Text = "0";
else
{
bool isNumber = int.TryParse(text, out amount);
if (!isNumber)
{
message += $"Invalid Input - {name} is not a number! ";
}
if (amount < 0)
{
message += $"Invalid Input - {name} is negative! ";
}
}
return message;
}
private bool HasValidInput()
{
string message = ValidateTextBox(DoublesTextBox, "Doubles") +
ValidateTextBox(TriplesTextBox, "Triples");
if (message == "")
{
return true;
}
else
{
MessageBox.Show(message);
return false;
}
}
}
}
I am expecting if I enter 300 Doubles and 150 Triples. Only display everybody who has more than 300 Doubles and more than 150 Triples. Right now, displays the doubles that are more than the input value.
Related
Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
public class Lookup extends GenericUDF {
private static String delimiter = "|";
private ConcurrentHashMap < String, HashMap < String, String >> fileMap = new ConcurrentHashMap < String, HashMap < String, String >> ();
protected String loggedInUser;
protected String loggedInApplication;
private transient GenericUDFUtils.StringHelper returnHelper;
private transient StringConverter[] stringConverter;
private static final Logger LOG = LoggerFactory.getLogger(Lookup.class.getName());
#Override
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
if (arguments.length < 2) {
throw new UDFArgumentLengthException(
"lookup takes 2 or more arguments");
}
stringConverter = new StringConverter[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (arguments[0].getCategory() != Category.PRIMITIVE) {
throw new UDFArgumentException(
"lookup only takes primitive types");
}
stringConverter[i] = new PrimitiveObjectInspectorConverter.StringConverter(
(PrimitiveObjectInspector) arguments[i]);
}
setLoggedInUser();
returnHelper = new GenericUDFUtils.StringHelper(
PrimitiveCategory.STRING);
LOG.info("initialize successful");
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
}
private void setLoggedInUser() {
if (loggedInUser == null) {
loggedInUser = SessionState.get().getUserName();
if (loggedInUser != null) {
int idx = loggedInUser.indexOf('.');
loggedInApplication = idx > -1 ? loggedInUser.substring(0, idx) : null;
}
}
}
private void initMap(String f) {
LOG.info("initMap involked");
if (loggedInApplication == null)
throw new NullPointerException(
"Unable to retrieve application name from user.");
String filePath = "/basepath/" + loggedInApplication.toLowerCase() + "/" + f +
".txt";
String line = null;
try {
LOG.info("filePath =" + filePath);
FileSystem fs = FileSystem.get(new Configuration());
FSDataInputStream in = fs.open(new Path(filePath));
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
HashMap < String, String > map = new HashMap < String, String > ();
while ((line = br.readLine()) != null) {
// ignore comment lines
if (line.startsWith("#")) {
continue;
}
String[] strs = line.split("\t");
if (strs.length == 2) {
map.put(strs[0].toUpperCase().trim(), strs[1].trim());
} else if (strs.length > 2) {
map.put(getKey(strs), strs[strs.length - 1].trim());
}
}
fileMap.put(f, map);
br.close();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public Text getValue(String s, String f) {
initMap(f);
HashMap < String, String > map = fileMap.get(f);
LOG.info("getValue() fileMap =" + fileMap);
String v = map.get(s);
return v == null ? null : new Text(v);
}
#Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
String val = buildVal(arguments);
String lookupFile = (String) stringConverter[arguments.length - 1].convert(arguments[arguments.length - 1].get());
Text returnVal = getValue(val.toUpperCase(), lookupFile.toLowerCase());
return returnVal == null ? null : returnHelper.setReturnValue(returnVal.toString());
}
#Override
public String getDisplayString(String[] arg0) {
return "lookup()";
}
private String buildVal(DeferredObject[] arguments) throws HiveException {
StringBuilder builder = new StringBuilder();
int cnt = arguments.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append((String) stringConverter[i].convert(arguments[i].get()));
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
private String getKey(String[] strs) {
StringBuilder builder = new StringBuilder();
int cnt = strs.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append(strs[i].toUpperCase().trim());
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
}
We insert a point cloud in Revit and have to move and rotate it in several axles to get a good world alignment. We then need to apply the same transforms to a Revit MEP link that contains edgwise piping.
I have acquired the 3x4 matrix from the point cloud in revit, I would like to apply that to the revit mep link so that they are in alignment.
I have successfully applied the translation portion of the transform, I am stuck on the rotation portion. Could someone please assist with this. Dyslexia and Matrices do not work well together.
Thanks to Jeremy at the Building Coder for getting me this far!
9/4/19 - I edited the rotational part of the code, however the "ElementTransformUtils.RotateElement" does not have any effect on the link in Revit.
Autodesk.Revit.DB.View
pView = ActiveUIDocument.Document.ActiveView;Autodesk.Revit.DB.Transaction
t = new Autodesk.Revit.DB.Transaction(ActiveUIDocument.Document, "EdgewiseCoordination");
t.Start();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
Autodesk.Revit.ApplicationServices.Application application = document.Application;
ElementId elementid = null;
elementid = uidoc.Selection.PickObject(ObjectType.Element, "Select element to Copy Transform or ESC to reset the view").ElementId;
Element e = document.GetElement(elementid);
Instance ei = e as Instance;
Transform pct = ei.GetTransform();
ElementId elementid2 = null;
elementid2 = uidoc.Selection.PickObject(ObjectType.Element, "Select element to Apply Transform or ESC to reset the view").ElementId;
Element e2 = document.GetElement(elementid2);
Instance ei2 = e2 as Instance;
ElementTransformUtils.MoveElement(document,elementid2,pct.Origin);
Line lineaxis = GetRotationAxisFromTransform(pct);
double tangle = GetRotationAngleFromTransform(pct);
ElementTransformUtils.RotateElement(document,elementid2,lineaxis,tangle);
t.Commit();
}
private static Line GetRotationAxisFromTransform(Transform transform)
{
double x = transform.BasisY.Z - transform.BasisZ.Y;
double y = transform.BasisZ.X - transform.BasisX.Z;
double z = transform.BasisX.Y - transform.BasisY.X;
return Line.CreateUnbound(transform.Origin, new XYZ(x, y, z));
}
private static double GetRotationAngleFromTransform(Transform transform)
{
double x = transform.BasisX.X;
double y = transform.BasisY.Y;
double z = transform.BasisZ.Z;
double trace = x + y + z;
return Math.Acos((trace - 1) / 2.0);
}
Earlier Code to save out the transform----------------------------------
public void Objectlocation()
{
Autodesk.Revit.DB.View
pView = ActiveUIDocument.Document.ActiveView;Autodesk.Revit.DB.Transaction
t = new Autodesk.Revit.DB.Transaction(ActiveUIDocument.Document, "Objectlocation");
t.Start();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
Autodesk.Revit.ApplicationServices.Application application = document.Application;
ElementId elementid = null;
elementid = uidoc.Selection.PickObject(ObjectType.Element, "Select element or ESC to reset the view").ElementId;
Element e = document.GetElement(elementid);
Instance ei = e as Instance;
Transform pct = ei.GetTransform();
//string spctrans = TransformString(pct);
//TaskDialog.Show("Point Cloud Transform", spctrans);
//spctrans = (spctrans + ",0,0,0,1");
string slocx = TransformStringX(pct);
string slocy = TransformStringY(pct);
string slocz = TransformStringZ(pct);
string slocation = (slocx + "," + slocy + "," + slocz + ",0,0,0,1");
using (StreamWriter sw = new StreamWriter("test.txt"))
{
sw.WriteLine(slocation);
}
t.Commit();
}
static public string RealString( double a )
{
return a.ToString( "0.####################" );
}
static public string PointStringX( XYZ p )
{
double convunit = 0;
convunit = UnitUtils.ConvertFromInternalUnits(p.X,DisplayUnitType.DUT_DECIMAL_INCHES);
return string.Format( "{0}", RealString( convunit ));
}
static public string TransformStringX( Transform t )
{
return string.Format( "{0},{1},{2},{3}", PointStringX( t.BasisX ),
PointStringX( t.BasisY ), PointStringX( t.BasisZ ), PointStringX( t.Origin ) );
}
static public string PointStringY( XYZ p )
{
double convunit = 0;
convunit = UnitUtils.ConvertFromInternalUnits(p.Y,DisplayUnitType.DUT_DECIMAL_INCHES);
return string.Format( "{0}", RealString( convunit ));
}
static public string TransformStringY( Transform t )
{
return string.Format( "{0},{1},{2},{3}", PointStringY( t.BasisX ),
PointStringY( t.BasisY ), PointStringY( t.BasisZ ), PointStringY( t.Origin ) );
}
static public string PointStringZ( XYZ p )
{
double convunit = 0;
convunit = UnitUtils.ConvertFromInternalUnits(p.Z,DisplayUnitType.DUT_DECIMAL_INCHES);
return string.Format( "{0}", RealString( convunit ));
}
static public string TransformStringZ( Transform t )
{
return string.Format( "{0},{1},{2},{3}", PointStringZ( t.BasisX ),
PointStringZ( t.BasisY ), PointStringZ( t.BasisZ ), PointStringZ( t.Origin ) );
}
I edited the stuff you had on bcoder to split up the matrix in order to match the acad api that I was feeding it into.
ACAD API below-----------------------------------------------------------
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System.Reflection;
namespace Transformer
{
public class Commands
{
[CommandMethod("TRANS", CommandFlags.UsePickSet)]
static public void TransformEntity()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// Our selected entity (only one supported, for now)
ObjectId id;
// First query the pickfirst selection set
PromptSelectionResult psr = ed.SelectImplied();
if (psr.Status != PromptStatus.OK || psr.Value == null)
{
// If nothing selected, ask the user
PromptEntityOptions peo =
new PromptEntityOptions(
"\nSelect entity to transform: "
);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
id = per.ObjectId;
}
else
{
// If the pickfirst set has one entry, take it
SelectionSet ss = psr.Value;
if (ss.Count != 1)
{
ed.WriteMessage(
"\nThis command works on a single entity."
);
return;
}
ObjectId[] ids = ss.GetObjectIds();
id = ids[0];
}
PromptResult pr = ed.GetString("\nEnter property name: ");
if (pr.Status != PromptStatus.OK)
return;
string prop = pr.StringResult;
// Now let's ask for the matrix string
pr = ed.GetString("\nEnter matrix values: ");
if (pr.Status != PromptStatus.OK)
return;
// Split the string into its individual cells
string[] cells = pr.StringResult.Split(new char[] { ',' });
if (cells.Length != 16)
{
ed.WriteMessage("\nMust contain 16 entries.");
return;
}
try
{
// Convert the array of strings into one of doubles
double[] data = new double[cells.Length];
for (int i = 0; i < cells.Length; i++)
{
data[i] = double.Parse(cells[i]);
}
// Create a 3D matrix from our cell data
Matrix3d mat = new Matrix3d(data);
// Now we can transform the selected entity
Transaction tr =
doc.TransactionManager.StartTransaction();
using (tr)
{
Entity ent =
tr.GetObject(id, OpenMode.ForWrite)
as Entity;
if (ent != null)
{
bool transformed = false;
// If the user specified a property to modify
if (!string.IsNullOrEmpty(prop))
{
// Query the property's value
object val =
ent.GetType().InvokeMember(
prop, BindingFlags.GetProperty, null, ent, null
);
// We only know how to transform points and vectors
if (val is Point3d)
{
// Cast and transform the point result
Point3d pt = (Point3d)val,
res = pt.TransformBy(mat);
// Set it back on the selected object
ent.GetType().InvokeMember(
prop, BindingFlags.SetProperty, null,
ent, new object[] { res }
);
transformed = true;
}
else if (val is Vector3d)
{
// Cast and transform the vector result
Vector3d vec = (Vector3d)val,
res = vec.TransformBy(mat);
// Set it back on the selected object
ent.GetType().InvokeMember(
prop, BindingFlags.SetProperty, null,
ent, new object[] { res }
);
transformed = true;
}
}
// If we didn't transform a property,
// do the whole object
if (!transformed)
ent.TransformBy(mat);
}
tr.Commit();
}
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage(
"\nCould not transform entity: {0}", ex.Message
);
}
}
}
}
END ACAD API
I am using script component in ssis with C# code using Microsoft.Analysisservices namespace to fetch the cube metadata. The code looks somewhat like this
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Microsoft.AnalysisServices;
using System.Windows.Forms;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
//IDTSConnectionManager100 connMgr;
Server OLAPServer = new Server();
public override void AcquireConnections(object Transaction)
{
OLAPServer.Connect(this.Connections.OLAPConnection.ConnectionString);
}
public override void PreExecute()
{
base.PreExecute();
/*
Add your code here for preprocessing or remove if not needed
*/
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void CreateNewOutputRows()
{
IDTSVariables100 vars = null;
string OLAPDBName;
VariableDispenser.LockOneForRead("OLAPDBName", ref vars);
Database OLAPDB;
OLAPDBName = vars[0].Value.ToString();
try
{
OLAPDB = OLAPServer.Databases.GetByName(OLAPDBName);
}
catch
{
return;
}
// loop through cubes
CubeCollection Cubes = OLAPDB.Cubes;
MeasureGroupCollection Mgroups;
CubeDimensionCollection Dimensions;
MeasureGroupDimensionCollection MgroupDims;
DimensionAttributeCollection Attributes;
foreach (Cube cb in Cubes)
{
//Test for one Measure Group
//MeasureGroup mgroup = Mgroups.GetByName("Inward Exposure");
Mgroups = cb.MeasureGroups;
// all dimensions associated with that Measure Group
// loop through Measure Groups
foreach (MeasureGroup mg in Mgroups)
{
// loop though all cube dimensions
Dimensions = cb.Dimensions;**strong text**
foreach (CubeDimension dim in Dimensions)
{
bool CanBeAnalysed = false;**strong text**
// loop through dimensions and see if dimension exists in mgroupDims (ie check if it can be analysed)
MgroupDims = mg.Dimensions;
foreach (MeasureGroupDimension mgd in MgroupDims)
{
if (mgd.CubeDimension == dim)
{
CanBeAnalysed = true;
break;
}
}
// loop through each Measure and Attribute a
String DimName = dim.Name;
bool DimVisible = dim.Visible;
String MgroupName = mg.Name;
String CubeName = cb.Name;
String MeasureExpression;
String Description;
// for every attribute in dimension
Attributes = dim.Dimension.Attributes;
foreach (DimensionAttribute Attr in Attributes)
{
String AttrName = Attr.Name;
bool AttrVisible = Attr.AttributeHierarchyVisible;
String AttrNameColumn = Attr.NameColumn.ToString();
String AttributeRelationship = Attr.AttributeRelationships.ToString();
// get every measure in measuregroup
foreach (Measure m in mg.Measures)
{
String MeasureName = m.Name.ToString();
bool MeasureVisible = m.Visible;
String MeasureNameColumn = m.Source.ToString();
if (m.MeasureExpression != null)
{
// MessageBox.Show(m.MeasureExpression.ToString());
MeasureExpression = m.MeasureExpression.ToString();
}
else
{
// MessageBox.Show(m.MeasureExpression.ToString());
MeasureExpression = " " ;
}
if (m.Description != null)
{
// MessageBox.Show(m.MeasureExpression.ToString());
Description = m.Description.ToString();
}
else
{
// MessageBox.Show(m.MeasureExpression.ToString());
Description = " ";
}
Output0Buffer.AddRow();
Output0Buffer.OLAPDBName = OLAPDBName;
Output0Buffer.CubeName = CubeName;
Output0Buffer.DimensionName = DimName;
Output0Buffer.DimensionVisible = DimVisible;
Output0Buffer.AttrDDSColumn = AttrNameColumn;
Output0Buffer.AttrName = AttrName;
Output0Buffer.AttrVisible = AttrVisible;
Output0Buffer.MeasureGroupName = MgroupName;
Output0Buffer.MeasureName = MeasureName;
Output0Buffer.MeasureVisible = MeasureVisible;
Output0Buffer.MeasureDDSColumn = MeasureNameColumn;
Output0Buffer.IsAnalysable = CanBeAnalysed;
Output0Buffer.MeasureExpression = MeasureExpression;
Output0Buffer.Description = Description;
Output0Buffer.AttributeRelationship = AttributeRelationship;
}
}
} // end of Cube Dim Loop
} // end of Measure Group loop
} // end of cube loop
}
}
I was successful in getting the cube metadata with the above code.However, i am stuck at getting the metadata of the perspective cube and the Relationships of the measure groups i.e whether the measure groups are many-many. Any help is very much appreciated.
Here is some code for detecting dimension relationships including many-to-many. See the GetDimensionUsage function:
https://raw.githubusercontent.com/BIDeveloperExtensions/bideveloperextensions/master/SSAS/PrinterFriendlyDimensionUsage.cs
Here is some code around navigating perspectives:
https://raw.githubusercontent.com/BIDeveloperExtensions/bideveloperextensions/master/SSAS/TriStatePerspectivesPlugin.cs
Start reading around the following line:
if (perspective.MeasureGroups.Contains(mg.Name))
Suppose a lucene index with fields : date, content.
I want to get all terms value and frequency of docs whose date is yesterday. date field is keyword field. content field is analyzed and indexed.
Pls help me with sample code.
My solution source is as follow ...
/**
*
*
* #param reader
* #param fromDateTime
* - yyyymmddhhmmss
* #param toDateTime
* - yyyymmddhhmmss
* #return
*/
static public String top10(IndexSearcher searcher, String fromDateTime,
String toDateTime) {
String top10Query = "";
try {
Query query = new TermRangeQuery("tweetDate", new BytesRef(
fromDateTime), new BytesRef(toDateTime), true, false);
final BitSet bits = new BitSet(searcher.getIndexReader().maxDoc());
searcher.search(query, new Collector() {
private int docBase;
#Override
public void setScorer(Scorer scorer) throws IOException {
}
#Override
public void setNextReader(AtomicReaderContext context)
throws IOException {
this.docBase = context.docBase;
}
#Override
public void collect(int doc) throws IOException {
bits.set(doc + docBase);
}
#Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
});
//
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43,
EnglishStopWords.getEnglishStopWords());
//
HashMap<String, Long> wordFrequency = new HashMap<>();
for (int wx = 0; wx < bits.length(); ++wx) {
if (bits.get(wx)) {
Document wd = searcher.doc(wx);
//
TokenStream tokenStream = analyzer.tokenStream("temp",
new StringReader(wd.get("content")));
// OffsetAttribute offsetAttribute = tokenStream
// .addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream
.addAttribute(CharTermAttribute.class);
tokenStream.reset();
while (tokenStream.incrementToken()) {
// int startOffset = offsetAttribute.startOffset();
// int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
if (term.length() < 2)
continue;
Long wl;
if ((wl = wordFrequency.get(term)) == null)
wordFrequency.put(term, 1L);
else {
wl += 1;
wordFrequency.put(term, wl);
}
}
tokenStream.end();
tokenStream.close();
}
}
analyzer.close();
// sort
List<String> occurterm = new ArrayList<String>();
for (String ws : wordFrequency.keySet()) {
occurterm.add(String.format("%06d\t%s", wordFrequency.get(ws),
ws));
}
Collections.sort(occurterm, Collections.reverseOrder());
// make query string by top 10 words
int topCount = 10;
for (String ws : occurterm) {
if (topCount-- == 0)
break;
String[] tks = ws.split("\\t");
top10Query += tks[1] + " ";
}
top10Query.trim();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
// return top10 word string
return top10Query;
}
I know this may be stupid question i am gonna put here since i am a complete java noob. may be you guys can help me out to get this problem solved.
I am working on an application where a user would need the result dislayed on jsp page in pdf form, and the pdf is being generated as output stream in HTTP request, means when a user clicks on a button(on jsp) to generate PDF with result i.e. PDF getting generated on fly and sent to client browser.
Using iText, i am able to generate custom generated pdfs on the fly
Heres the Code snippet
public class PdfSample extends HttpServlet {
public PdfSample() {
super();
}
//connection to DB.... code goes here.....
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws javax.servlet.ServletException, java.io.IOException {
DocumentException ex = null;
ByteArrayOutputStream baosPDF = null;
try {
baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("filename_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
resp.setHeader("Cache-Control", "max-age=30");
resp.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
resp.setHeader("Content-disposition", sbContentDispValue.toString());
resp.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = resp.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
} catch (DocumentException dex) {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println(this.getClass().getName() + " caught an exception: "
+ dex.getClass().getName() + "<br>");
writer.println("<pre>");
dex.printStackTrace(writer);
writer.println("</pre>");
} finally {
if (baosPDF != null) {
baosPDF.reset();
}
}
}
protected ByteArrayOutputStream generatePDFDocumentBytes(
final HttpServletRequest req, final ServletContext ctx)
throws DocumentException
{
Document doc = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null;
try {
docWriter = PdfWriter.getInstance(doc, baosPDF);
doc.addAuthor("Sample");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("Sample");
doc.addTitle("Sample Report");
doc.setPageSize(PageSize.LETTER);
doc.open();
String strServerInfo = ctx.getServerInfo();
if (strServerInfo != null) {
}
doc.add(makeHTTPParameterInfoElement(req));
} catch (DocumentException dex) {
baosPDF.reset();
throw dex;
} finally {
if (doc != null) {
doc.close();
}
if (docWriter != null) {
docWriter.close();
}
}
if (baosPDF.size() < 1) {
throw new DocumentException("document has " + baosPDF.size()
+ " bytes");
}
return baosPDF;
}
protected Element makeHTTPParameterInfoElement(final HttpServletRequest req) {
Table tab = null;
tab = makeTable("", "White Color Car", "Black Color Car", "Total");
return (Element) tab;
}
private static Table makeTable(final String firstColumnTitle,
final String secondColumnTitle, final String thirdColumnTitle,
final String fourthColumnTitle) {
Paragraph paragraph, paragraph1;
int val1 = 0;
int val2 = 0;
int val3 = 0;
int val4 = 0;
Table tab = null;
try {
tab = new Table(4);
} catch (BadElementException ex) {
throw new RuntimeException(ex);
}
Cell c = null;
try {
paragraph = new Paragraph("Car Report");
paragraph.setAlignment(1);
c = new Cell(paragraph);
c.setColspan(tab.getColumns());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tab.setBorderWidth(1);
tab.setBorderColor(Color.BLACK);
tab.setPadding(2);
tab.setSpacing(3);
tab.setBackgroundColor(Color.WHITE);
tab.addCell(c);
tab.addCell(new Cell(firstColumnTitle));
tab.addCell(new Cell(secondColumnTitle));
tab.addCell(new Cell(thirdColumnTitle));
tab.addCell(new Cell(fourthColumnTitle));
tab.endHeaders();
String startDate1 = "01/06/2011";
String endDate1 = "11/09/2011";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date startDate = sdf1.parse(startDate1);
Date endDate = sdf1.parse(endDate1);
java.sql.Date sdate = new java.sql.Date(startDate.getTime());
java.sql.Date edate = new java.sql.Date(endDate.getTime());
String newWhiteColor = "select count(*) from .......";
String newBlackColor = "select count(*) from .......";
String totalWhiteColor= "select count(*) from .....";
String totalBlackColor = "select count(*) from .......";
Connection connection = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
PreparedStatement preparedStatement3 = null;
ResultSet resultSet = null;
ResultSet resultSet1 = null;
ResultSet resultSet2 = null;
ResultSet resultSet3 = null;
connection = getSimpleConnection1();
// New Car recently sold out - White Color
preparedStatement = connection
.prepareStatement(newWhiteColor);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
val1 = resultSet.getInt(1);
}
// New Car recently sold out - Black Color
preparedStatement3 = connection
.prepareStatement(newBlackColor);
resultSet3 = preparedStatement3.executeQuery();
while (resultSet3.next()) {
val2 = resultSet3.getInt(1);
}
// Total White Color cars sold out
preparedStatement1 = connection
.prepareStatement(totalWhiteColor);
resultSet1 = preparedStatement1.executeQuery();
while (resultSet1.next()) {
val3 = resultSet1.getInt(1);
}
// Total Black Color cars sold out
preparedStatement2 = connection
.prepareStatement(totalBlackColor);
resultSet2 = preparedStatement2.executeQuery();
while (resultSet2.next()) {
val4 = resultSet2.getInt(1);
}
Integer newWhite = val1;
Integer newBlack = val2;
Integer totalWhite = val3;
Integer totalBlack = val4;
Integer totalNewCars = newWhite + new Black;
Integer totalCars= totalWhite + totalBlack ;
tab.addCell(new Cell("New Cars Sold Out"));
tab.addCell(new Cell(newWhite.toString()));
tab.addCell(new Cell(newBlack.toString()));
tab.addCell(new Cell(totalNewCars.toString()));
tab.addCell(new Cell("Total Cars Sold out"));
tab.addCell(new Cell(totalWhite.toString()));
tab.addCell(new Cell(totalBlack.toString()));
tab.addCell(new Cell(totalCars.toString()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tab;
}
}
The Above code fetching the data (count) from the database by making the connection and displaying in cells. with the above code i am able to create pdf on fly and output as showing below.
--------------------------------------------------------------------------------------------------
Car Report
--------------------------------------------------------------------------------------------------
| White Color Car |Black Color Car | Total
--------------------------------------------------------------------------------------------------
New Cars Sold out| 5 | 8 | 13
--------------------------------------------------------------------------------------------------
Total Cars Sold Out| 6 | 4 | 10
--------------------------------------------------------------------------------------------------
Query 1) How Can I align the car report in Center?
Query 2) Data and text are being displayed inside a cell, how can i set the border of the cell to "0".
Query 3) How can i color a particular cell ( the blank one)?
Query 4) Is it possible to Insert a image on top of the header of the pdf?
Any help would be greatly appreciated !!!!!
Query 1) How Can I align the car report in Center?
Solution : c.setHorizontalAlignment(Element.ALIGN_CENTER);