How to copy resultset into object? - java

I am using the following to add retrieved values to the class. all values will be added to attributes of the class but I am using compisition ( have an object of class in the class) and it does not show anything on output.
class employee
{
....
private Address address = new Address();
.....
}
...
Employee emp = new Employee();
try {
ps = con.prepareStatement("select * from employee,address "
+ "WHERE employee.username = ? AND "
+ "employee.ADD_ID = address.ID");
ps.setString(1, username);
ResultSet r = ps.executeQuery();
if (r.next()) {
BeanProcessor bp = new BeanProcessor();
emp = bp.toBean(r,Employee.class);
System.out.println("blockkkk:"+emp.getAddress().getBlock());
//output of above line is blockkkk:null
}
con.close();
ps.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return emp;
Address class is as following:
public class Address {
.....
private String block;
....
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
....
}

The BeanProcessor.toBean works like this:
Convert a ResultSet row into a JavaBean. This implementation uses reflection and BeanInfo classes to match column names to bean property names. Properties are matched to columns based on several factors:
The class has a writable property with the same name as a column. The name comparison is case insensitive.
The column type can be converted to the property's set method parameter type with a ResultSet.get* method. If the conversion fails (ie. the property was an int and the column was a Timestamp) an SQLException is thrown.
Primitive bean properties are set to their defaults when SQL NULL is returned from the ResultSet. Numeric fields are set to 0 and booleans are set to false. Object bean properties are set to null when SQL NULL is returned. This is the same behavior as the ResultSet get* methods.
May be the address is not a writable property. Pls do check it.

public static Object copyFromResultSet(Class clazz, ResultSet resultSet)
{
ArrayList objectArrayList = new ArrayList(1);
try
{
Object object = clazz.newInstance();
objectArrayList.add(object);
copyFromResultSet(objectArrayList, resultSet);
}
catch (Exception e)
{
e.printStackTrace();
}
return objectArrayList.get(0);
}
then:
public static void copyFromResultSet(ArrayList<Object> objectArrayList, ResultSet resultSet)
{
ArrayList arrayList = null;
try
{
if (objectArrayList != null)
{
int objectArrayList_len = objectArrayList.size();
int objectArrayList_index = 0;
java.beans.BeanInfo toBeanInfo[] = new java.beans.BeanInfo[objectArrayList_len];
Vector<Method> objectMethodVector[] = new Vector[objectArrayList_len];
Vector<Type> objectTypeVector[] = new Vector[objectArrayList_len];
int totalMethod[] = new int[objectArrayList_len];
int[][] indexes = new int[objectArrayList_len][];
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
toBeanInfo[objectArrayList_index] = java.beans.Introspector.getBeanInfo(objectArrayList.get(objectArrayList_index).getClass());
}
if (objectArrayList_len > 0 && resultSet != null)
{
Method method = null;
Type type[] = null;
int cols = 0;
String colName = null;
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
//toBeanInfo[objectArrayList_index]=java.beans.Introspector.getBeanInfo(objectArrayList.get(objectArrayList_index).getClass());
java.beans.PropertyDescriptor toPropertyDescriptor[] = toBeanInfo[objectArrayList_index].getPropertyDescriptors();
int toPropertyDescriptor_length = toPropertyDescriptor.length;
method = null;
type = null;
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
cols = resultSetMetaData.getColumnCount();
colName = null;
Vector<Method> methodVector = new Vector(cols);
Vector<Type> typeVector = new Vector(cols);
indexes[objectArrayList_index] = new int[cols];
totalMethod[objectArrayList_index] = -1;
for (int i = 1; i <= cols; i++)
{
colName = resultSetMetaData.getColumnName(i);
for (int j = 0; j < toPropertyDescriptor_length; j++)
{
if (toPropertyDescriptor[j].getName().equalsIgnoreCase(colName))
{
totalMethod[objectArrayList_index]++;
method = toPropertyDescriptor[j].getWriteMethod();
type = method.getGenericParameterTypes();
methodVector.add(method);
typeVector.add(type[0]);
indexes[objectArrayList_index][totalMethod[objectArrayList_index]] = i;
break;
}
}
}
objectMethodVector[objectArrayList_index] = (methodVector);
objectTypeVector[objectArrayList_index] = (typeVector);
}
if (resultSet.next())
{
arrayList = new ArrayList();
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
for (int i = 0; i <= totalMethod[objectArrayList_index]; i++)
{
//System.out.println(objectMethodVector[objectArrayList_index].get(i));
objectMethodVector[objectArrayList_index].get(i).invoke(objectArrayList.get(objectArrayList_index), getObject(indexes[objectArrayList_index][i], objectTypeVector[objectArrayList_index].get(i), resultSet));
}
arrayList.add(objectArrayList.get(objectArrayList_index));
}
}
while (resultSet.next())
{
for (objectArrayList_index = 0; objectArrayList_index < objectArrayList_len; objectArrayList_index++)
{
for (int i = 0; i <= totalMethod[objectArrayList_index]; i++)
{
objectMethodVector[objectArrayList_index].get(i).invoke(objectArrayList.get(objectArrayList_index), getObject(indexes[objectArrayList_index][i], objectTypeVector[objectArrayList_index].get(i), resultSet));
}
arrayList.add(objectArrayList.get(objectArrayList_index));
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
just copy paste this code call method copyFromResultSet(class, ResultSet )
pass two perameters first is class name and second is resultset.
i am sure this is working properlly

Related

Strings can not be converted to DAO Receiver

I am trying to perform batch insertion operation with a list object but while inserting I am getting String cannot be converted to DAO.The receiver in the iterator loop.
I have tried to list the list object, at that time it is printing values from the list. but, when I use generics are normal list it is showing error and I don't find any solution to insert
From this method I am reading the excel file and storing into list
public List collect(Receiver rec)
{
//ReadFromExcel rd = new ReadFromExcel();
List<String> up = new ArrayList<String>();
//List<String> details = rd.reader();
//System.out.println(details);
try( InputStream fileToRead = new FileInputStream(new File(rec.getFilePath())))
{
XSSFWorkbook wb = new XSSFWorkbook(fileToRead);
wb.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
XSSFSheet sheet = wb.getSheetAt(0);
DataFormatter fmt = new DataFormatter();
String data ="";
for(int sn = 0;sn<wb.getNumberOfSheets()-2;sn++)
{
sheet = wb.getSheetAt(sn);
for(int rn =sheet.getFirstRowNum();rn<=sheet.getLastRowNum();rn++)
{
Row row = sheet.getRow(rn);
if(row == null)
{
System.out.println("no data in row ");
}
else
{
for(int cn=0;cn<row.getLastCellNum();cn++)
{
Cell cell = row.getCell(cn);
if(cell == null)
{
// System.out.println("no data in cell ");
// data = data + " " + "|";
}
else
{
String cellStr = fmt.formatCellValue(cell);
data = data + cellStr + "|";
}
}
}
}
}
up = Arrays.asList(data.split("\\|"));
// System.out.println(details);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
Iterator iter = up.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
String row="";
Receiver info = null;
String cid = "";
String cname = "";
String address = "";
String mid = "";
boolean b = false;
List<Receiver> res = new ArrayList<Receiver>();
int c = 0;
try
{
String str = Arrays.toString(up.toArray());
//System.out.println(str);
String s = "";
s = s + str.substring(1,str.length());
// System.out.println("S:"+s);
StringTokenizer sttoken = new StringTokenizer(s,"|");
int count = sttoken.countTokens();
while(sttoken.hasMoreTokens())
{
if(sttoken.nextToken() != null)
{
// System.out.print(sttoken.nextToken());
cid = sttoken.nextToken();
cname = sttoken.nextToken();
address = sttoken.nextToken();
mid = sttoken.nextToken();
info = new Receiver(cid,cname,address,mid);
res.add(info);
System.out.println("cid :"+cid+ " cname : "+cname +" address : "+address+" mid : "+mid);
c = res.size();
// System.out.println(c);
}
else
{
break;
}
}
System.out.println(count);
// System.out.println("s");
}
catch(NoSuchElementException ex)
{
System.out.println("No Such Element Found Exception" +ex);
}
return up;
}
with this method I'm trying to insert into database
public boolean insert(List res)
{
String sqlQuery = "insert into records(c_id) values (?)";
DBConnection connector = new DBConnection();
boolean flag = false;
// Iterator itr=res.iterator();
// while(it.hasNext())
// {
// System.out.println(it.next());
// }
try( Connection con = connector.getConnection();)
{
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(sqlQuery);
Iterator it = res.iterator();
while(it.hasNext())
{
Receiver rs =(Receiver) it.next();
pstmt.setString(1,rs.getcID());
pstmt.setString(2,rs.getcName());
pstmt.setString(3,rs.getAddress());
pstmt.setString(4,rs.getMailID());
pstmt.addBatch();
}
int [] numUpdates=pstmt.executeBatch();
for (int i=0; i < numUpdates.length; i++)
{
if (numUpdates[i] == -2)
{
System.out.println("Execution " + i +": unknown number of rows updated");
flag=false;
}
else
{
System.out.println("Execution " + i + "successful: " + numUpdates[i] + " rows updated");
flag=true;
}
}
con.commit();
} catch(BatchUpdateException b)
{
System.out.println(b);
flag=false;
}
catch (SQLException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
flag=false;
}
return flag;
}
I want to insert list object using JDBC batch insertion to the database.
Your method collect(Receiver rec) returns the List of strings called up.
return up;
However (if you are really using the method collect to pass the List into insert(List res) method), you are expecting this list to contain Receiver objects. Which is incorrect, since it collect(..) returns the list of Strings.
And that causes an error when you try to cast Receiver rs =(Receiver) it.next();
You need to review and fix your code, so you will pass the list of Receiver objects instead of strings.
And I really recommend you to start using Generics wherever you use List class. In this case compiler will show you all data-type errors immediately.

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

Problems with ResultSet Nodes

Quick questions...
I'm trying to make a Dynamic JTree but I can't get to put every database I have into one single node for each one. This is my code so far:
jTree2 = new javax.swing.JTree();
try {
String DSN = "jdbc:mysql://localhost";
String user = "root";
String password = "";
conexion = DriverManager.getConnection(DSN, user, password);
}
catch(Exception e) {
System.out.println("ERROR");
}
try {
sentencia = conexion.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception e) {
System.out.println("ERROR2");
}
try {
String hi = "";
ResultSet rs1 = conexion.getMetaData().getCatalogs();
ResultSetMetaData rsmd = rs1.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++ ) {
hi = hi + rs1.getString(i) + ", ";
}
//for
String sb = hi.substring(0, hi.length()-2);
jTree2.setModel(new FileSystemModel(new File(sb)));
}
}
catch(Exception ae) {
System.out.println("ERROR3");
}
jScrollPane3.setViewportView(jTree2);
And the result I get is this:
Every database is splitted by a "," but I want them to be on a single node for each one. Any help?
This should do it for you:
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases", true);
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rs1.getString(i), true);
parent.add(node);
}
jTree2.setModel(new DefaultTreeModel(parent));
}

How to give Column Name to ResultSet dynamically in this case?

I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}

Business Objects Java

I need help extracting all the file names within a folder in Business Objects. With the code I have now I can get the name of a single file within a folder. I want to get all the file names in that folder. The variable temp is where I enter the name of the file that I want. The variable doc is where the file name is retrieved, and the variable reportname is where I store doc to write to an external spreadsheet.
public class variable {
private static String expressionEx;
private static String nameEx;
private static String nameXE[] = new String[11];
private static String expressionXE[] = new String[11];
private static String query;
public static String reportName;
private static String reportPath;
/** This method writes data to new excel file * */
public static void writeDataToExcelFile(String fileName) {
String[][] excelData = preapreDataToWriteToExcel();// Creates first
// sheet in Excel
String[][] excelData1 = preapreDataToWriteToExcel1();// Creates
// second
// sheet in
// Excel
String[][] excelData2 = preapreDataToWriteToExcel2();// Creates third
// sheet in
// Excel
HSSFWorkbook myReports = new HSSFWorkbook();
HSSFSheet mySheet = myReports.createSheet("Variables");
HSSFSheet mySheet1 = myReports.createSheet("SQL Statement");
HSSFSheet mySheet2 = myReports.createSheet("File Info");
// edits first sheet
mySheet.setFitToPage(true);
mySheet.setHorizontallyCenter(true);
mySheet.setColumnWidth(0, 800 * 6);
mySheet.setColumnWidth(1, 7000 * 6);
// edits second sheet
mySheet1.setFitToPage(true);
mySheet1.setHorizontallyCenter(true);
mySheet1.setColumnWidth(0, 800 * 6);
mySheet1.setColumnWidth(1, 7000 * 6);
// edits third sheet
mySheet2.setFitToPage(true);
mySheet2.setHorizontallyCenter(true);
mySheet2.setColumnWidth(0, 800 * 6);
mySheet2.setColumnWidth(1, 2000 * 6);
HSSFRow myRow = null;
HSSFCell myCell = null;
// first sheet
for (int rowNum = 0; rowNum < excelData[0].length; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// second sheet
for (int rowNum = 0; rowNum < excelData1[0].length; rowNum++) {
myRow = mySheet1.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData1[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// third sheet
for (int rowNum = 0; rowNum < excelData2[0].length; rowNum++) {
myRow = mySheet2.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData2[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static String password;
public static String username;
public static String temp;
public variable() throws FileNotFoundException {
// TODO Auto-generated method stub
IEnterpriseSession oEnterpriseSession = null;
ReportEngines reportEngines = null;
try {
// String cmsname = "det0190bpmsdev3";
// String authenticationType = "secEnterprise";
String cmsname = "";
String authenticationType = "";
// Log in.
oEnterpriseSession = CrystalEnterprise.getSessionMgr().logon(
username, password, cmsname, authenticationType);
if (oEnterpriseSession == null) {
} else {
// Process Document
reportEngines = (ReportEngines) oEnterpriseSession
.getService("ReportEngines");
ReportEngine wiRepEngine = (ReportEngine) reportEngines
.getService(ReportEngines.ReportEngineType.WI_REPORT_ENGINE);
IInfoStore infoStore = (IInfoStore) oEnterpriseSession
.getService("InfoStore");
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and SI_INSTANCE=0 and SI_NAME ='"
+ temp + "'";
IInfoObjects infoObjects = (IInfoObjects) infoStore
.query(query);
for (Object object : infoObjects) {
IInfoObject infoObject = (IInfoObject) object;
String path = getInfoObjectPath(infoObject);
if (path.startsWith("/")) {
DocumentInstance widoc = wiRepEngine
.openDocument(infoObject.getID());
String doc = infoObject.getTitle();
reportPath = path;// this is the path of document
$$$$$$$$$ reportName = doc;// this is the document name
printDocumentVariables(widoc);
purgeQueries(widoc);
widoc.closeDocument();
}
}
// End processing
}
} catch (SDKException sdkEx) {
} finally {
if (reportEngines != null)
reportEngines.close();
if (oEnterpriseSession != null)
oEnterpriseSession.logoff();
}
}
public static void printDocumentVariables(DocumentInstance widoc) {
int i = 0;
// this is the report documents variables
ReportDictionary dic = widoc.getDictionary();
VariableExpression[] variables = dic.getVariables();
for (VariableExpression e : variables) {
nameEx = e.getFormulaLanguageID();
expressionEx = e.getFormula().getValue();
// stores variables in array
nameXE[i] = nameEx;
expressionXE[i] = expressionEx;
i++;
}
}
public static String getInfoObjectPath(IInfoObject infoObject)
throws SDKException {
String path = "";
while (infoObject.getParentID() != 0) {
infoObject = infoObject.getParent();
path = "/" + infoObject.getTitle() + path;
}
return path;
}
#SuppressWarnings("deprecation")
public static void purgeQueries(DocumentInstance widoc) {
DataProviders dps = widoc.getDataProviders();
for (int i = 0; i < dps.getCount(); ++i) {
DataProvider dp = (DataProvider) dps.getItem(i);
if (dp instanceof SQLDataProvider) {
SQLDataProvider sdp = (SQLDataProvider) dp;
sdp.purge(true);
query = sdp.getQuery().getSQL();
}
}
If Temp is going to hold the name of a unique folder, then you can use this code. Replace the String query = line with:
IInfoObjects oParents = infoStore.query("select si_id from ci_infoobjects where si_kind = 'folder' and si_name = '" + temp + "'");
if(oParents.size()==0)
return; // folder name not found
IInfoObject oParent = (IInfoObject)oParents.get(0);
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and si_parentid = " + oParent.getID();
I don't see in the code where you're populating the temp, username, or password variables, but I assume you just left that out of the listing intentionally. Obviously they will need to be defined.
Couple of other things I noticed in your code:
You are purging the query in each report, but not saving the report afterwards.
You are storing the report's SQL in an instance variable named query, but you also have a local variable named query in the variable constructor. This could very likely cause a conflict if you need the SQL value for something.
You have an "empty catch" for SDKException. SDKExceptions can happen for all kinds of reasons, and as it is you will not know why the program failed. You should at least be printing out the exception, or just let it bubble up.

Categories