IDT SDK - getting object - table(s) mapping
Hello,
How do I find out which tables (in data foundation) using object in business layer?
I try open universe business layer (blx) via sdk and get extra tables, but always return empty list.
My code:
public void getMapping() {
SlContext context = null;
IEnterpriseSession enterpriseSession = null;
try {
context = SlContext.create();
enterpriseSession = CrystalEnterprise.getSessionMgr().logon(CMS_LOG_USER, CMS_LOG_PASS, CMS_LOG_HOST, CMS_AUTH_MODE);
context.getService(CmsSessionService.class).setSession(enterpriseSession);
LocalResourceService service = context.getService(LocalResourceService.class);
RelationalBusinessLayer businessLayer = (RelationalBusinessLayer) service.load(BLX_PATH);
RootFolder rootFolder = businessLayer.getRootFolder();
printObjectMapping(rootFolder);
service.close(businessLayer);
} catch (SDKException e) {
System.out.println("Error: " + e.getMessage());
protected static void printObjectMapping(BlItem biItem) {
if (biItem instanceof BusinessObject) {
BusinessObject elem = (BusinessObject) biItem;
RelationalBinding binding = (RelationalBinding) elem.getBinding();
System.out.println("Object " + elem.getName() + " using tables: " + binding.getExtraTables());
if (biItem instanceof BlContainer) {
for (BlItem item : ((BlContainer) biItem).getChildren()) {
printObjectMapping(item);
BO 4.1 SP1
Any ideas?
It is in the com.sap.sl.sdk.authoring.businesslayer package.
You obtain the service as you do the other SL services, with the SlContext.getService() method:
BusinessLayerService blservice = myContext.getService(BusinessLayerService.class);
Like all the other components of the SL SDK, it is referenced by an entry in the manifest of the all-encompassing sl_sdk.jar. We've split (or hacked) this apart to put the individual components into our maven build and the internal jar is com.sap.sl.sdk.authoring.jar. Not sure how you've configured your build but you should be able to find the class.
Hope this helps.
Similar Messages
-
Map.get(Object o) vs Map.get(K k) ?
Hi All,
I hace a question about Map (or may be TreeMap as it comes into my notice whle using TreeMap). I posted it on Collections related forum and got referred here
http://forum.java.sun.com/thread.jspa?threadID=684755
I was wondering why some methods of Map<k,V> specify Object as type for keys used and not the given type K. problem is that following code will throw a ClassCastException
String key="146564";
TreeMap<String, String> map = new TreeMap<String, String>();
map.put(key,key); /*If you uncomment this line you will get Exception*/
map.containsValue(new Long(key)); /*can compile */
map.containsKey(new Long(146564)); /*can compile */
String v = map.get("1");
//map.put(new Long(1), "");/*Can't compile*/
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at java.lang.Long.compareTo(Long.java:34)
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.getEntry(TreeMap.java:347)
at java.util.TreeMap.containsKey(TreeMap.java:204)
atTestClass.main(TestClass.java:27)It is suggested that since I am passing a Long to map.containsKey(), where as Map was declared as Map<String,String> I should expect to get such nasty runtime exceptions. My thinking is 'generics' are specifically designed to avoid such situations.
Can any one let me know why 'generics' are implemented such a way that is not orthognal accross various interfaces? i.e. why is it that I need to remember what instance of a Map was created with key/value pairs of Type A/B and which one with C/D, however if I am using Collection, it will be type checked at comple time? I would either expect to remember it always or to expet it to get type checked at compile time always.This was heavily debated during the evaluation phase. The reason that get(Object) was favoured is basically backwards compatibility: the contract of Map talks only in terms of the equals(Object) method, and for many key types K there can be objects which are not of type K but are equal to a key of type K.
My personal view is that if get(K) introduces problems then you've used the wrong type for K, and your entire design is probably shoddy if there isn't a suitable interface type to use. Moreover, having get(K) would save me probably 5+ hours per year chasing bugs due to calling get (or Collection.contains, which is really the same issue) with the wrong object.
If you really want to compile against get(K), it's fairly straightforward to make a jar with a "fixed" java.util package and use this with javac -bootclasspath. I believe that as long as you don't distribute said jar (and you only need it for compilation, so that's fine) the licence permits this, but IANAL and this is not legal advice. -
IDT SDK - getting connection for DataFoundation table
Hello,
I retrive universe from repository, open local DataFoundation and getting tables.
Now I want to know which connection (repository SI_ID) using each table. Any ideas?
My code:
String localPath = cmsService.retrieveUniverse("MY_UNIVERSE.unx", LOCAL_FOLDER, true);
SlResource loadedRes = localService.load(localPath);
RelationalBusinessLayer businessLayer = (RelationalBusinessLayer) loadedRes;
String localDFPath = businessLayer.getDataFoundationPath();
SlResource resource = localService.load(localDFPath);
DataFoundation dataFoundation = null;
if (resource instanceof MonoSourceDataFoundation) {
dataFoundation = (MonoSourceDataFoundation) resource;
} else if (resource instanceof MultiSourceDataFoundation) {
dataFoundation = (MultiSourceDataFoundation) resource;
List<Table> tables = dataFoundation.getTables();
for (Table table : tables) {
System.out.println("Table: " + table.getName() + " using connection: ????");
BO 4.1 SP3Hi
To check the connection information for IDT universe
To check a secured connection, in the repository resources view, open a session on the repository where the connection is published and The Connection folder or sub folder, double click connection name.
Then check the Server, connection name, Connection Type, Repository Folder, and general information.
Please find the below link.
How to check connection parameters information in IDT -
How to get the List of Database Objects (Table/View) for a given APEX Page.
Hi,
I have an application and that consist of pages like page1,2,3,.....
*1.* I want a report which can give me the list of all the Pages1,2,3,....
I am using the following query to acheive this.... THIS IS FINE..
select a.workspace, a.owner, a.application_name, b.page_id, b.page_name
from apex_applications a,
apex_application_pages b
where a.workspace = b.workspace
and a.application_id = b.application_id*2. Now, I want for each individual page*, the list all the database objects (tables/views), which that page is using.
I am using ALL_DEPENDENCIES , but I am not getting the result.
So, want to know if there any view/table, where I can get the Application Pages & there database object list...
Thanks,
DeepakHari,
Thanks for the response.
The view APEX_APPLICATION_PAGE_DB_ITEMS will only give me the table name related to any Page Items defined to that page..It will not give me all the database objects..
suppose we have a Page, having a report based on multiple tables and there is no Page items defined on that page, we will not have any value in this ....DB_ITEMS table. same thing if we have define some PL|SQL(using some table/view) in a Process, that will not be populated in .....DB_ITEMS table. I want some thing like all the database objects (table/views/function/procedure/.....) for a particular Page ID.
Thanks,
Deepak -
HI Gentlemen,
I needed so badly a JDeveloper/Toplink mapping to object tables. Unfortunately, even the latest version (11g) does not support them; however, according to documentation, there is a solution by means of Java programming. What can I do? If not, how long is it to wait for the next release?
Thank you very much, kind regards from
Dr. Miklos HERBOLY
Software engineerYes,
these are user-defined types including nested tables of NOT ONLY REFs but real objects; arrays and so on. This would be very helpful because pure relational storage requires me to set up a large number of tables.
Suppose, for example, in a medical care record there is an attribute 'psycholgogical treatment' and this has a set of dates associated with it. I am not allowed to restrict the user to say, 5 dates which would yield a non- normalized relational table, rather I have to set up a separate table for the unknown number of dates and a foreign key link to its master table. And this occurs many-many times in different situations with considerably more complex types than just a simple date. However, if I could use a nested table for the date, Oracle would arrange the whole linkage internally and transparently for me, so that I could select the WHOLE treatment record with those nasty dates implied. That's it.
If you have anything for me, I am very grateful to you.
Kind regards from
Miklos -
Map.get(K) and Map.get(Object)
When I first saw the new 2.0 generics compiler, I was very pleased to see that the signature of Map.get() has changed (since 1.3) from:
interface Map<K,V> { V get(Object obj); }to:
interface Map<K,V> { V get(K key); }because it means buggy code like this:
Map<File,Integer> fileSizeMap = new HashMap<File,Integer>();
Integer sizeOfFile = fileSizeMap.get("/tmp/foo");
if (sizeOfFile == null) {
System.err.println("File not found in map");
}(where I have mistakenly called Map.get() with a String rather than a File) will now get a compiler error rather than a fault raised several months after the application has gone live.
So, as I say, I am very pleased with the new signature for Map.get(), although I would also like to see the following methods changed:
boolean containsKey(Object) -> boolean containsKey(K)
boolean containsValue(Object) -> boolean containsValue(V)
V remove(Object object) -> V remove(K)However, I just read on http://cag.lcs.mit.edu/~cananian/Projects/GJ/Bugs/v20/map.html that Neal Gafter says that putting Map.get(K) into 2.0 was a mistake, and that it will be put back to Map.get(Object) in the next version.
I do hope I haven't missed something obvious, but keeping these methods with Object parameters seems to me to be a backwards step from the excellent type safety benefits provided by Generics.
Does anyone else agree with me that having get(K) would be beneficial in allowing the compiler to identify bugs that would otherwise only be discovered much later?
Or, could someone explain to me why having get(Object) is preferable, and whether this reason is more important than the type safety issue I identified in my example code above?
Many thanks in advance
GeoffGafter wrote:
The reason the argument type is Object and not K is that existing code depends on the fact
that passing the "wrong" key type is allowed, causes no error, and simply results in the
key not being found in the map.But "existing code" does not use Generics, and therefore as with all other non-generic code, the authors of that code can choose to either leave it as it is (in which case their Maps will become Map<Object,Object> and Map.get() will then take an Object), or to upgrade it to Generics, and take advantage of the helpful compiler messages that may highlight some design flaws in the original code.
In Jakarta Commons Collections (this is "existing code"), there's a class MultiHashMap which extends HashMap. When you call MultiHashMap.put(someKey, someValue) it appends someValue to an ArrayList that gets stored as the value in the HashMap. However when you call MultiHashMap.get(someKey), it returns a Collection of values, rather than just a single value.
If they try to upgrade MultiHashMap to Generics, they are going to come up with a problem: they would be needing something like this:
public class MultiHashMap<K,V> extends HashMap<K,V> {
public V put(K key, V value) { ... }
public Collection<V> get(K key) { ... }
}which of course is not allowed, since Map<K,V>.get() returns V, not Collection<V>.
Now, I don't hear anyone saying: This "existing code" relies on Map.get() returning an Object, so in Generics we're going to make Map.get() return Object rather than V.
No, instead we (correctly) say: That MultiHashMap code was wrong to abuse the flexibility provided by the use of Object as the return value of Map.get(), and if it wishes to use Generics, it will either need to become MultiHashMap<K,Object>, or if it insists on being MultiHashMap<K,V>, it will not be allowed to extend HashMap.
I really don't see the problem in using Generics (and a typesafe Java Collections API) as a means of highlighting problems in existing code. As I said before, existing code will continue to work as before, because List will become List<Object> and Map will become Map<Object,Object>.
This is no worse than "accidentally" trying to get() with a key of the right
type but the wrong value. Since none of these methods place the key into the
map, it is entirely typesafe to use Object as the method's parameter.Suppose for a moment that when String.endsWith() was first written, it took an Object parameter instead of a String. If I were to say to you: This method needs to change its parameter from Object to String, would you tell me that that there's no need to make the change, because a String can only ever end in a String, and so it is entirely typesafe to use Object as the method's parameter?
Geoff -
I have an application that I would like to map bc4j to a object type hierarchy in the database. From reading previous otn threads I'm under the impression that Domains are not used for Oracle Table Types, just for columns based on oracle types. The thread later goes on to say that for the base type (person_typ) I would map a entity object to the table(person_table) mapped to the base type. To map all the sub-types I would create new entity objects and have PersonEO subclassed into StudentEO and EmployeeEO.
I have done this and it's unclear to me when I subclass PersonEO as StudentEO how do I declare that StudentEO is of oracle object type student_typ?
I'm also having problems with inserting data into the base entity obect. Here's code:
PersonVOImpl personVo = am.getPersonVO();
PersonVORowImpl row = (PersonVORowImpl)personVo.createRow();
personVo.insertRow(row);
row.setName("Mark");
row.setPhone("911");
am.getTransaction().commit();
personVo.executeQuery();
while (personVo.hasNext()){
PersonVORowImpl personRow = (PersonVORowImpl)personVo.next();
The data gets comitted to the db correctly but when the code hits personVo.executeQuery() I get the following error:
oracle.jbo.domain.DataCreationException: JBO-25009: Cannot create an object of type:oracle.sql.STRUCT with value:Mark
at oracle.jbo.domain.TypeFactory.get(TypeFactory.java:687)
at oracle.jbo.domain.TypeFactory.getInstance(TypeFactory.java:80)
at oracle.jbo.server.OracleSQLBuilderImpl.doLoadBulkFromResultSet(OracleSQLBuilderImpl.java:1113)
at oracle.jbo.server.ViewRowImpl.populate(ViewRowImpl.java:2017)
at oracle.jbo.server.ViewDefImpl.createInstanceFromResultSet(ViewDefImpl.java:1013)
at oracle.jbo.server.ViewObjectImpl.createRowFromResultSet(ViewObjectImpl.java:2309)
at oracle.jbo.server.ViewObjectImpl.createInstanceFromResultSet(ViewObjectImpl.java:2240)
at oracle.jbo.server.QueryCollection.populateRow(QueryCollection.java:1698)
at oracle.jbo.server.QueryCollection.fetch(QueryCollection.java:1552)
at oracle.jbo.server.QueryCollection.get(QueryCollection.java:1008)
at oracle.jbo.server.ViewRowSetImpl.getRow(ViewRowSetImpl.java:2791)
at oracle.jbo.server.ViewRowSetIteratorImpl.doFetch(ViewRowSetIteratorImpl.java:2504)
at oracle.jbo.server.ViewRowSetIteratorImpl.ensureRefreshed(ViewRowSetIteratorImpl.java:2368)
at oracle.jbo.server.ViewRowSetIteratorImpl.refresh(ViewRowSetIteratorImpl.java:2569)
at oracle.jbo.server.ViewRowSetImpl.notifyRefresh(ViewRowSetImpl.java:1641)
at oracle.jbo.server.ViewRowSetImpl.execute(ViewRowSetImpl.java:577)
at oracle.jbo.server.ViewRowSetImpl.executeQueryForMasters(ViewRowSetImpl.java:611)
at oracle.jbo.server.ViewRowSetImpl.executeQuery(ViewRowSetImpl.java:593)
at oracle.jbo.server.ViewObjectImpl.executeQuery(ViewObjectImpl.java:2886)
at model.testing.main(testing.java:33)
Am I coding this correctly? I'm using jdev9032 for this. Are there any examples out there on how to correctly use bc4j with oracle object type tables?
Thanks in advance!
-MarkHere is my ddl:
CREATE TYPE Person_typ AS OBJECT
( name VARCHAR2(30),
address VARCHAR2(100)) NOT FINAL
CREATE TABLE PERSON_TABLE OF PERSON_TYP
I map a entity object to person_table one for one and I edit the SYS_NC_OID$ property of updateable to never.
I then map a view object one for one to the entity object. The jbo trace I get when -Djbo.debugoutput=console is declared is the following (omitted everything before the db connected).[156] Successfully logged in
[157] JDBCDriverVersion: 9.0.1.4.0
[158] DatabaseProductName: Oracle
[159] DatabaseProductVersion: Personal Oracle9i Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production
[160] ViewRowSetImpl's jbo.viewlink.consistent = false (0)
[161] Column count: 3
[162] Executing SQL in generateRefAndOID...
[163] select a.oid, make_ref(PERSON_TABLE, a.oid) from (select /*+ NO_MERGE +*/ sys_op_guid() as oid from dual) a
[164] OracleSQLBuilder Executing DML on: PERSON_TABLE (Insert)
[165] INSERT INTO PERSON_TABLE(NAME,ADDRESS) VALUES (:1,:2)
[166] BaseSQLBuilder: releaseSavepoint 'BO_SP' ignored
[167] PersonVO notify COMMIT ...
[168] Column count: 3
[169] ViewObject : Created new QUERY statement
[170] SELECT REF(PersonTable), PersonTable.NAME, PersonTable.ADDRESS FROM PERSON_TABLE PersonTable
[171] LoadBulkFromResultSet failed (2)
oracle.jbo.domain.DataCreationException: JBO-25009: Cannot create an object of type:oracle.sql.STRUCT with value:Mark
java.lang.Object oracle.jbo.domain.TypeFactory.get(java.lang.Class, java.lang.Class, java.lang.Object)
TypeFactory.java:687
java.lang.Object oracle.jbo.domain.TypeFactory.getInstance(java.lang.Class, java.lang.Object)
TypeFactory.java:80
java.lang.Object[] oracle.jbo.server.OracleSQLBuilderImpl.doLoadBulkFromResultSet(oracle.jbo.server.AttributeDefImpl[], int, java.sql.ResultSet, int, oracle.jbo.server.DBTransactionImpl)
OracleSQLBuilderImpl.java:1059
void oracle.jbo.server.ViewRowImpl.populate(java.sql.ResultSet)
ViewRowImpl.java:1964
oracle.jbo.server.ViewRowImpl oracle.jbo.server.ViewDefImpl.createInstanceFromResultSet(oracle.jbo.server.ViewObjectImpl, oracle.jbo.server.QueryCollection, java.sql.ResultSet)
ViewDefImpl.java:1019
oracle.jbo.server.ViewRowImpl oracle.jbo.server.ViewObjectImpl.createRowFromResultSet(java.lang.Object, java.sql.ResultSet)
ViewObjectImpl.java:2035
oracle.jbo.server.ViewRowImpl oracle.jbo.server.ViewObjectImpl.createInstanceFromResultSet(oracle.jbo.server.QueryCollection, java.sql.ResultSet)
ViewObjectImpl.java:1966
oracle.jbo.server.ViewRowImpl oracle.jbo.server.QueryCollection.populateRow()
QueryCollection.java:1395
boolean oracle.jbo.server.QueryCollection.fetch(int)
QueryCollection.java:1237
java.lang.Object oracle.jbo.server.QueryCollection.get(int)
QueryCollection.java:832
oracle.jbo.Row oracle.jbo.server.ViewRowSetImpl.getRow(int)
ViewRowSetImpl.java:2621
void oracle.jbo.server.ViewRowSetIteratorImpl.doFetch(int)
ViewRowSetIteratorImpl.java:2347
void oracle.jbo.server.ViewRowSetIteratorImpl.ensureRefreshed()
ViewRowSetIteratorImpl.java:2211
void oracle.jbo.server.ViewRowSetIteratorImpl.refresh(boolean, boolean)
ViewRowSetIteratorImpl.java:2412
void oracle.jbo.server.ViewRowSetImpl.notifyRefresh(boolean, boolean)
ViewRowSetImpl.java:1556
void oracle.jbo.server.ViewRowSetImpl.execute(boolean, boolean)
ViewRowSetImpl.java:548
void oracle.jbo.server.ViewRowSetImpl.executeQuery()
ViewRowSetImpl.java:564
void oracle.jbo.server.ViewObjectImpl.executeQuery()
ViewObjectImpl.java:2616
void mypackage1.testing.main(java.lang.String[])
testing.java:25
Exception in thread main
Process exited with exit code 1.
Please let me know if you need more information.
-Mark -
Hello all,
I am facing a problem which extracting data thro' EJBQL,
when ever I try this, I get an exception TABLE NOT MAPPED.
Can anyone tell me what exactly is not mapped. Although I am able to store the data in the database thro' EntityManager.persist(Object) method.
I am using jboss-4.0.5 (Hibernate for persistence) and Oracle 9i.
Thanks & Regards,
Varun Narang.HI Jyotika,
This usually happens when you have a lookup table which has more than one display field. You get this error because you have to create an Compound field, which might not be set in the map. In order to create a Compound filed just check wether all the individual fields in the destinations field BankDetails<X,Y,Z>(X,Y,Z are individually mapped) then just right click in any portion on the source fields and select compound filed's, it creates a Bank details field and automatically maps it to the destination fields. Some times it also maps the values; if not you got to manually map it.
I you have any problem please let me know.
Regards,
CHARAN -
InterMedia clipboard: cannot get object view
Hi all.
I'm trying to use clipboard against 8.1.6r2 on Linux.
I've got a table with a primary key column and a BLOB column, and I created the necessary batch of procedures, modified to work with the BLOB column--I'm not using the ORDSYS types. This column will be storing PDFs and Word documents.
I can see the table view, but I can't double-click on the object icon and get an object view. Am I barking up the wrong tree, trying to load Word/PDFs via the clipboard? If not, where I can start looking to fix this problem?
Thanks for info.
-JohnHi,
The interMedia Clipboard is able to recognize multimedia data in object columns only. Furthermore, by default, it recognizes only interMedia objects, like ORDImage, ORDAudio, etc. However, it is possible to use the interMedia Clipboard to handle any object type, providing one 'teaches' it how to handle types it knows nothing about. If you have a table with a simple BLOB column, then you can create a new type to represent the multimedia data in the BLOB column, then create a view on the base table and map the BLOB column into the user-defined type. I've illustrated how to do this in the following example; however, please be aware that this is an undocumented and unsupported feature.
Hope this helps,
Simon
Here's an example of a simple table that holds documents in a BLOB column. If the table is used only to store documents of a single type, then you could skip the MIME type column. If you wanted, you could include a last-modified column and use it to return an appropriate HTTP status if a browser cache contains an up-to-date version.
SQL> create table mydocs ( docid varchar2(32), doc blob, mimetype varchar2(100) );The object type MYDOCSTYPE created below will be used by the Clipboard to recognize the presence of a multimedia data column it can handle.
create or replace type mydoctype as object ( doc blob, mimetype varchar2(100) );
/The MYDOCSVIEW is a view of the base table that uses MYDOCSTYPE to view the document.
create view mydocsview as
select d.docid, mydoctype( d.doc, d.mimetype ) mydoc
from mydocs d;The following 3 PL/SQL procedures are normally generated by the Clipboard Wizard; however, we have to do them by hand because the Clipboard recognizes only the interMedia types.
The MYDOC_INSERT procedure is used by the Clipboard to insert a new row into the MYDOCS table.
create or replace procedure mydocs_insert
( in_docid in varchar2, out_rowid out varchar2 ) as
begin
insert into mydocsview ( docid, mydoc ) values
( in_docid, mydoctype ( null, null ) )
returning rowid into out_rowid;
end;
/The MYDOCS_GET and MYDOCS_PUT are the mediaget and mediaput procedures used by the Web Agent to access the document data.
create or replace procedure mydocs_get
( ord_procedure_path in varchar2, ord_content_type out varchar2,
ord_content_length out number, ord_content_blob out blob ) as
begin
select d.mydoc.mimetype, dbms_lob.getlength( d.mydoc.doc ), d.mydoc.doc
into ord_content_type, ord_content_length, ord_content_blob
from mydocsview d where d.docid = ord_procedure_path;
end;
create or replace procedure mydocs_put
( ord_procedure_path in varchar2,
ord_content_type in varchar2,
ord_content_blob out blob ) as
begin
update mydocsview d set d.mydoc.doc = empty_blob(),
d.mydoc.mimetype = ord_content_type
where docid = ord_procedure_path;
select d.mydoc.doc into ord_content_blob from mydocsview d
where docid = ord_procedure_path for update;
end;
/All the above happens in the user's schema. Now we have to update the Clipboard's metadata in the ORDSYS schema. As before, the Clipboard normally does this, but we have to do it because we're not dealing with an interMedia type.
First tell the Clipboard about the new MYDOCTYPE object type: its in schema SCOTT, its names is MYDOCTYPE, it can hold ANY media data (contrast with IMAGE, AUDIO or VIDEO that are built-in media types the Clipboard knows how to handle), its stored as a BLOB and the BLOB is stored in the .DOC attribute (don't forget the .) of the MYDOCTYPE object type. Note that case is important here for all schema object names.
connect ordsys/ordsys
delete from mw$catalog_by_typ where type_name = 'MYDOCTYPE';
insert into mw$catalog_by_typ values (
'SCOTT', 'MYDOCTYPE', 'ANY', 'BLOB', '.DOC' );
insert into mw$catalog_by_tab values (
'SCOTT', 'MYDOCSVIEW', 'DOCID', 'MYDOCS_INSERT', NULL );
insert into mw$catalog_by_col values (
'SCOTT', 'MYDOCSVIEW', 'MY DOC', 'MYDOCS_GET', 'MYDOCS_PUT', NULL );
commit;Once that's done, you should be able to run the Clipboard, insert new rows into the table, upload new documents, and so forth. Remember to select the view, not the base table when you open the schema in the Clipboard.
null -
How to get the table name in the trigger definition without hard coding.
CREATE TRIGGER db.mytablename
AFTER UPDATE,INSERT
AS
INSERT INTO table1(col1)
SELECT InsRec.col1
FROM
INSERTED Ins
--Below i am calling one sp for which i have to pass the table name
EXEC myspname 'tablename'
In the above trigger,presently i am hard coding the tablename
but is it possible to get the table name dynamically on which the trigger is defined in order to avoid hard coding the table nameI really liked your audit table concept. You inspired me to modify it so that, the entire recordset gets captured and added a couple of other fields. Wanted to share my end result.
USE [YourDB]
GO
/****** Object: Trigger [dbo].[iudt_AutoAuditChanges] Script Date: 10/18/2013 12:49:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[iudt_AutoAuditChanges]
ON [dbo].[YourTable]
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
SET NOCOUNT ON;
Declare @v_AuditID bigint
IF OBJECT_ID('dbo.AutoAudit','U') IS NULL BEGIN
CREATE TABLE [dbo].[AutoAudit]
( [AuditID] bigint identity,
[AuditDate] DateTime,
[AuditUserName] varchar(128),
[TableName] varchar(128) NULL,
[OldContent] XML NULL,
[NewContent] XML NULL
ALTER TABLE dbo.AutoAudit ADD CONSTRAINT
PK_AutoAudit PRIMARY KEY CLUSTERED
[AuditID]
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [idx_AutoAudit_TableName_AuditDate] ON [dbo].[AutoAudit]
( [TableName] ASC,
[AuditDate] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
Select * Into #AuditDeleted from deleted
Select * Into #AuditInserted from inserted
While (Select COUNT(*) from #AuditDeleted) > 0 OR (Select COUNT(*) from #AuditInserted) > 0
Begin
INSERT INTO [dbo].[AutoAudit]
( [AuditDate], [AuditUserName], [TableName], [OldContent], [NewContent])
SELECT
GETDATE(),
SUSER_NAME(),
[TableName]=object_name([parent_obj]),
[OldContent]=CAST((SELECT TOP 1 * FROM #AuditDeleted D FOR XML RAW) AS XML),
[NewContent]=CAST((SELECT TOP 1 * FROM #AuditInserted I FOR XML RAW) AS XML)
FROM sysobjects
WHERE
[xtype] = 'tr'
and [name] = OBJECT_NAME(@@PROCID)
Set @v_AuditID = SCOPE_IDENTITY()
Delete from AutoAudit
Where AuditID = @v_AuditID
AND Convert(varchar(max),oldContent) = Convert(varchar(max),NewContent)
Delete top(1) from #AuditDeleted
Delete top(1) from #AuditInserted
End
END -
IN_WRONG_TABLESPACE, object: table/index
Hi all,
Apologies for the repost of this topic. I have seen it a few times but without resolutions. My problem is as follows.
BR0970W Database administration alert - level: WARNING, type: IN_WRONG_TABLESPACE, object: (index) SAPSR3.D010INC~1, value: PSAPSR346C
BR0970W Database administration alert - level: WARNING, type: IN_WRONG_TABLESPACE, object: (table) SAPSR3.D010L, value: PSAPSR346C
This is IAORA.
TABART
TABSPACE
PCTINC
OFREELIST
OPCTFREE
APPL0
PSAPSR3
0000
1
10
APPL1
PSAPSR3
0000
1
10
APPL2
PSAPSR3
0000
1
10
CLUST
PSAPSR3
0000
1
10
POOL
PSAPSR3
0000
1
10
SDIC
PSAPSR3
0
1
10
SDOCU
PSAPSR3
0000
1
10
SLDEF
PSAPSR346D
0000
1
10
SLEXC
PSAPSR346D
0000
1
10
SLOAD
PSAPSR3
0000
1
10
SPROT
PSAPSR3
0000
1
10
SSDEF
PSAPSR346D
0000
1
10
SSEXC
PSAPSR346D
0000
1
10
SSRC
PSAPSR3
0000
1
10
TEMP
PSAPSR3
0000
1
10
USER
PSAPSR3USR
0000
1
10
USER1
PSAPSR3USR
0000
1
10
This is TAORA.
TABART
TABSPACE
PCTINC
OFREELIST
OFREEGROUP
OPCTFREE
OPCTUSED
APPL0
PSAPSR3
0000
001
01
10
40
APPL1
PSAPSR3
0000
1
1
10
40
APPL2
PSAPSR3
0000
1
1
10
40
CLUST
PSAPSR3
0000
1
1
10
40
POOL
PSAPSR3
0000
1
1
10
40
SDIC
PSAPSR3
0
1
1
10
40
SDOCU
PSAPSR3
0000
1
1
10
40
SLDEF
PSAPSR346D
0000
1
1
10
40
SLEXC
PSAPSR346D
0000
1
1
10
40
SLOAD
PSAPSR3
0000
1
1
10
40
SPROT
PSAPSR3
0000
1
1
10
40
SSDEF
PSAPSR346D
0000
1
1
10
40
SSEXC
PSAPSR346D
0000
1
1
10
40
SSRC
PSAPSR3
0000
1
1
10
40
TEMP
PSAPSR3
0000
1
1
10
40
USER
PSAPSR3USR
0000
1
1
10
40
USER1
PSAPSR3USR
0000
1
1
10
40
select tablespace_name from dba_tablespaces;
SYSTEM,PSAPUNDO,SYSAUX,PSAPTEMP,PSAPSR3,PSAPSR346C,PSAPSR3USR
Tablespace does exist as you can see above now to determine type of tablespace, and as per below query you can see it contains
both data and indexes.
select distinct(segment_type), tablespace_name from dba_segments order by tablespace_name;
SEGMENT_TYPE TABLESPACE_NAME
INDEX PSAPSR3
TABLE PSAPSR3
INDEX PSAPSR346C
TABLE PSAPSR346C
TABLE PSAPSR3USR
TYPE2 UNDO PSAPUNDO
INDEX SYSAUX
INDEX PARTITION SYSAUX
LOB PARTITION SYSAUX
LOBINDEX SYSAUX
LOBSEGMENT SYSAUX
As per note 655162 option 1 and 2 are applicable to me. But as this tablespace seems to be both a data and index tablespace I am thinking I need to create the tablespace entry in IAORA and TAORA.
How would I correctly edit these table entries and which of the following tables might also have to be edited?
DDART and DARTT are used to maintain the classes ( tabarts)
DD09L maps the tables to each class ( tabart)
TAORA/IAORA maps the classes to the tablespaces
TSORA lists the tablespaces.
As a non dba I find the sap note a bit confusing please advise.
Kind Regards,
JohanHi guys,
For clarification:
disp+work information
kernel release 46D
kernel make variant 46D_EXT
DBMS client library OCI_920__OCI_7_API
DBSL shared library version 46D.00
compiled on Linux 2.6.5-7.202.5-smp #1_SMP_Thu_Aug_25_06:20:45_UTC_2005 x86_64
compiled for 64 BIT
compile time Aug 10 2008 21:39:12
update level 0
patch number 2415
source id 0.2415
supported environment
database (SAP, table SVERS) 46A
46B
46C
46D
DBMS server ORACLE 8.0.5..
ORACLE 8.0.6..
ORACLE 8.1.6..
ORACLE 8.1.7..
ORACLE 9.2.0..
ORACLE 10.2.0..
operating system Linux 2.6
System build information:
LCHN :
System components:
ST-PI 2008_1_46C
ST-A/PI 01J_R3_46C
SAP_NOTES 46C
SAP_HR 46C
SAP_BASIS 46C
SAP_APPL 46C
SAP_ABA 46C
Regards,
J -
Nulls from HashMap.get(Object)
I understand that I get the nulls because the Object is not in the map. But is there some elegant way to have it default to the empty String?
Right now, after I grab all my data into variable with HashMap.get(Object), I go and check each once for null, and assign it the empty String instead. This is a lot of lines of code for something that is so basic.
I know i could initialize them all to the empty string, and then for each variable, check the HashMap with containsKey(Object) before assigning with HashMap.get(Object). Now, would I be correct in assuming the compiler would optimize this for me and not actually check the HashMap twice for the same Object? And... even if that is the case, its still just as many lines of code.
Is there perhaps some more elegant way?
String exchange = parameterMap.get("exchange");
String messageType = parameterMap.get("messagetype");
String traderTimeStamp = parameterMap.get("traderTimeStamp");
String exchangeTimeStamp = parameterMap.get("exchangeTimeStamp");
String sequence = parameterMap.get("sequence");
String product = parameterMap.get("product");
String quantity = parameterMap.get("quantity");
String price = parameterMap.get("price");
if (exchange == null)
exchange = "";
if (messageType == null)
messageType = "";
if (traderTimeStamp == null)
traderTimeStamp = "";
if (exchangeTimeStamp == null)
exchangeTimeStamp = "";
if (sequence == null)
sequence = "";
if (product == null)
product = "";
if (quantity == null)
quantity = "";
if (price == null)
price = "";You could first put "" for all potential keys.
Or you could create a helper method
public String nonNull(String s) {
return (s != null) ? s : "";
String exchange = nonNull(parameterMap.get("exchange")); -
Getting the table names in an MS Access database
Hi,
I am new to JDBC and making a client/server application that updates a MS Access database through jdbc:odbc.
I need to get a list of existing user tables in the db. I have found a great document on the net which has the code, however the code doesn't work. I have tried different ways and looked every where with no success. (link to the doco: http://www-128.ibm.com/developerworks/opensource/library/j-jdbc-objects/)
Here is my dbManager class that handles all db related services in my application. I would appreciate any help I can get as I have exhusted all my avenues.
Thanks
Sep,
* dbManager.java
* Created on 31 October 2005, 10:20
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
import java.io.*;
import java.sql.*;
import java.util.regex.*;
* @author AUMahdavSe
public class dbManager {
/** Constant Declaration */
public static final String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final
String sqlCreateTable = "create table TABLENAME (" +
"name varchar (100)," +
"surname varchar(100)," +
"computerType integer," +
"computerNAL varchar(20)," +
"haveMonitor integer," +
"monitorNAL varchar (20)," +
"auditDate varchar(10) );";
public static final String sqlUpdateTable = "insert into TABLENAME values" +
" (NAMEHOLDER, SURNAMEHOLDER, COMPTYPE, COMPNAL, HAVEMON, MONNAL);";
/** Attributes */
private String dbURL = "jdbc:odbc:";
private String Username = "admin"; // user input
private String Password = "purina123"; // user input
private String ODBCDataSource; // config file
private String dbPath; // set through config file or defaults to current folder
private String configFile = "config.txt"; // set either at commandline or defaults to current folder
private Connection con = null;
private Statement stmt = null;
private ResultSet tables;
private DatabaseMetaData dma;
private ResultSetMetaData rsmd;
private String CurrentAuditTable = "TestTable2";
int numCols, i;
/** Set Methodes */
public void setUsername( String usr ) {
this.Username = usr;
public void setPassword( String pswd ) {
this.Password = pswd;
public void setDbPath( String path ) {
this.dbPath = path;
public void setODBCDataSource( String ds ) {
this.ODBCDataSource = ds;
public void setDbURL( String dsname ) {
this.dbURL = this.dbURL + dsname;
/** Get Methodes */
public String getDriver() {
return this.Driver;
// can be run only after a connection obj is setup
public void getMDA() {
try {
this.dma = this.con.getMetaData();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
public void getDBTables() {
//now dump out the names of the tables in the database
String[] types = new String[1];
types[0] = "TABLES"; //set table type mask
//note the %-sign is a wild card (not '*')
try {
this.tables = this.dma.getTables(null, null, "%", types);
dumpResults("--Tables--");
this.tables.close();
//this.listTables();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
// listing tables
/*int count = 0;
int numCols = 0;
//ResultSetMetaData rsmd;
try {
System.out.println("Listing db tables ...");
//this.tables.beforeFirst();
rsmd = this.tables.getMetaData();
numCols = rsmd.getColumnCount();
System.out.println("number of cols: " + numCols);
boolean more = this.tables.first();
System.out.println("this is why: " + more);
while ( more ) {
count++;
for (int i = 1; i <= numCols; i++)
System.out.print( "Table-" + count + " -> " + this.tables.getString(count)+" " );
System.out.println();
more = this.tables.next();
catch ( SQLException ex ) {
System.out.println( "problem listing db tables: " + ex.getMessage() );
/** Other Methodes */
// Initialize the db parameters, like driver, username, passwd, etc.
public void dbInitialize() {
// load configuration from config.txt (dbPath and ODBC Data Source name)
this.loadDbConfig();
// loadDriver
this.loadDriver();
// get username and password for the ODBC from user
this.getDSSecurity();
// populate dbURL, username and password
this.setDbURL( this.ODBCDataSource );
// connect to db
this.dbConnect();
// get db metadata
this.getMDA();
// get a list of tables in db
this.getDBTables();
// load JDBC driver
public void loadDriver() {
try {
Class.forName( getDriver() );
} catch (Exception e) {
System.out.println("Failed to load JDBC/ODBC driver.");
return;
// connects to db and create a Connection obj and a Statement obj
public void dbConnect() {
try {
this.con = DriverManager.getConnection (
this.dbURL,
this.Username,
this.Password);
this.stmt = con.createStatement();
} catch (Exception e) {
System.err.println("problems connecting to "+this.dbURL);
// creates table tblname in db
public void CreateTable( String tblname ) {
try {
String sqlcommand = mergeTblName(sqlCreateTable, tblname);
this.stmt.execute( sqlcommand );
catch (SQLException ex) {
System.err.println("problems with SQL statement sent to "+this.dbURL+
": "+ex.getMessage());
System.out.println("SQL Command: " + mergeTblName(sqlCreateTable, tblname) );
// updates db with new record(s) by executing the SQL query sqlstmt
// and closes db connection
public void dbUpdate( String sqlstmt ) {
try {
// execute SQL commands to create table, insert data
this.stmt.execute( sqlstmt );
this.con.close();
} catch (Exception e) {
System.err.println("problems with SQL sent to "+this.dbURL+
": "+e.getMessage());
// list all user tables in the db
public void listTables() {
//now dump out the names of the tables in the database
int count = 0;
try {
System.out.println("Listing db tables ...");
//this.tables.beforeFirst();
while ( this.tables.next() ) {
count++;
System.out.print( "Table-" + count + " -> " + this.tables.getString(1) );
System.out.println();
catch ( SQLException ex ) {
System.out.println( "problem listing db tables: " + ex.getMessage() );
// checks whether tbname exist in db as a table
// this function has to be called after dbConnect
public boolean tableExists( String tbname ) {
boolean tbexists = false;
//get the database metadata
try {
dma = con.getMetaData();
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
//now dump out the names of the tables in the database
String[] types = new String[1];
types[0] = "TABLES"; //set table type mask
//note the %-sign is a wild card (not '*')
try {
tables = dma.getTables(null, null, "%", types);
catch (SQLException ex) {
System.err.println("database connection: " + ex.getMessage());
try {
while ( tables.next() ) {
if ( tbname.equalsIgnoreCase( tables.getString(1) ) ) {
tbexists = true;
catch ( SQLException ex ) {
System.err.println("database connection: " + ex.getMessage());
return tbexists;
// merge tablename using REGEX
public String mergeTblName( String sqlcommand, String tbname ) {
String REGEX = "TABLENAME";
String INPUT = sqlcommand;
String REPLACE = tbname;
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
INPUT = m.replaceAll(REPLACE);
//System.out.println(INPUT);
return INPUT;
// merge feildnames specific terms using REGEX
public String mergeFldName( Message msg ) {
String sqlcommand;
sqlcommand = "insert into TABLENAME values" +
" ('" + msg.getName() + "', '" + msg.getSurname() + "', " +
msg.getComputerType() + ", '" + msg.getComputerNAL() + "', " +
msg.getHaveMonitor() + ", '" + msg.getMonitorNAL() + "', '" +
msg.getDateOfMsg() + "');";
sqlcommand = mergeTblName( sqlcommand, CurrentAuditTable );
return sqlcommand;
// get users input char
/**public char getChar() {
int i = System.in.read();
while (i != -1) {
// here's your character
char c = (char) i;
i = System.in.read();
return (char) i;
// load the config parameters from config.txt
public void loadDbConfig() {
// make a file obj pointing to the config file config.txt
File configFile = new File( this.configFile );
//...checks on configFile are elided
StringBuffer contents = new StringBuffer();
//declared here only to make visible to finally clause
BufferedReader input = null;
try {
//use buffering
//this implementation reads one line at a time
input = new BufferedReader( new FileReader(configFile) );
String line = null; //not declared within while loop
int count = 0;
while (( line = input.readLine()) != null){
//first line in config file is dbPath
if(count == 0) this.setDbPath( line.trim() );
//second line in config file is ODBCDataSource
if(count == 1) this.setODBCDataSource( line.trim() );
count++;
//contents.append(line);
//contents.append(System.getProperty("line.separator"));
catch (FileNotFoundException ex) {
System.err.println("the file congif.txt cannot be found ...");
System.err.print("Enter the path to db file (e.g. c:\\temp): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the db path from the command-line; need to use try/catch with the
// readLine() method
try {
this.setDbPath( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read user input.");
System.exit(1);
System.err.print("Enter the name of the ODBC Data Source: ");
// read the ODBC Data Source name from the command-line; need to use try/catch with the
// readLine() method
try {
this.setODBCDataSource( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read user input.");
System.exit(1);
ex.printStackTrace();
catch (IOException ex){
//ex.printStackTrace();
finally {
try {
if (input!= null) {
//flush and close both "input" and its underlying FileReader
input.close();
catch (IOException ex) {
//ex.printStackTrace();
//return contents.toString();
// get datasource security details i.e. username and password
public void getDSSecurity() {
// get username
System.out.print("Enter username for the ODBC DataSource: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
this.setUsername( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read username.");
System.exit(1);
// get password
System.out.print("Enter password: ");
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
this.setPassword( br.readLine() );
catch (IOException ioe) {
System.out.println("IO error trying to read password.");
System.exit(1);
private void dumpResults(String head)
//this is a general routine to print out
//column headers and the contents of each column
System.out.println(head);
try
//get the number of columns from the metadata
this.rsmd = this.tables.getMetaData();
numCols = this.rsmd.getColumnCount();
//print out the column names
for (i = 1; i<= numCols; i++)
System.out.print(rsmd.getColumnName(i)+" ");
System.out.println();
//print out the column contents
boolean more = this.tables.next();
while (more)
for (i = 1; i <= numCols; i++)
System.out.print(this.tables.getString(i)+" ");
System.out.println();
more = this.tables.next();
catch(Exception e)
{System.out.println(e.getMessage());}
/** Creates a new instance of dbManager */
public dbManager() {
this.dbInitialize();
}here is the result when I make a new dbManager obj from my server class which is a multithreaded one.
H:\java>java EchoServer
Enter username for the ODBC DataSource: admin
Enter password: purina123
Tables
TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
Listening for clients on 12111...
here is the code of my server class called EchoServer:
import java.net.*;
import java.io.*;
public class EchoServer
ServerSocket m_ServerSocket;
dbManager haDB;
public EchoServer()
// db methods to setup a jdbc connection to the database
haDB = new dbManager();
// list tables
//haDB.listTables();
//haDB.getDBTables();
// create table
//haDB.CreateTable("TestTable2");
// update table
// server code
try
// Create the server socket.
m_ServerSocket = new ServerSocket(12111);
catch(IOException ioe)
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while(true)
try
// Accept incoming connections.
Socket clientSocket = m_ServerSocket.accept();
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests. This is to demonstrate a
// multithreaded server, although not required for such a
// trivial application. Starting a thread also lets our
// EchoServer accept multiple connections simultaneously.
// Start a service thread
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++, haDB);
cliThread.start();
catch(IOException ioe)
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
public static void main (String[] args)
new EchoServer();
class ClientServiceThread extends Thread
Socket m_clientSocket;
int m_clientID = -1;
dbManager m_db;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID, dbManager db)
m_clientSocket = s;
m_clientID = clientID;
m_db = db;
public void run()
// Obtain the input stream and the output stream for the socket
// A good practice is to encapsulate them with a BufferedReader
// and a PrintWriter as shown below.
BufferedReader in = null;
PrintWriter out = null;
Message msg = new Message();
// Print out details of this connection
System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " +
m_clientSocket.getInetAddress().getHostName());
try
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until m_bRunThread is set to false
while(m_bRunThread)
// read incoming stream
String clientCommand = in.readLine();
if ( clientCommand.indexOf(",") != -1 ) {
msg.deserialize( clientCommand );
System.out.println("SQL command: " + m_db.mergeFldName(msg) );
m_db.dbUpdate( m_db.mergeFldName(msg) );
//System.out.println("Name :" + msg.getName() );
//System.out.println("Surname :" + msg.getSurname() );
//System.out.println("ComputerType :" + msg.getComputerType() );
//System.out.println("ComputerNAL :" + msg.getComputerNAL() );
//System.out.println("HaveMonitor :" + msg.getHaveMonitor() );
//System.out.println("Monitor NAL :" + msg.getMonitorNAL() );
//System.out.println("AuditDate :" + msg.getDateOfMsg() );
System.out.println("Client Says :" + clientCommand);
if(clientCommand.equalsIgnoreCase("quit"))
// Special command. Quit this thread
m_bRunThread = false;
System.out.print("Stopping client thread for client : " + m_clientID);
else
// Echo it back to the client.
out.println(clientCommand);
out.flush();
catch(Exception e)
e.printStackTrace();
finally
// Clean up
try
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
catch(IOException ioe)
ioe.printStackTrace();
}I find that taking any problem and reducing it to the simplest thing is the best way to approach it.
Why you had to post all that bloody code (especially since you didn't write it) is beyond me.
This will list all the tables in an Access database (or any other, for that matter):
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
public class TableLister
public static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DATABASE = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String USERNAME = "admin";
public static final String PASSWORD = "";
public static void main(String [] args)
try
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : DATABASE);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
DatabaseMetaData meta = conn.getMetaData();
// Bring back ALL tables and views, including SYSTEM tables.
ResultSet tables = meta.getTables(null, null, null, null);
ResultSetMetaData rsmd = tables.getMetaData();
int numColumns = rsmd.getColumnCount();
List columnNames = new ArrayList();
for (int j = 0; j < numColumns; ++j)
columnNames.add(rsmd.getColumnName(j+1));
Element root = new Element("tables");
int tableCount = 0;
while (tables.next())
Element table = new Element("table");
table.setAttribute("id", Integer.toString(++tableCount));
for (int j = 0; j < numColumns; ++j)
Element column = new Element((String)columnNames.get(j));
column.setText(tables.getString((String)columnNames.get(j)));
table.addContent(column);
root.addContent(table);
conn.close();
Document doc = new Document(root);
XMLOutputter outputter = new XMLOutputter(" ", true);
System.out.println(outputter.outputString(doc));
catch (ClassNotFoundException e)
System.err.println("Couldn't load JDBC driver class");
e.printStackTrace();
catch (SQLException e)
System.err.println("SQL state: " + e.getSQLState());
System.err.println("SQL error: " + e.getErrorCode());
e.printStackTrace();
catch (Exception e)
e.printStackTrace();
}Run it and see if it works for you. If it does, put the essence of the code into your stuff.
% -
Getting Error in java mapping: Parsing empty source. Root element expected!
Hi Experts,
I am using java mapping for schema validation of input message. I have followed all the standard procedures and implemented the java class in the interface mapping.
My interface mapping is like this:
OrderData --->Java Class ---SchemaValidate
Mesg Map ---OrderData_to_BAP --->BAPI Msg
So first I want to validate the schema of the input message. If the input message is invalid then XI should throw an exception. Then I use the actual message mapping to map the input order data to the BAPI input parameters.
In the java code I am using xerces parser.
The java code works fine when I run it as a standalone application.
The interface mapping also works fine if I don't include the java mapping. Ofcourse schema validation does not happen.
But when I test the interface mapping by including the java mapping then I am getting the error:
Call method execute of the application Java mapping SchemaValidate
Java mapping SchemaValidate completed. (execute() of SchemaValidate
com.sap.aii.utilxi.misc.api.BaseRuntimeException: Parsing an empty source. Root element expected!
What am I doing wrong? Why it is not getting the root element?
My Java code is as follows:
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationConstants;
import com.sap.aii.mapping.api.StreamTransformationException;
import java.io.*;
import java.util.Map;
import javax.xml.parsers.*;
import org.xml.sax.helpers.*;
import org.xml.sax.*;
import org.apache.xerces.jaxp.*;
Sample mapper for SAP-XI
@author Gopal
public class SchemaValidate implements StreamTransformation {
//Constants when using XML Schema for SAX parsing.
static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
Injection of mapping parameters
from integration engine
@param map Map with configuration data
public void setParameter(Map map) {
Mapping implementation
@param inputStream Input data from integration engine
@param outputStream Output data to integration engine
public void execute(InputStream inputStream,
OutputStream outputStream)
throws StreamTransformationException {
try {
// obtain an object of class javax.xml.parsers.SAXParser,
SAXParserFactory spf = SAXParserFactoryImpl.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// setup the schema file
sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
sp.setProperty(JAXP_SCHEMA_SOURCE, new File("IOReqMsgSchema.xsd"));
//parse the input xml using the given schema
sp.parse(inputStream, new ParseErrorHandler());
catch(SAXException se) {
se.printStackTrace();
catch ( Exception e ) {
throw new StreamTransformationException( e.getMessage() );
My input message is :
<?xml version="1.0" encoding="UTF-8"?>
<ns0:OrderCreate_request xmlns:ns0="mynamespace">
<ORDER>HTEST1234567</ORDER>
<ORDER_TYPE>z001</ORDER_TYPE>
<ORDER_NAME>Test Order</ORDER_NAME>
<CO_AREA>INTC</CO_AREA>
<CCTR_POSTED>1234567890888888888</CCTR_POSTED>
<CURRENCY>USD</CURRENCY>
<PERSON_RESP>12345679</PERSON_RESP>
</ns0:OrderCreate_request>
Kindly help! please this is urgent!!!!!!
Thanks
Gopal
Edited by: gopalkrishna baliga on Feb 28, 2008 9:34 AMHi Stefan,
I did the code changes to return output stream and the java code works perfectly in standalone mode in my PC.
But when I use the same in the Java mapping with XI then It throws an error "Getting Error in java mapping: Parsing empty source. Root element expected!".
My XI J2EE server has JDK1.4.3.11.
Is there any limitation of using SAX parser in XI? If Yes, then which parser should be used for schema validation in XI?
I have included the XSD file for schema validation along with class files in the .jar file. This jar file is then imported in XI repository. Is the XI engine not able to read the XSD file?
Do I have to handle reading XSD file differently? Any suggession how?
Is this parser error due to some security access?
Kindly help me! I have been struggling with this problem since 2 weeks. I will be greatfull to you if you can help me.
Thanks
Gopal -
How to use error table in mapping level?
Hi all
Any one please tell me how to use error table in mapping level or how to handle the errors in mapping.
I am creating one error table in oracle but i dont know how to use it in mapping.
Thanks in advance.
KumarHi Kumar,
You need to use Error Table along with the Data Rule .
Error tables are used with Logical error handlers (Data Rules). Detailed description on using data rules is explained in the following document
http://www.oracle.com/technology/products/warehouse/pdf/OWB10gR2_ETLandBusinessRules.pdf
In a nut shell usage of error tables is as follows.
1. Create a data rule associate it with a table (Target table or table in which you load data).
2. Use the table in a mapping as target table.
3. Deploy the table and mapping.
Now in the target schema one more table will be created with the name <target table name>_ERR. When a mapping is executed the data which violates the data rule gets into this error table.
The following has to be done to have error table name of customers choice.
1. Right click on the table and click configure.
2. Give the table name in "shadow table name" section.
3. Deploy the table.
4. Use this table in a mapping. Now in the mapping on this table properties in "Error Table Name" section the name of the table specified in "shadow table name" will be populated.
Thanks,
Sutirtha
Maybe you are looking for
-
There is no video when I import a wmv file.
I'm trying to edit a video. When I bring in the wmv file, I can see the picture in teh organizer, but when I bring it into the project, I can "see" the audio in the timeline, but can't view the video in either the timeline or the sceneline.
-
I upgraded my iMac to Yosemite and now I can't print on my Kodak ESP 5250, any ideas?
I downloaded Yosemite to my iMac and I can no longer print to my Kodak ESP 5250. I didn't upgrade my MacBook Air and it still prints fine. Will there be any drivers to fix this problem or can I downgrade back to Mavericks until I get a new printer?
-
Record& playback option in LabVIEW
Dear All, I am trying to develop a Macro Recorder using labVIEW in which i need to listdown(record) all the front panel event change(eg.control data change) and aftersome time using the list it must be played back. I have put all front panel control
-
Internet Sharing stopped working on Mavericks (10.9)
I've used to use my Internet Sharing in my home through my MacBook Pro. Lately, it's not working and sometimes it back to work correctly. But now it's not working with me. I don't know what is the problem! Is there any popular issues with this proble
-
I bought a Apple TV and thought I would use it on one tv but have thought about maybe using on a projector which does noes not have hhdmi but only RCA and VGA