Collections in Java
How to display data when the out parameter of a pl/sql program
is a collection.
This is what i am doing.
OracleCallableStatement ocstmt = (OracleCallableStatement)
conn.prepareCall("{call test1.get_data(?)}") ;
ocstmt.registerOutParameter(1,
OracleTypes.ARRAY, "CHANNELOBJ") ;
ocstmt.execute() ;
ARRAY array = ocstmt.getARRAY(1);
String str = array.getSQLTypeName();
String str1 = array.getBaseTypeName();
System.out.println(" Length of Array :"+array.length());
System.out.println(str);
System.out.println(str1);
Datum[] values = array.getOracleArray();
for (int i=0;i<values.length;i++)
ChannelObj obj = new ChannelObj();
obj.create(values, OracleTypes.ARRAY);
System.out.println(obj.channel);
System.out.println(obj.languageCode);
System.out.println(obj.profileCode);
System.out.println(obj.cssName);
System.out.println(obj.alwaysLink);
The above thing return null.
Where ChannelObj is a class and is as follows
import java.math.BigDecimal;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleConnection;
import oracle.sql.*;
public class ChannelObj implements CustomDatum,
CustomDatumFactory
static final ChannelObj channelFactory = new ChannelObj(null,
null, null, null, null);
public static CustomDatumFactory getFactory()
return channelFactory;
public ChannelObj()
public ChannelObj(String channel, String languageCode, String
profileCode, String cssName, String alwaysLink)
this.channel = channel;
this.languageCode = languageCode;
this.profileCode = profileCode;
this.cssName = cssName;
this.alwaysLink = alwaysLink;
public ChannelObj(ChannelObj obj)
this.channel = obj.channel;
this.languageCode = obj.languageCode;
this.profileCode = obj.profileCode;
this.cssName = obj.cssName;
this.alwaysLink = obj.alwaysLink;
/* CustomDatum interface */
public Datum toDatum(OracleConnection c) throws SQLException
ArrayDescriptor sd =
ArrayDescriptor.createDescriptor("CHANNELOBJ", c);
Object [] attributes = { channel, languageCode, profileCode,
cssName, alwaysLink };
return new ARRAY(sd, c, attributes);
/* CustomDatumFactory interface */
public CustomDatum create(Datum d, int sqlType) throws
SQLException
if (d == null) return null;
System.out.println("3");
ChannelObj attributes = (ChannelObj)d.toJdbc();
System.out.println("4");
return attributes;
/* fields */
public String channel;
public String languageCode;
public String profileCode;
public String cssName;
public String alwaysLink;
Could anyone point out where am i going wrong or help me some
example of it.
Regards,
Mahesh.
Hi,
Try java.util.Vector
Evan
Similar Messages
-
Hello everyone! I am rather new to the concept of Collections in Java (I have used extensively collections in VB).
I am trying to find how collections in java work, so I used a CASE tool that automatically generates code. I am trying to model the simplest case of a maritime company that owns some ships.
However the code that is generated by this tool can not be compiled in JBuilder. I have two classes one called "Company" and another called "Ship". The code is the following one (the errors that I receive are in the code):
//Company.java
public class Company
public final Set getShips()
if (ships == null)
return java.util.Collections.EMPTY_SET;
return java.util.Collections.unmodifiableSet(ships);
// I GET AN ERROR IN THE FOLLOWING LINE SAYING: "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 31, column 32"
public final void addShips(Ship arg)
if (arg != null)
if (ships == null)
ships = new LinkedHashSet();
if (ships.add(arg))
arg.setCompany(this);
// I GET AN ERROR FOLLOWING LINE : "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 48, column 35"
public final void removeShips(Ship arg)
if (ships != null && arg != null)
if (ships.remove(arg))
arg.setCompany(null);
public Company()
public Set ships;
protected String CName;
//Ship.java
public class Ship
public final Company getCompany()
return company;
public final void setCompany(Company arg)
if (company != arg)
Company temp = company;
company = null;//to avoid infinite recursions
if (temp != null)
temp.removeShips(this);
if (arg != null)
company = arg;
arg.addShips(this);
public Ship()
public Company company;
protected String SName;
protected int NumOfCrew;
protected String TypeOfShip;
} I have read the Java tutorial on collections, but I was wondering if there are any good code samples on Java Collections.
I am after a code sample that implements a relationship 1 to many like one Company has many ships.
Thank you very much for your responses. I am sorry for the long post!First of all, those errors are telling you there's a CLASSPATH problem. You need to compile and run like this:
javac -classpath . *.java
java -classpath . YourMainClassNote the "dot" after "-classpath". That tells the class loader to start looking in the current directory for the .class files it needs.
Read the Sun coding standards for Java:
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
You're using a VB coding standard. Variables should start with a lower case letter (e.g., change NumOfCrew to numOfCrew).
Make that Set of ships private, not public.
You'll have to import java.util.Set and java.util.LinkedHashSet, of course.
Bad idea having two empty constructors. A constructor should leave a class ready to go, fully initialized. I'd rewrite the Company ctor like this:
public Company()
this("", new LinkedHashSet());
public Company(final String companyName, Collection ships)
this.companyName = companyName;
this.ships = new LinkedHashSet(ships);
}Now your collection of ships isn't null, all ready to go. - MOD -
Hi,
I am trying to fetch properties of all lists of "Survey Type" from my site collection in SharePoint 2013 using script editor web part. I am able to fetch properties of one list by mentioning its name explicitly in code but not all survey
list.
My task is to display Survey name , description ,Time created and URLs of all survey lists using java script in script editor web part.
And let me know , if there is any other OOB feature of SharePoint 2013 to achieve the same.
Here is the code :
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
function sharePointReady() {
GetSurveyList();
function GetSurveyList() {
var spListTitle = " List Name";
var clientContext = new SP.ClientContext.get_current();
var oWeb = clientContext.get_web();
this.surveyList = oWeb.get_lists().getByTitle(spListTitle);
clientContext.load(surveyList);
clientContext.executeQueryAsync(Function.createDelegate(this, this.GetListProperties),Function.createDelegate(this, this.onFailure));
function GetListProperties() {
$("#SurveyList").text("");
var surveyTable = "<table border=1>";
surveyTable = surveyTable.concat("<tr><td>Survey Name</td>");
surveyTable = surveyTable.concat("<td>Survey Description</td>");
surveyTable = surveyTable.concat("<td>Time Created</td>");
surveyTable = surveyTable.concat("<tr><td>" + surveyList.get_title() + "</td>");
surveyTable = surveyTable.concat("<td>" + surveyList.get_description() + "</td>");
surveyTable = surveyTable.concat("<td>" + surveyList.get_created().format("MM/dd/yyyy hh:mm tt")+ "</td>");
surveyTable = surveyTable.concat("</table>");
$("#SurveyList").append(surveyTable);
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
</script>
<div id="SurveyList"></div>Shifa,
Please use search result webpart or content query webpart to list all survey list.
Please 'propose as answer' if it helped you, also 'vote helpful' if you like this reply. -
What is the main use of collections in java?
What is the need for choosing collections?
kajbj wrote:
Ohh ... What r u doing in java forum Man.....Stop that. Don't resurrect threads.What's wrong with resurrecting threads?
People are constantly being told to search this forum for information, but that's the same dead information they can find anywhere else on the internet.
So if this forum is to offer something special it's to be able to continued resurrected threads.
You can't have it both ways. Either you discourage people to seach the forum (because it's dead anyway) or you encourage them to do it. If you do you must allow them to resurrect old threads. -
Hi,
In the case of Garbage Collection (GM), if I created a object s in line1, done operation in line2 and made s as null in line3 and after some more execution (may be 10000 lines of code or may running of the prog. for 2 days), I will use same var. s again. Will it will able to work or already Garabage Collected ? Can, I get proper answer ?
bye
RaviGaneshthe object referred to by reference "s" becomes a candidate for garbage collection as soon as the last reference to it is broken. so when you make the reference "s" refer to null, if no other references refer to the originat object, the object can be garbage collected. you are free to assign the reference to other objects at any time (supposing you haven't declared the reference final).
note how careful i was to distinguish "object" from "reference" here. in java, when we say: Object o = new Object();o is the reference, the new Object is the object. if i then say: Object p = o;there are now two references to the initially created object, o and p.
keep in mind the distinction between objects and references to them, and you should be on your way. -
Is it possible to find out what types a Collection contains (java 1.5)
Suppose there is a Collection that is passed as an argument to a function. Well, before doing processing, the types of objects contains in the Collection needs to be know.
So, for instance if
Collection<String> stringCol;Is there a function that I can call that will return String as an object or Class type?
stringCol.getClass() only returns Clas type.However, there is a way if the collection is a member field of a class:
public class Test {
class ListHolder {
List<String> list;
public static void main(String[] args) throws Exception {
//ListHolder not even instantiated
Type lType = ((ParameterizedType)ListHolder.class.getDeclaredField("list").getGenericType()).getActualTypeArguments()[0];
System.out.println(lType);
//or
//ListHolder instantiated but empty
ListHolder lHolder = new ListHolder();
lType = ((ParameterizedType)lHolder.getClass().getDeclaredField("list").getGenericType()).getActualTypeArguments()[0];
System.out.println(lType);
} -
Out of memory in java swing application
Hi,
I am continously getting out of memory in my java application. I collected the java heap dump and found major memory chunk ( >90%) of total java heap is taken by some "class [I", which is array of 'Inetger' objects and sometimes by "class [S", which is array of 'Short' objects.
Elements of these arrays are referred by:
java.awt.image.DataBufferUShort and
sun.awt.image.ShortInterleavedRaster
and these are consuming major memory chunks.
Has anyone observed this kind of problem?
I am not able to proceed in my analysis and kind of struck at these Integer and Short arrays. Please help.
Thanks
CharanjeetSounds like you're retaining a lot of image resources - make sure you're doing the following:
1. flush()ing images once you've used them
2. not retaining references you no longer need
3. not creating duplicate Image objects where not required
4. not creating Image objects which are never needed, or creating a huge pile of images at once when they are not all required at the same time -
Unable to call the RFC from the WD java Program
Hi All,
I have a table and three buttons Create, Edit, Save in the layout.
If no record available in the R3 the the end user will click on create and then he will click on save so that the insert RFC will be called accordingly and the record will be inserted.My table is limited to 5 records only. If i enter all the 5 records and Click on submit the record is inserting in the backend , but if i enter less than 5 records im unable to call the RFC what might be the issue.
My insert RFC takes one Table node and 4 import parameters i'm passing all of the all the mentioned import parameters.
Code:-
View Controller code
// This file has been generated partially by the Web Dynpro Code Generator.
// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.
// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.
package com.gmr.ess;
// IMPORTANT NOTE:
// ALL IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED
// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN
// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateAPPView).
// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY
// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS
// OF IMPORT STATEMENTS.
//@@begin imports
import java.math.BigDecimal;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import com.gmr.ess.wdp.IPrivateAPPView;
import com.gmr.pck.Zst_Hr_Nominee;
import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
import com.sap.tc.webdynpro.services.sal.um.api.IWDClientUser;
import com.sap.tc.webdynpro.services.sal.um.api.WDClientUser;
//@@end
//@@begin documentation
//@@end
public class APPView
Logging location.
private static final com.sap.tc.logging.Location logger =
com.sap.tc.logging.Location.getLocation(APPView.class);
static
//@@begin id
String id = "$Id$";
//@@end
com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);
Private access to the generated Web Dynpro counterpart
for this controller class. </p>
Use <code>wdThis</code> to gain typed access to the context,
to trigger navigation via outbound plugs, to get and enable/disable
actions, fire declared events, and access used controllers and/or
component usages.
@see com.gmr.ess.wdp.IPrivateAPPView for more details
private final IPrivateAPPView wdThis;
Root node of this controller's context. </p>
Provides typed access not only to the elements of the root node
but also to all nodes in the context (methods node<i>XYZ</i>())
and their currently selected element (methods current<i>XYZ</i>Element()).
It also facilitates the creation of new elements for all nodes
(methods create<i>XYZ</i>Element()). </p>
@see com.gmr.ess.wdp.IPrivateAPPView.IContextNode for more details.
private final IPrivateAPPView.IContextNode wdContext;
A shortcut for <code>wdThis.wdGetAPI()</code>. </p>
Represents the generic API of the generic Web Dynpro counterpart
for this controller. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDViewController wdControllerAPI;
A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>
Represents the generic API of the Web Dynpro component this controller
belongs to. Can be used to access the message manager, the window manager,
to add/remove event handlers and so on. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;
public APPView(IPrivateAPPView wdThis)
this.wdThis = wdThis;
this.wdContext = wdThis.wdGetContext();
this.wdControllerAPI = wdThis.wdGetAPI();
this.wdComponentAPI = wdThis.wdGetAPI().getComponent();
//@@begin javadoc:wdDoInit()
/** Hook method called to initialize controller. */
//@@end
public void wdDoInit()
//@@begin wdDoInit()
try{
IWDMessageManager manager1 = wdComponentAPI.getMessageManager();
IWDClientUser user = WDClientUser.getLoggedInClientUser();
String logUser= user.getSAPUser().getUniqueName();
wdContext.currentContextElement().setUserid(logUser);
wdThis.wdGetAPPController().executeBapi_Employee_Getdata_Input();//Returns the user id for the employee
Collection nomineeList = new ArrayList();
wdThis.wdGetAPPController(). executeZ_Hrfm_Nominee_Disp_Input( );
int nomineeTableSize = wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().size();
for(int i=0;i< nomineeTableSize;i++){
IPrivateAPPView.IDisplay_table_nodeElement ele = wdContext.nodeDisplay_table_node().createDisplay_table_nodeElement();
ele.setAddr(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getAddr());
ele.setDob(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getDob());
ele.setGuard(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getGuard());
ele.setName(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getName());
ele.setPerc(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getPerc());
ele.setRelat(wdContext.nodeZ_Hrfm_Nominee_Disp_Input().nodeOutput_Nominee().nodeNominee().getNomineeElementAt(i).getRelat());
nomineeList.add(ele);
wdContext.nodeDisplay_table_node().bind(nomineeList);
wdContext.currentContextElement().setEdit_val_attr(true);
if(nomineeTableSize<=0){
wdContext.currentContextElement().setCreateButtonEnable(true);
wdContext.currentContextElement().setEditButtonEnable(false);
else{
wdContext.currentContextElement().setCreateButtonEnable(false);
wdContext.currentContextElement().setEditButtonEnable(true);
catch(Exception e){
wdComponentAPI.getMessageManager().reportException("",true);
//@@end
//@@begin javadoc:wdDoExit()
/** Hook method called to clean up controller. */
//@@end
public void wdDoExit()
//@@begin wdDoExit()
//@@end
//@@begin javadoc:wdDoModifyView
Hook method called to modify a view just before rendering.
This method conceptually belongs to the view itself, not to the
controller (cf. MVC pattern).
It is made static to discourage a way of programming that
routinely stores references to UI elements in instance fields
for access by the view controller's event handlers, and so on.
The Web Dynpro programming model recommends that UI elements can
only be accessed by code executed within the call to this hook method.
@param wdThis Generated private interface of the view's controller, as
provided by Web Dynpro. Provides access to the view controller's
outgoing controller usages, etc.
@param wdContext Generated interface of the view's context, as provided
by Web Dynpro. Provides access to the view's data.
@param view The view's generic API, as provided by Web Dynpro.
Provides access to UI elements.
@param firstTime Indicates whether the hook is called for the first time
during the lifetime of the view.
//@@end
public static void wdDoModifyView(IPrivateAPPView wdThis, IPrivateAPPView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
//@@begin wdDoModifyView
//@@end
//@@begin javadoc:onActionGetData(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionGetData(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionGetData(ServerEvent)
//$$begin ActionButton(-535519310)
//wdThis.wdGetAPPController().executeZ_Hrfm_Nominee_Disp_Input();
//$$end
//@@end
//@@begin javadoc:onActionEdit(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionEdit(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionEdit(ServerEvent)
//$$begin ActionButton(-535519310)
displayTablesize=wdContext.nodeDisplay_table_node().size();
if(displayTablesize<5){
for(int i=0;i<size-displayTablesize;i++){
IPrivateAPPView.IDisplay_table_nodeElement ele = wdContext.nodeDisplay_table_node().createDisplay_table_nodeElement();
wdContext. nodeDisplay_table_node().addElement(ele);
operation="MOD";
wdContext.currentContextElement().setTableReadOnly(true);
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setOperation(operation);
//$$end
//@@end
//@@begin javadoc:onActionCreate(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionCreate(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionCreate(ServerEvent)
int month=0,year=0,day=0;
String month1,day1,year1;
try{
displayTablesize=wdContext.nodeDisplay_table_node().size();
wdContext.currentContextElement().setEdit_val_attr(false);
if(wdContext.nodeDisplay_table_node().isEmpty()){
if(displayTablesize<5){
Calendar cal=Calendar.getInstance();
month=cal.get(Calendar.MONTH)+1;
if(month==1||month==2||month==3||month==4||month==5||month==6||month==7||month==8||month==9){
month1="0"+month;
else{
month1=""+month;
day = cal.get(Calendar.DAY_OF_MONTH);
if(day==1||day==2||day==3||day==4||day==5||day==6||day==7||day==8||day==9){
day1= "0"+day;
else{
day1=""+day;
year = cal.get(Calendar.YEAR);
year1=""+year;
String strFormat=day1"."month1"."year1;
wdContext.currentOutput_NomineeElement().setBegda(strFormat);
wdContext.currentOutput_NomineeElement().setEndda("31.12.9999");
for(int i=0;i<size-displayTablesize;i++){
IPrivateAPPView.IDisplay_table_nodeElement ele = wdContext.nodeDisplay_table_node().createDisplay_table_nodeElement();
wdContext. nodeDisplay_table_node().addElement(ele);
operation="INS";
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setOperation(operation);
wdContext.currentContextElement().setTableReadOnly(true);
catch(NullPointerException npe){
wdComponentAPI.getMessageManager().reportException("No Data Available",true);
//@@end
//@@begin javadoc:onActionSaveData(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionSaveData(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionSaveData(ServerEvent)
float percentage=0;
float dupePercentage=0;
boolean isTest = false;
Collection DispTList = new ArrayList();
IWDMessageManager manager1 = wdComponentAPI.getMessageManager();
try{
displayTablesize = wdContext.nodeDisplay_table_node().size();
//for(int i=1;i<=displayTablesize;i++){
for(int i=0;i<displayTablesize;i++){
BigDecimal share = wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getPerc();
String name = wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getName();
percentage = share.floatValue();
dupePercentage = dupePercentage + percentage;
if(name!=null && share!=null){
Zst_Hr_Nominee nominee = new Zst_Hr_Nominee();
nominee.setAddr(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getAddr());
manager1.reportSuccess(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getAddr());
nominee.setDob(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getDob());
manager1.reportSuccess(""+wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getDob());
nominee.setGuard(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getGuard());
manager1.reportSuccess(""+wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getGuard());
nominee.setName(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getName());
manager1.reportSuccess(""+wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getName());
nominee.setPerc(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getPerc());
manager1.reportSuccess(""+wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getPerc());
nominee.setRelat(wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getRelat());
manager1.reportSuccess(""+wdContext.nodeDisplay_table_node().getDisplay_table_nodeElementAt(i).getRelat());
DispTList.add(nominee);
wdContext.nodeZ_Hrfm_Nominee_Ins_Mod_Input().nodeNominee_ins().bind(DispTList);
if((dupePercentage)!=100)
wdComponentAPI.getMessageManager().reportException(
"The sum of the share Percentages is not 100. Modify the percentages accordingly",true);
wdContext.nodeZ_Hrfm_Nominee_Ins_Mod_Input().nodeNominee_ins().bind(DispTList);
IWDMessageManager manager = wdComponentAPI.getMessageManager();
String beginDate = wdContext.currentOutput_NomineeElement().getBegda();
manager.reportSuccess(wdContext.currentOutput_NomineeElement().getBegda());
String endDate=wdContext.currentOutput_NomineeElement().getEndda();
manager.reportSuccess(wdContext.currentOutput_NomineeElement().getEndda());
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setBegda(beginDate);
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setEndda(endDate);
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setOperation(operation);
wdComponentAPI.getMessageManager().reportSuccess(operation);
wdThis.wdGetAPPController().executeBapi_Employee_Getdata_Input();
wdThis.wdGetAPPController().executeZ_Hrfm_Nominee_Ins_Mod_Input();
//wdContext.currentContextElement().setTableReadOnly(false);
catch(Exception e){
e.getMessage();
//@@end
The following code section can be used for any Java code that is
not to be visible to other controllers/views or that contains constructs
currently not supported directly by Web Dynpro (such as inner classes or
member variables etc.). </p>
Note: The content of this section is in no way managed/controlled
by the Web Dynpro Designtime or the Web Dynpro Runtime.
//@@begin others
int nomineeTableSize = 0;
int displayTablesize = 0;
String operation= null;
int size=5;
// float dupePercentage=0;
//String mod_op="MOD";
//@@end
content of obsolete user coding area(s) -
//@@begin obsolete:javadoc:onActionSave(ServerEvent)
// /** Declared validating even
Component controller code
// This file has been generated partially by the Web Dynpro Code Generator.
// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.
// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.
package com.gmr.ess;
// IMPORTANT NOTE:
// ALL IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED
// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN
// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateAPP).
// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY
// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS
// OF IMPORT STATEMENTS.
//@@begin imports
import java.util.Iterator;
import com.gmr.ess.wdp.IPrivateAPP;
import com.gmr.pck.Bapi_Employee_Getdata_Input;
import com.gmr.pck.Bapip0002B;
import com.gmr.pck.Z_Hrfm_Nominee_Disp_Input;
import com.gmr.pck.Z_Hrfm_Nominee_Ins_Mod_Input;
import com.gmr.pck.Zst_Hr_Nominee;
import com.sap.lcr.api.util.SetProfileConnect;
import com.sap.tc.webdynpro.modelimpl.dynamicrfc.WDDynamicRFCExecuteException;
import com.sap.tc.webdynpro.progmodel.api.IWDMessageManager;
//@@end
//@@begin documentation
//@@end
public class APP
Logging location.
private static final com.sap.tc.logging.Location logger =
com.sap.tc.logging.Location.getLocation(APP.class);
static
//@@begin id
String id = "$Id$";
//@@end
com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);
Private access to the generated Web Dynpro counterpart
for this controller class. </p>
Use <code>wdThis</code> to gain typed access to the context,
to trigger navigation via outbound plugs, to get and enable/disable
actions, fire declared events, and access used controllers and/or
component usages.
@see com.gmr.ess.wdp.IPrivateAPP for more details
private final IPrivateAPP wdThis;
Root node of this controller's context. </p>
Provides typed access not only to the elements of the root node
but also to all nodes in the context (methods node<i>XYZ</i>())
and their currently selected element (methods current<i>XYZ</i>Element()).
It also facilitates the creation of new elements for all nodes
(methods create<i>XYZ</i>Element()). </p>
@see com.gmr.ess.wdp.IPrivateAPP.IContextNode for more details.
private final IPrivateAPP.IContextNode wdContext;
A shortcut for <code>wdThis.wdGetAPI()</code>. </p>
Represents the generic API of the generic Web Dynpro counterpart
for this controller. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdControllerAPI;
A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>
Represents the generic API of the Web Dynpro component this controller
belongs to. Can be used to access the message manager, the window manager,
to add/remove event handlers and so on. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;
public APP(IPrivateAPP wdThis)
this.wdThis = wdThis;
this.wdContext = wdThis.wdGetContext();
this.wdControllerAPI = wdThis.wdGetAPI();
this.wdComponentAPI = wdThis.wdGetAPI().getComponent();
//@@begin javadoc:wdDoInit()
/** Hook method called to initialize controller. */
//@@end
public void wdDoInit()
//@@begin wdDoInit()
//$$begin Service Controller(1490375209)
// wdContext.nodeZ_Hrfm_Nominee_Ins_Mod_Input().bind(new Z_Hrfm_Nominee_Ins_Mod_Input());
Z_Hrfm_Nominee_Ins_Mod_Input input = new Z_Hrfm_Nominee_Ins_Mod_Input();
input.addNominee(new Zst_Hr_Nominee());
wdContext.nodeZ_Hrfm_Nominee_Ins_Mod_Input().bind(input);
//$$end
//$$begin Service Controller(-932523997)
wdContext.nodeZ_Hrfm_Nominee_Disp_Input().bind(new Z_Hrfm_Nominee_Disp_Input());
//$$end
//$$begin Service Controller(-368783613)
wdContext.nodeBapi_Employee_Getdata_Input().bind(new Bapi_Employee_Getdata_Input());
//$$end
//@@end
//@@begin javadoc:wdDoExit()
/** Hook method called to clean up controller. */
//@@end
public void wdDoExit()
//@@begin wdDoExit()
//@@end
//@@begin javadoc:wdDoPostProcessing()
Hook called to handle data retrieval errors before rendering.
After doModifyView(), the Web Dynpro Framework gets all context data needed
for rendering by validating the contexts (which in turn calls the supply
functions and supplying relation roles). In this hook, the application
should handle the errors which occurred during validation of the contexts.
Using preorder depth-first traversal, this hook is called for all component
controllers starting with the current root component.
Permitted operations:
- Flushing model queue
- Creating messages
- Reading context and model data
Forbidden operations:
- Invalidating model data
- Manipulating the context
- Firing outbound plugs
- Creating components
@param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoPostProcessing(boolean isCurrentRoot)
//@@begin wdDoPostProcessing()
//@@end
//@@begin javadoc:wdDoBeforeNavigation()
Hook before the navigation phase starts.
This hook allows you to flush the model queue and handle any
errors that occur. Firing outbound plugs is allowed in this hook.
Using preorder depth-first traversal, this hook is called for all component
controllers starting with the current root component.
@param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoBeforeNavigation(boolean isCurrentRoot)
//@@begin wdDoBeforeNavigation()
//@@end
//@@begin javadoc:wdDoApplicationStateChange()
Hook that informs the application about a state change.
<p>
This hook is called e.g. to tell the application that will be
<ul>
<li>left via a suspend plug and therefore should go into a suspend/sleep
mode with minimal need of resources. errors that occur. Firing
outbound plugs is allowed in this hook.
<li>left due to a timeout and could write it's state to a data base if the
user comes back later on
</ul>
The concrete reason is available via IWDApplicationStateChangeInfo
<p>
<b>Important</b>: This hook is called for the top level component only!
@param stateChangeInfo contains the information about the nature of the state change
@param stateChangeReturn allows the application to ask for a different state change.
The framework is allowed to ignore it considering i.e. the current resources situation.
//@@end
public void wdDoApplicationStateChange(com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeInfo stateChangeInfo, com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeReturn stateChangeReturn)
//@@begin wdDoApplicationStateChange()
//@@end
//@@begin javadoc:executeBapi_Employee_Getdata_Input()
/** Declared method. */
//@@end
public void executeBapi_Employee_Getdata_Input( )
//@@begin executeBapi_Employee_Getdata_Input()
//$$begin Service Controller(1705750894)
IWDMessageManager manager = wdComponentAPI.getMessageManager();
Iterator itrGetData = null;
Bapip0002B out = null;
try
wdContext.currentBapi_Employee_Getdata_InputElement().modelObject().execute();
wdContext.nodeOutput().invalidate();
itrGetData = wdContext.currentOutputElement().modelObject().getPersonal_Data().iterator();
while (itrGetData.hasNext()) {
out = (Bapip0002B) itrGetData.next();
empNo = out.getPerno();
wdContext.currentZ_Hrfm_Nominee_Disp_InputElement().setPernr(empNo);
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().setPernr(empNo);
// manager.reportSuccess(empNo);
//wdThis.executeZ_Hrfm_Nominee_Disp_Input();
catch(WDDynamicRFCExecuteException e)
manager.reportException(e.getMessage(), false);
//$$end
//@@end
//@@begin javadoc:executeZ_Hrfm_Nominee_Disp_Input()
/** Declared method. */
//@@end
public void executeZ_Hrfm_Nominee_Disp_Input( )
//@@begin executeZ_Hrfm_Nominee_Disp_Input()
//$$begin Service Controller(-366407911)
IWDMessageManager manager = wdComponentAPI.getMessageManager();
try
wdContext.currentZ_Hrfm_Nominee_Disp_InputElement().modelObject().execute();
wdContext.nodeOutput_Nominee().invalidate();
catch(WDDynamicRFCExecuteException e)
manager.reportException(e.getMessage(), false);
//$$end
//@@end
//@@begin javadoc:executeZ_Hrfm_Nominee_Ins_Mod_Input()
/** Declared method. */
//@@end
public void executeZ_Hrfm_Nominee_Ins_Mod_Input( )
//@@begin executeZ_Hrfm_Nominee_Ins_Mod_Input()
//$$begin Service Controller(1524028406)
IWDMessageManager manager = wdComponentAPI.getMessageManager();
try
wdContext.currentZ_Hrfm_Nominee_Ins_Mod_InputElement().modelObject().execute();
wdContext.nodeOutput_nominee_ins_mod().invalidate();
catch(WDDynamicRFCExecuteException e)
manager.reportException(e.getMessage(), false);
//$$end
//@@end
The following code section can be used for any Java code that is
not to be visible to other controllers/views or that contains constructs
currently not supported directly by Web Dynpro (such as inner classes or
member variables etc.). </p>
Note: The content of this section is in no way managed/controlled
by the Web Dynpro Designtime or the Web Dynpro Runtime.
//@@begin others
String empNo = null;
//@@end
Suman
Edited by: sumankumar kurimilla on Dec 23, 2008 9:26 AMHi,
I have checked from RFC side that is working fine only java app its not working can you tell any thing needs to be changed from my application end.
Please check in Savedata action.
Regards,
Suman
Edited by: sumankumar kurimilla on Dec 23, 2008 11:01 AM -
How to make gif-animations from java-midlets?
I have produced a collection of Java animations as midlets.
I am planning to make gif-animations of some of them.
I suppose I can make a gif-picture of every frame of the applet
through coding that myself in the code. Then I could take
those gif-pictures and make an animation of them
with some animation software. Is this a good approach?
If so, what is the best software for doing this?What I need to do is to make color wallpapers. Do you know any better approach for doing this?
-
Using a Collection of beans to store a result set help.
Does anyone have any sample code on the subject? This is something I wrote up, but I wanted feedback, and also an example of how to retreive data out of the array of beans in jsp
package beanpersonal;
import beandatabase.DBConnection;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.Collection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class PersonNew {
public PersonNew() { }
public Collection getPersondata( String alias, String password ) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Collection retValue = new ArrayList();
String query = "SELECT * FROM person WHERE (alias = ?, password = ?)";
try {
conn = DBConnection.getDBConnection();
stmt = conn.prepareStatement( query );
stmt.setString( 1, alias );
stmt.setString( 2, password );
rs = stmt.executeQuery();
while (rs.next()) {
PersonalInfo beanrow = new PersonalInfo();
beanrow.setAlias(rs.getString("alias"));
beanrow.setPassword(rs.getString("password"));
retValue.add(beanrow);
return retValue;
catch( SQLException sqle ) {
//sqle.printStackTrace();
//throw new ApplicationSpecficException("Cannot query db", sqle);
throw new RuntimeException(sqle);
finally {
try {if (rs != null) rs.close();} catch (SQLException e) {}
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}sorry i only view the codes, but don't read it as a whole maybe this codes can help you..
jsp:
<%@ page contentType="text/html;charset=windows-1252"%>
<%@page import="java.util.*,mypackage.TestBean"%>
<%
String name = request.getParameter("name")!=null?request.getParameter("name"):"";
String age = request.getParameter("age")!=null?request.getParameter("age"):"";
System.out.println(name);
System.out.println(age);
Collection col = new ArrayList();
col = (Collection)session.getAttribute("col")!=null?(Collection)session.getAttribute("col"):new ArrayList();
TestBean tBean = new TestBean();
if(!name.equals(""))
tBean.setName(name);
if(!age.equals(""))
tBean.setAge(age);
if(!age.equals("") || !name.equals(""))
col.add(tBean);
session.setAttribute("col",col);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>untitled</title>
</head>
<body>
<form>
<table cellspacing="0" cellpadding="0" border="1" width="200">
<tr>
<td>Name</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input type="text" name="age"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
<%
if(col.size()>0){
Iterator iter = col.iterator();
%>
<table cellspacing="0" cellpadding="0" border="1" width="200">
<tr>
<td>
NAME
</td>
<td>
AGE
</td>
</tr>
<%while(iter.hasNext()){
tBean = (TestBean)iter.next();
%>
<tr>
<td>
<%=tBean.getName()%>
</td>
<td>
<%=tBean.getAge()%>
</td>
</tr>
<%}%>
</table>
<%}%>
</form>
</body>
</html>TestBean.java
package mypackage;
public class TestBean
private String name;
private String age;
public TestBean()
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAge()
return age;
public void setAge(String age)
this.age = age;
} -
Description:
A specific group of users/customers (using Windows7 OS with IE and FireFox web browsers) are facing problems with retrieving the applet File, after they upgraded the JRE on the system(PC) to JRE 1.7.0_25-b17 from JRE version 1.6.0_29-b11.
With JRE 1.7.0_25-b17 it is noticed that when the Java plugin requests for the applet File; it sends a request to the Domain Controller of the user, which causes a delay of 2 to 5 minutes and sometimes hangs. The problem occurs consistently.
The current temporary workaround for this group of users is to use JRE version 1.6.0_29-b11.
Problem analysis:
To investigate the problem the below steps were executed:
1) Collected the Java console outputbelow details from the user's system. (The complete output is not posted due to lengthy content, though can be added further to this post if required.)
(a) Works fine with JRE version 1.6.0_29-b11. Kindly refer to Java console output in the code ‘section A’ towards the end of this post.
(b) The problem occurs with problem with JRE version 1.7.0_25-b17. Kindly refer to Java console output in the code ‘section B’ towards the end of this post. The step where the problem is observed, is indicated as(##<comment>##).
2) The network settings in the user's browser was checked. Internet Options > Connections > LAN setting
The configured option is 'Use automatic configuration script' and the value is http://www.userAppX.com/proxy.pac
This configuration remains the same irrespective of the JRE version in use.
3) The network settings in the Java Control Panel was checked.
The used/selected option is "Use browser settings", although values for 'Use proxy server' and 'use automatic proxy configuration script' are filled-in as 'user-proxy.com' and 'http://www.userAppX.com/proxy.pac' respectively.
This configuration remains the same irrespective of the JRE version in use.
4) The proxy PAC file was checked and debugging was done for the request 'https://myAppletHost.com/download/...'. The FindProxyForUrl function (including the conditions defined in it, for the hostname and domain checks) returns PROXY user-proxy.com:80
5) The user also tried the below
a. Changed the option in the network settings in the browser to 'Proxy server' with Address 'user-proxy.com' and Port '80'
b. Restarted the browser.
c. Tried with Java Plug-in 1.6.0_29, JRE version 1.6.0_29-b11. There was no problem and no request to the Domain Controller of the user.
d. Tried with Java Plug-in 10.40.2.43, JRE version 1.7.0_40-b43. The problem occurs with the delay and a request to the Domain Controller of the user is observed.
Kindly refer to Java console output in the code ‘section C’ towards the end of this post.
6) The user also tried setting the below property in the Java Control panel; restarted the browser, and try with JRE 1.7.0_40-b43. The problem stil persists.
-Djava.net.preferIPv4Stack=true
7) The Global Policy Management of the Domain Controller was verified by the user. It has GPO for proxy setting but nothing related to Java security.
Questions:
The problem seems be specific to a particular (user) environment setup, and the user faces the problem when using JRE 1.7.
We would like to know if the issue is in the (user) environment setup or in JRE 1.7.
Could you please help with information/ideas/suggestions to identify the root cause and solution for this problem?
Section A:
Java Plug-in 1.6.0_29
Using JRE version 1.6.0_29-b11 Java HotSpot(TM) Client VM
User home directory = C:\Users\userA
basic: Plugin2ClassLoader.addURL parent called for https://myAppletHost.com/download/myApplet.jar
network: Connecting https://myAppletHost.com/download/myApplet.jar with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-b1bb5056c5b0e83f=2; Path=/"
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-b1bb5056c5b0e83f=2; Path=/"
security: Loading Root CA certificates from C:\Program Files (x86)\Java\jre6\lib\security\cacerts
security: Loaded Root CA certificates from C:\Program Files (x86)\Java\jre6\lib\security\cacerts
security: Loading SSL Root CA certificates from C:\Program Files (x86)\Java\jre6\lib\security\cacerts
security: Loaded SSL Root CA certificates from C:\Program Files (x86)\Java\jre6\lib\security\cacerts
security: Loading certificates from Deployment session certificate store
security: Loaded certificates from Deployment session certificate store
security: Loading certificates from Internet Explorer ROOT certificate store
security: Loaded certificates from Internet Explorer ROOT certificate store
security: Checking if certificate is in Deployment denied certificate store
network: Connecting https://myAppletHost.com/download/myApplet.jar with cookie "JSESSIONID=0000IK4bEMoqXH10zsl88rwvoRI:175oe9tjd; BCSI-CS-b1bb5056c5b0e83f=2"
network: Downloading resource: https://myAppletHost.com/download/myApplet.jar
Content-Length: 403.293
Content-Encoding: null
Dump system properties ...
https.protocols = TLSv1,SSLv3
java.vm.info = mixed mode, sharing
java.vm.name = Java HotSpot(TM) Client VM
java.vm.specification.name = Java Virtual Machine Specification
java.vm.specification.vendor = Sun Microsystems Inc.
java.vm.specification.version = 1.0
java.vm.vendor = Sun Microsystems Inc.
java.vm.version = 20.4-b02
javaplugin.nodotversion = 160_29
javaplugin.version = 1.6.0_29
javaplugin.vm.options =
os.arch = x86
os.name = Windows 7
os.version = 6.1
trustProxy = true
deployment.proxy.auto.config.url = http://www.userAppX.com/proxy.pac
deployment.proxy.bypass.local = false
deployment.proxy.http.host = user-proxy.com
deployment.proxy.http.port = 80
deployment.proxy.override.hosts =
deployment.proxy.same = false
deployment.proxy.type = 3
deployment.security.SSLv2Hello = false
deployment.security.SSLv3 = true
deployment.security.TLSv1 = true
deployment.security.mixcode = ENABLE
Section B:
Java Plug-in 10.25.2.17
Using JRE version 1.7.0_25-b17 Java HotSpot(TM) Client VM
User home directory = C:\Users\userA
basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@12adac5
basic: Plugin2ClassLoader.addURL parent called for https://myAppletHost.com/download/myApplet.jar
network: Connecting https://myAppletHost.com/download/myApplet.jar with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-2d4ce94a2ae7b460=2; Path=/"
network: Connecting http://10.x.x.xx:53/ with proxy=DIRECT
(##THE ABOVE REQUEST CAUSES THE DELAY OR HANGS##)
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-2d4ce94a2ae7b460=2; Path=/"
security: Loading Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loaded Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loading SSL Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loaded SSL Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loading certificates from Deployment session certificate store
security: Loaded certificates from Deployment session certificate store
security: Loading certificates from Internet Explorer ROOT certificate store
security: Loaded certificates from Internet Explorer ROOT certificate store
network: Connecting https://myAppletHost.com/download/myApplet.jar with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-2d4ce94a2ae7b460=2; Path=/"
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-2d4ce94a2ae7b460=2; Path=/"
network: Connecting https://myAppletHost.com/download/myApplet.jar with cookie "JSESSIONID=0000UQuXWY5tjxjpwcKHlfJKe_8:175oe9j45; BCSI-CS-2d4ce94a2ae7b460=2"
network: ResponseCode for https://myAppletHost.com/download/myApplet.jar : 200
network: Encoding for https://myAppletHost.com/download/myApplet.jar : null
network: Server response: (length: -1, lastModified: Thu Feb xx yy:yy:yy CET 2013, downloadVersion: null, mimeType: text/plain)
network: Downloading resource: https://myAppletHost.com/download/myApplet.jar
Content-Length: -1
Content-Encoding: null
Section C:
Java Plug-in 10.40.2.43
Using JRE version 1.7.0_40-b43 Java HotSpot(TM) Client VM
User home directory = C:\Users\userA
basic: Plugin2ClassLoader.addURL parent called for https://myAppletHost.com/download/myApplet.jar
network: Connecting https://myAppletHost.com/download/myApplet.jar with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-1d67c8b6508ca09c=2; Path=/"
network: Connecting http://10.x.x.xx:53/ with proxy=DIRECT
(##THE ABOVE REQUEST CAUSES THE DELAY OR HANGS##)
network: Checking for update at: https://javadl-esd-secure.oracle.com/update/blacklist
network: Checking for update at: https://javadl-esd-secure.oracle.com/update/blacklisted.certs
network: Checking for update at: https://javadl-esd-secure.oracle.com/update/baseline.version
network: Connecting https://javadl-esd-secure.oracle.com/update/blacklist with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Connecting https://javadl-esd-secure.oracle.com/update/baseline.version with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Connecting https://javadl-esd-secure.oracle.com/update/blacklisted.certs with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
security: Loading Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loaded Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loading SSL Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
security: Loaded SSL Root CA certificates from C:\Program Files (x86)\Java\jre7\lib\security\cacerts
Dump system properties ...
https.protocols = TLSv1,SSLv3
java.vm.info = mixed mode, sharing
java.vm.name = Java HotSpot(TM) Client VM
java.vm.specification.name = Java Virtual Machine Specification
java.vm.specification.vendor = Oracle Corporation
java.vm.specification.version = 1.7
java.vm.vendor = Oracle Corporation
java.vm.version = 24.0-b56
javaplugin.nodotversion = 10402
javaplugin.version = 10.40.2.43
os.arch = x86
os.name = Windows 7
os.version = 6.1
trustProxy = true
active.deployment.proxy.auto.config.url = http://www.userAppX.com/proxy.pac
active.deployment.proxy.bypass.local = false
active.deployment.proxy.http.host = user-proxy.com
active.deployment.proxy.http.port = 80
active.deployment.proxy.same = false
active.deployment.proxy.type = 3
deployment.browser.path = C:\Program Files (x86)\Internet Explorer\iexplore.exe
deployment.proxy.auto.config.url = http://www.userAppX.com/proxy.pac
deployment.proxy.bypass.local = false
deployment.proxy.http.host = user-proxy.com
deployment.proxy.http.port = 80
deployment.proxy.override.hosts =
deployment.proxy.same = false
deployment.proxy.type = 3
deployment.security.SSLv2Hello = false
deployment.security.SSLv3 = true
deployment.security.TLSv1 = true
deployment.security.TLSv1.1 = false
deployment.security.TLSv1.2 = false
deployment.security.authenticator = true
deployment.security.disable = false
deployment.security.level = HIGH
deployment.security.mixcode = ENABLE
PS:
Since the JRE 1.7.0_25-b17 update, it is noticed that when the Java plugin requests for the applet File; it sends a request to the Domain Controller of the user, which causes a delay of 2 to 5 minutes and sometimes hangs.
The problem occurs consistently, and also with JRE 1.7.0_45-b18.
Java Plug-in 10.45.2.18
Using JRE version 1.7.0_45-b18 Java HotSpot(TM) Client VM
User home directory = C:\Users\userA
c: clear console window
f: finalize objects on finalization queue
g: garbage collect
h: display this help message
l: dump classloader list
m: print memory usage
o: trigger logging
q: hide console
r: reload policy configuration
s: dump system and deployment properties
t: dump thread list
v: dump thread stack
x: clear classloader cache
0-5: set trace level to <n>
cache: Initialize resource manager: com.sun.deploy.cache.ResourceProviderImpl@134a33d
basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@1971f66
basic: Plugin2ClassLoader.addURL parent called for https://myAppletHost.com/download/myApplet.jar
network: Connecting https://myAppletHost.com/download/myApplet.jar with proxy=HTTP @ user-proxy.com/194.xxx.xx.xx:80
network: Server https://myAppletHost.com/download/myApplet.jar requesting to set-cookie with "BCSI-CS-f797d4d262467220=2; Path=/"
network: Connecting http://10.x.x.xx:53/ with proxy=DIRECT
network: Connecting http://10.x.x.xx:53/ with proxy=DIRECT
(##THE ABOVE REQUEST CAUSES THE DELAY AND SOMETIMES HANGS##)My organization is experiencing very similar problems. We have resolved it through several steps.
We upgraded the client to Java 8 and we saw in the console that the hanging connection with the Domain Controller no longer occurs. This may be all that is necessary for your environment as well. -
Hi to all.
I have two classes.
The first is:
public class FatherBean implements Serializable {
public String name;
public int id;
/** Creates a new instance of ChildBean */
public FatherBean() {
this.name= null;
this.id = 0;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public int getId() {
return id;
public void setId(int id) {
this.id = id;
The second is :
public class ChildBean extends FatherBean implements Serializable {
public double number;
/** Creates a new instance of ChildBean */
public ChildBean() {
super();
this.number = 0.0;
public double getNumber() {
return number;
public void setNumber(double number) {
this.number = number;
A test client class implements the following method that is exposed as web service:
public java.util.Collection getBeans() {
java.util.Collection beans = new ArrayList();
ChildBean childBean1 = new ChildBean();
ChildBean childBean2 = new ChildBean();
childBean1.setId(100);
childBean1.setName("pippo");
childBean1.setNumber(3.9);
childBean2.setId(100000);
childBean2.setName("pluto");
childBean2.setNumber(4.7);
beans.add(childBean1);
beans.add(childBean2);
return beans;
When I invoke the web service to url:
http://localhost:8080/Prova
and invoke the correspondent method on jsp client, throws exception:
java.rmi.ServerException: Internal Server Error (serialization error: no serializer is registered for (class test.ChildBean, null))
at com.sun.xml.rpc.client.StreamingSender._raiseFault(StreamingSender.java:357)
at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:228)
at ws.ProvaClientGenClient.ProvaRPC_Stub.getBeans(ProvaRPC_Stub.java:59)
at ws.ProvaClientGenClient.getBeans_handler.doAfterBody(getBeans_handler.java:64)
at jasper.getBeans_TAGLIB_jsp._jspService(_getBeans_TAGLIB_jsp.java:121)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.iplanet.ias.web.jsp.JspServlet$JspServletWrapper.service(JspServlet.java:552)
at com.iplanet.ias.web.jsp.JspServlet.serviceJspFile(JspServlet.java:368)
at com.iplanet.ias.web.jsp.JspServlet.service(JspServlet.java:287)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:720)
at org.apache.catalina.core.StandardWrapperValve.access$000(StandardWrapperValve.java:118)
at org.apache.catalina.core.StandardWrapperValve$1.run(StandardWrapperValve.java:278)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:274)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:203)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:157)
at com.iplanet.ias.web.WebContainer.service(WebContainer.java:598)
Where is the problem? Will be ChildBean that extends FatherBean? Wich settings on Sun Java Studio Enterprise 6 2004Q1?
Thank you.Hi,
This forum is for Sun Java Studio Creator related questions. Could you pls post your message in the appropriate forum.
Thank you
Cheers :-) -
hi,
i got error in the following programme in java named dmdemotree.java the code and the error are as mentioned below
i have installed oracle 10g r2 and i have used JDK 1.4.2 softwares , i have set classpath for jdm.jar and ojdm_api.jar available in oracle 10g r2 software ,successfully compiled but at execution stage i got error as
F:\Mallari\DATA MINING demos\java\samples>java dmtreedemo localhost:1521:orcl scott tiger
--- Build Model - using cost matrix ---
javax.datamining.JDMException: Generic Error.
at oracle.dmt.jdm.resource.OraExceptionHandler.createException(OraExcept
ionHandler.java:142)
at oracle.dmt.jdm.resource.OraExceptionHandler.createException(OraExcept
ionHandler.java:91)
at oracle.dmt.jdm.OraDMObject.createException(OraDMObject.java:111)
at oracle.dmt.jdm.base.OraTask.saveObjectInDatabase(OraTask.java:204)
at oracle.dmt.jdm.OraMiningObject.saveObjectInDatabase(OraMiningObject.j
ava:164)
at oracle.dmt.jdm.resource.OraPersistanceManagerImpl.saveObject(OraPersi
stanceManagerImpl.java:245)
at oracle.dmt.jdm.resource.OraConnection.saveObject(OraConnection.java:3
83)
at dmtreedemo.executeTask(dmtreedemo.java:622)
at dmtreedemo.buildModel(dmtreedemo.java:304)
at dmtreedemo.main(dmtreedemo.java:199)
Caused by: java.sql.SQLException: Unsupported feature
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
at oracle.jdbc.dbaccess.DBError.throwUnsupportedFeatureSqlException(DBEr
ror.java:690)
at oracle.jdbc.driver.OracleCallableStatement.setString(OracleCallableSt
atement.java:1337)
at oracle.dmt.jdm.utils.OraSQLUtils.createCallableStatement(OraSQLUtils.
java:126)
at oracle.dmt.jdm.utils.OraSQLUtils.executeCallableStatement(OraSQLUtils
.java:532)
at oracle.dmt.jdm.scheduler.OraProgramJob.createJob(OraProgramJob.java:7
7)
at oracle.dmt.jdm.scheduler.OraJob.saveJob(OraJob.java:107)
at oracle.dmt.jdm.scheduler.OraProgramJob.saveJob(OraProgramJob.java:85)
at oracle.dmt.jdm.scheduler.OraProgramJob.saveJob(OraProgramJob.java:290
at oracle.dmt.jdm.base.OraTask.saveObjectInDatabase(OraTask.java:199)
... 6 more
SO PLZ HELP ME OUT IN THIS , I WILL BE VERY THANK FULL
===========================================================
the sample code is
// Copyright (c) 2004, 2005, Oracle. All rights reserved.
// File: dmtreedemo.java
* This demo program describes how to use the Oracle Data Mining (ODM) Java API
* to solve a classification problem using Decision Tree (DT) algorithm.
* PROBLEM DEFINITION
* How to predict whether a customer responds or not to the new affinity card
* program using a classifier based on DT algorithm?
* DATA DESCRIPTION
* Data for this demo is composed from base tables in the Sales History (SH)
* schema. The SH schema is an Oracle Database Sample Schema that has the customer
* demographics, purchasing, and response details for the previous affinity card
* programs. Data exploration and preparing the data is a common step before
* doing data mining. Here in this demo, the following views are created in the user
* schema using CUSTOMERS, COUNTRIES, and SUPPLIMENTARY_DEMOGRAPHICS tables.
* MINING_DATA_BUILD_V:
* This view collects the previous customers' demographics, purchasing, and affinity
* card response details for building the model.
* MINING_DATA_TEST_V:
* This view collects the previous customers' demographics, purchasing, and affinity
* card response details for testing the model.
* MINING_DATA_APPLY_V:
* This view collects the prospective customers' demographics and purchasing
* details for predicting response for the new affinity card program.
* DATA MINING PROCESS
* Prepare Data:
* 1. Missing Value treatment for predictors
* See dmsvcdemo.java for a definition of missing values, and the steps to be
* taken for missing value imputation. SVM interprets all NULL values for a
* given attribute as "sparse". Sparse data is not suitable for decision
* trees, but it will accept sparse data nevertheless. Decision Tree
* implementation in ODM handles missing predictor values (by penalizing
* predictors which have missing values) and missing target values (by simple
* discarding records with missing target values). We skip missing values
* treatment in this demo.
* 2. Outlier/Clipping treatment for predictors
* See dmsvcdemo.java for a discussion on outlier treatment. For decision
* trees, outlier treatment is not really necessary. We skip outlier treatment
* in this demo.
* 3. Binning high cardinality data
* No data preparation for the types we accept is necessary - even for high
* cardinality predictors. Preprocessing to reduce the cardinality
* (e.g., binning) can improve the performance of the build, but it could
* penalize the accuracy of the resulting model.
* The PrepareData() method in this demo program illustrates the preparation of the
* build, test, and apply data. We skip PrepareData() since the decision tree
* algorithm is very capable of handling data which has not been specially
* prepared. For this demo, no data preparation will be performed.
* Build Model:
* Mining Model is the prime object in data mining. The buildModel() method
* illustrates how to build a classification model using DT algorithm.
* Test Model:
* Classification model performance can be evaluated by computing test
* metrics like accuracy, confusion matrix, lift and ROC. The testModel() or
* computeTestMetrics() method illustrates how to perform a test operation to
* compute various metrics.
* Apply Model:
* Predicting the target attribute values is the prime function of
* classification models. The applyModel() method illustrates how to
* predict the customer response for affinity card program.
* EXECUTING DEMO PROGRAM
* Refer to Oracle Data Mining Administrator's Guide
* for guidelines for executing this demo program.
// Generic Java api imports
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
// Java Data Mining (JDM) standard api imports
import javax.datamining.ExecutionHandle;
import javax.datamining.ExecutionState;
import javax.datamining.ExecutionStatus;
import javax.datamining.JDMException;
import javax.datamining.MiningAlgorithm;
import javax.datamining.MiningFunction;
import javax.datamining.NamedObject;
import javax.datamining.SizeUnit;
import javax.datamining.algorithm.tree.TreeHomogeneityMetric;
import javax.datamining.algorithm.tree.TreeSettings;
import javax.datamining.algorithm.tree.TreeSettingsFactory;
import javax.datamining.base.AlgorithmSettings;
import javax.datamining.base.Model;
import javax.datamining.base.Task;
import javax.datamining.data.AttributeDataType;
import javax.datamining.data.CategoryProperty;
import javax.datamining.data.CategorySet;
import javax.datamining.data.CategorySetFactory;
import javax.datamining.data.ModelSignature;
import javax.datamining.data.PhysicalAttribute;
import javax.datamining.data.PhysicalAttributeFactory;
import javax.datamining.data.PhysicalAttributeRole;
import javax.datamining.data.PhysicalDataSet;
import javax.datamining.data.PhysicalDataSetFactory;
import javax.datamining.data.SignatureAttribute;
import javax.datamining.modeldetail.tree.TreeModelDetail;
import javax.datamining.modeldetail.tree.TreeNode;
import javax.datamining.resource.Connection;
import javax.datamining.resource.ConnectionFactory;
import javax.datamining.resource.ConnectionSpec;
import javax.datamining.rule.Predicate;
import javax.datamining.rule.Rule;
import javax.datamining.supervised.classification.ClassificationApplySettings;
import javax.datamining.supervised.classification.ClassificationApplySettingsFactory;
import javax.datamining.supervised.classification.ClassificationModel;
import javax.datamining.supervised.classification.ClassificationSettings;
import javax.datamining.supervised.classification.ClassificationSettingsFactory;
import javax.datamining.supervised.classification.ClassificationTestMetricOption;
import javax.datamining.supervised.classification.ClassificationTestMetrics;
import javax.datamining.supervised.classification.ClassificationTestMetricsTask;
import javax.datamining.supervised.classification.ClassificationTestMetricsTaskFactory;
import javax.datamining.supervised.classification.ClassificationTestTaskFactory;
import javax.datamining.supervised.classification.ConfusionMatrix;
import javax.datamining.supervised.classification.CostMatrix;
import javax.datamining.supervised.classification.CostMatrixFactory;
import javax.datamining.supervised.classification.Lift;
import javax.datamining.supervised.classification.ReceiverOperatingCharacterics;
import javax.datamining.task.BuildTask;
import javax.datamining.task.BuildTaskFactory;
import javax.datamining.task.apply.DataSetApplyTask;
import javax.datamining.task.apply.DataSetApplyTaskFactory;
// Oracle Java Data Mining (JDM) implemented api imports
import oracle.dmt.jdm.algorithm.tree.OraTreeSettings;
import oracle.dmt.jdm.resource.OraConnection;
import oracle.dmt.jdm.resource.OraConnectionFactory;
import oracle.dmt.jdm.modeldetail.tree.OraTreeModelDetail;
public class dmtreedemo
//Connection related data members
private static Connection m_dmeConn;
private static ConnectionFactory m_dmeConnFactory;
//Object factories used in this demo program
private static PhysicalDataSetFactory m_pdsFactory;
private static PhysicalAttributeFactory m_paFactory;
private static ClassificationSettingsFactory m_clasFactory;
private static TreeSettingsFactory m_treeFactory;
private static BuildTaskFactory m_buildFactory;
private static DataSetApplyTaskFactory m_dsApplyFactory;
private static ClassificationTestTaskFactory m_testFactory;
private static ClassificationApplySettingsFactory m_applySettingsFactory;
private static CostMatrixFactory m_costMatrixFactory;
private static CategorySetFactory m_catSetFactory;
private static ClassificationTestMetricsTaskFactory m_testMetricsTaskFactory;
// Global constants
private static DecimalFormat m_df = new DecimalFormat("##.####");
private static String m_costMatrixName = null;
public static void main( String args[] )
try
if ( args.length != 3 ) {
System.out.println("Usage: java dmsvrdemo <Host name>:<Port>:<SID> <User Name> <Password>");
return;
String uri = args[0];
String name = args[1];
String password = args[2];
// 1. Login to the Data Mining Engine
m_dmeConnFactory = new OraConnectionFactory();
ConnectionSpec connSpec = m_dmeConnFactory.getConnectionSpec();
connSpec.setURI("jdbc:oracle:thin:@"+uri);
connSpec.setName(name);
connSpec.setPassword(password);
m_dmeConn = m_dmeConnFactory.getConnection(connSpec);
// 2. Clean up all previuosly created demo objects
clean();
// 3. Initialize factories for mining objects
initFactories();
m_costMatrixName = createCostMatrix();
// 4. Build model with supplied cost matrix
buildModel();
// 5. Test model - To compute accuracy and confusion matrix, lift result
// and ROC for the model from apply output data.
// Please see dnnbdemo.java to see how to test the model
// with a test input data and cost matrix.
// Test the model with cost matrix
computeTestMetrics("DT_TEST_APPLY_OUTPUT_COST_JDM",
"dtTestMetricsWithCost_jdm", m_costMatrixName);
// Test the model without cost matrix
computeTestMetrics("DT_TEST_APPLY_OUTPUT_JDM",
"dtTestMetrics_jdm", null);
// 6. Apply the model
applyModel();
} catch(Exception anyExp) {
anyExp.printStackTrace(System.out);
} finally {
try {
//6. Logout from the Data Mining Engine
m_dmeConn.close();
} catch(Exception anyExp1) { }//Ignore
* Initialize all object factories used in the demo program.
* @exception JDMException if factory initalization failed
public static void initFactories() throws JDMException
m_pdsFactory = (PhysicalDataSetFactory)m_dmeConn.getFactory(
"javax.datamining.data.PhysicalDataSet");
m_paFactory = (PhysicalAttributeFactory)m_dmeConn.getFactory(
"javax.datamining.data.PhysicalAttribute");
m_clasFactory = (ClassificationSettingsFactory)m_dmeConn.getFactory(
"javax.datamining.supervised.classification.ClassificationSettings");
m_treeFactory = (TreeSettingsFactory) m_dmeConn.getFactory(
"javax.datamining.algorithm.tree.TreeSettings");
m_buildFactory = (BuildTaskFactory)m_dmeConn.getFactory(
"javax.datamining.task.BuildTask");
m_dsApplyFactory = (DataSetApplyTaskFactory)m_dmeConn.getFactory(
"javax.datamining.task.apply.DataSetApplyTask");
m_testFactory = (ClassificationTestTaskFactory)m_dmeConn.getFactory(
"javax.datamining.supervised.classification.ClassificationTestTask");
m_applySettingsFactory = (ClassificationApplySettingsFactory)m_dmeConn.getFactory(
"javax.datamining.supervised.classification.ClassificationApplySettings");
m_costMatrixFactory = (CostMatrixFactory)m_dmeConn.getFactory(
"javax.datamining.supervised.classification.CostMatrix");
m_catSetFactory = (CategorySetFactory)m_dmeConn.getFactory(
"javax.datamining.data.CategorySet" );
m_testMetricsTaskFactory = (ClassificationTestMetricsTaskFactory)m_dmeConn.getFactory(
"javax.datamining.supervised.classification.ClassificationTestMetricsTask");
* This method illustrates how to build a mining model using the
* MINING_DATA_BUILD_V dataset and classification settings with
* DT algorithm.
* @exception JDMException if model build failed
public static void buildModel() throws JDMException
System.out.println("---------------------------------------------------");
System.out.println("--- Build Model - using cost matrix ---");
System.out.println("---------------------------------------------------");
// 1. Create & save PhysicalDataSpecification
PhysicalDataSet buildData =
m_pdsFactory.create("MINING_DATA_BUILD_V", false);
PhysicalAttribute pa = m_paFactory.create("CUST_ID",
AttributeDataType.integerType, PhysicalAttributeRole.caseId );
buildData.addAttribute(pa);
m_dmeConn.saveObject("treeBuildData_jdm", buildData, true);
//2. Create & save Mining Function Settings
// Create tree algorithm settings
TreeSettings treeAlgo = m_treeFactory.create();
// By default, tree algorithm will have the following settings:
// treeAlgo.setBuildHomogeneityMetric(TreeHomogeneityMetric.gini);
// treeAlgo.setMaxDepth(7);
// ((OraTreeSettings)treeAlgo).setMinDecreaseInImpurity(0.1, SizeUnit.percentage);
// treeAlgo.setMinNodeSize( 0.05, SizeUnit.percentage );
// treeAlgo.setMinNodeSize( 10, SizeUnit.count );
// ((OraTreeSettings)treeAlgo).setMinDecreaseInImpurity(20, SizeUnit.count);
// Set cost matrix. A cost matrix is used to influence the weighting of
// misclassification during model creation (and scoring).
// See Oracle Data Mining Concepts Guide for more details.
String costMatrixName = m_costMatrixName;
// Create ClassificationSettings
ClassificationSettings buildSettings = m_clasFactory.create();
buildSettings.setAlgorithmSettings(treeAlgo);
buildSettings.setCostMatrixName(costMatrixName);
buildSettings.setTargetAttributeName("AFFINITY_CARD");
m_dmeConn.saveObject("treeBuildSettings_jdm", buildSettings, true);
// 3. Create, save & execute Build Task
BuildTask buildTask = m_buildFactory.create(
"treeBuildData_jdm", // Build data specification
"treeBuildSettings_jdm", // Mining function settings name
"treeModel_jdm" // Mining model name
buildTask.setDescription("treeBuildTask_jdm");
executeTask(buildTask, "treeBuildTask_jdm");
//4. Restore the model from the DME and explore the details of the model
ClassificationModel model =
(ClassificationModel)m_dmeConn.retrieveObject(
"treeModel_jdm", NamedObject.model);
// Display model build settings
ClassificationSettings retrievedBuildSettings =
(ClassificationSettings)model.getBuildSettings();
if(buildSettings == null)
System.out.println("Failure to restore build settings.");
else
displayBuildSettings(retrievedBuildSettings, "treeBuildSettings_jdm");
// Display model signature
displayModelSignature((Model)model);
// Display model detail
TreeModelDetail treeModelDetails = (TreeModelDetail) model.getModelDetail();
displayTreeModelDetailsExtensions(treeModelDetails);
* Create and save cost matrix.
* Consider an example where it costs $10 to mail a promotion to a
* prospective customer and if the prospect becomes a customer, the
* typical sale including the promotion, is worth $100. Then the cost
* of missing a customer (i.e. missing a $100 sale) is 10x that of
* incorrectly indicating that a person is good prospect (spending
* $10 for the promo). In this case, all prediction errors made by
* the model are NOT equal. To act on what the model determines to
* be the most likely (probable) outcome may be a poor choice.
* Suppose that the probability of a BUY reponse is 10% for a given
* prospect. Then the expected revenue from the prospect is:
* .10 * $100 - .90 * $10 = $1.
* The optimal action, given the cost matrix, is to simply mail the
* promotion to the customer, because the action is profitable ($1).
* In contrast, without the cost matrix, all that can be said is
* that the most likely response is NO BUY, so don't send the
* promotion. This shows that cost matrices can be very important.
* The caveat in all this is that the model predicted probabilities
* may NOT be accurate. For binary targets, a systematic approach to
* this issue exists. It is ROC, illustrated below.
* With ROC computed on a test set, the user can see how various model
* predicted probability thresholds affect the action of mailing a promotion.
* Suppose I promote when the probability to BUY exceeds 5, 10, 15%, etc.
* what return can I expect? Note that the answer to this question does
* not rely on the predicted probabilities being accurate, only that
* they are in approximately the correct rank order.
* Assuming that the predicted probabilities are accurate, provide the
* cost matrix table name as input to the RANK_APPLY procedure to get
* appropriate costed scoring results to determine the most appropriate
* action.
* In this demo, we will create the following cost matrix
* ActualTarget PredictedTarget Cost
* 0 0 0
* 0 1 1
* 1 0 8
* 1 1 0
private static String createCostMatrix() throws JDMException
String costMatrixName = "treeCostMatrix";
// Create categorySet
CategorySet catSet = m_catSetFactory.create(AttributeDataType.integerType);
// Add category values
catSet.addCategory(new Integer(0), CategoryProperty.valid);
catSet.addCategory(new Integer(1), CategoryProperty.valid);
// Create cost matrix
CostMatrix costMatrix = m_costMatrixFactory.create(catSet);
// ActualTarget PredictedTarget Cost
costMatrix.setValue(new Integer(0), new Integer(0), 0);
costMatrix.setValue(new Integer(0), new Integer(1), 1);
costMatrix.setValue(new Integer(1), new Integer(0), 8);
costMatrix.setValue(new Integer(1), new Integer(1), 0);
//save cost matrix
m_dmeConn.saveObject(costMatrixName, costMatrix, true);
return costMatrixName;
* This method illustrates how to compute test metrics using
* an apply output table that has actual and predicted target values. Here the
* apply operation is done on the MINING_DATA_TEST_V dataset. It creates
* an apply output table with actual and predicted target values. Using
* ClassificationTestMetricsTask test metrics are computed. This produces
* the same test metrics results as ClassificationTestTask.
* @param applyOutputName apply output table name
* @param testResultName test result name
* @param costMatrixName table name of the supplied cost matrix
* @exception JDMException if model test failed
public static void computeTestMetrics(String applyOutputName,
String testResultName, String costMatrixName) throws JDMException
if (costMatrixName != null) {
System.out.println("---------------------------------------------------");
System.out.println("--- Test Model - using apply output table ---");
System.out.println("--- - using cost matrix table ---");
System.out.println("---------------------------------------------------");
else {
System.out.println("---------------------------------------------------");
System.out.println("--- Test Model - using apply output table ---");
System.out.println("--- - using no cost matrix table ---");
System.out.println("---------------------------------------------------");
// 1. Do the apply on test data to create an apply output table
// Create & save PhysicalDataSpecification
PhysicalDataSet applyData =
m_pdsFactory.create( "MINING_DATA_TEST_V", false );
PhysicalAttribute pa = m_paFactory.create("CUST_ID",
AttributeDataType.integerType, PhysicalAttributeRole.caseId );
applyData.addAttribute( pa );
m_dmeConn.saveObject( "treeTestApplyData_jdm", applyData, true );
// 2 Create & save ClassificationApplySettings
ClassificationApplySettings clasAS = m_applySettingsFactory.create();
HashMap sourceAttrMap = new HashMap();
sourceAttrMap.put( "AFFINITY_CARD", "AFFINITY_CARD" );
clasAS.setSourceDestinationMap( sourceAttrMap );
m_dmeConn.saveObject( "treeTestApplySettings_jdm", clasAS, true);
// 3 Create, store & execute apply Task
DataSetApplyTask applyTask = m_dsApplyFactory.create(
"treeTestApplyData_jdm",
"treeModel_jdm",
"treeTestApplySettings_jdm",
applyOutputName);
if(executeTask(applyTask, "treeTestApplyTask_jdm"))
// Compute test metrics on new created apply output table
// 4. Create & save PhysicalDataSpecification
PhysicalDataSet applyOutputData = m_pdsFactory.create(
applyOutputName, false );
applyOutputData.addAttribute( pa );
m_dmeConn.saveObject( "treeTestApplyOutput_jdm", applyOutputData, true );
// 5. Create a ClassificationTestMetricsTask
ClassificationTestMetricsTask testMetricsTask =
m_testMetricsTaskFactory.create( "treeTestApplyOutput_jdm", // apply output data used as input
"AFFINITY_CARD", // actual target column
"PREDICTION", // predicted target column
testResultName // test metrics result name
testMetricsTask.computeMetric( // enable confusion matrix computation
ClassificationTestMetricOption.confusionMatrix, true );
testMetricsTask.computeMetric( // enable lift computation
ClassificationTestMetricOption.lift, true );
testMetricsTask.computeMetric( // enable ROC computation
ClassificationTestMetricOption.receiverOperatingCharacteristics, true );
testMetricsTask.setPositiveTargetValue( new Integer(1) );
testMetricsTask.setNumberOfLiftQuantiles( 10 );
testMetricsTask.setPredictionRankingAttrName( "PROBABILITY" );
if (costMatrixName != null) {
testMetricsTask.setCostMatrixName(costMatrixName);
displayTable(costMatrixName, "", "order by ACTUAL_TARGET_VALUE, PREDICTED_TARGET_VALUE");
// Store & execute the task
boolean isTaskSuccess = executeTask(testMetricsTask, "treeTestMetricsTask_jdm");
if( isTaskSuccess ) {
// Restore & display test metrics
ClassificationTestMetrics testMetrics = (ClassificationTestMetrics)
m_dmeConn.retrieveObject( testResultName, NamedObject.testMetrics );
// Display classification test metrics
displayTestMetricDetails(testMetrics);
* This method illustrates how to apply the mining model on the
* MINING_DATA_APPLY_V dataset to predict customer
* response. After completion of the task apply output table with the
* predicted results is created at the user specified location.
* @exception JDMException if model apply failed
public static void applyModel() throws JDMException
System.out.println("---------------------------------------------------");
System.out.println("--- Apply Model ---");
System.out.println("---------------------------------------------------");
System.out.println("---------------------------------------------------");
System.out.println("--- Business case 1 ---");
System.out.println("--- Find the 10 customers who live in Italy ---");
System.out.println("--- that are least expensive to be convinced to ---");
System.out.println("--- use an affinity card. ---");
System.out.println("---------------------------------------------------");
// 1. Create & save PhysicalDataSpecification
PhysicalDataSet applyData =
m_pdsFactory.create( "MINING_DATA_APPLY_V", false );
PhysicalAttribute pa = m_paFactory.create("CUST_ID",
AttributeDataType.integerType, PhysicalAttributeRole.caseId );
applyData.addAttribute( pa );
m_dmeConn.saveObject( "treeApplyData_jdm", applyData, true );
// 2. Create & save ClassificationApplySettings
ClassificationApplySettings clasAS = m_applySettingsFactory.create();
// Add source attributes
HashMap sourceAttrMap = new HashMap();
sourceAttrMap.put( "COUNTRY_NAME", "COUNTRY_NAME" );
clasAS.setSourceDestinationMap( sourceAttrMap );
// Add cost matrix
clasAS.setCostMatrixName( m_costMatrixName );
m_dmeConn.saveObject( "treeApplySettings_jdm", clasAS, true);
// 3. Create, store & execute apply Task
DataSetApplyTask applyTask = m_dsApplyFactory.create(
"treeApplyData_jdm", "treeModel_jdm",
"treeApplySettings_jdm", "TREE_APPLY_OUTPUT1_JDM");
executeTask(applyTask, "treeApplyTask_jdm");
// 4. Display apply result -- Note that APPLY results do not need to be
// reverse transformed, as done in the case of model details. This is
// because class values of a classification target were not (required to
// be) binned or normalized.
// Find the 10 customers who live in Italy that are least expensive to be
// convinced to use an affinity card.
displayTable("TREE_APPLY_OUTPUT1_JDM",
"where COUNTRY_NAME='Italy' and ROWNUM < 11 ",
"order by COST");
System.out.println("---------------------------------------------------");
System.out.println("--- Business case 2 ---");
System.out.println("--- List ten customers (ordered by their id) ---");
System.out.println("--- along with likelihood and cost to use or ---");
System.out.println("--- reject the affinity card. ---");
System.out.println("---------------------------------------------------");
// 1. Create & save PhysicalDataSpecification
applyData =
m_pdsFactory.create( "MINING_DATA_APPLY_V", false );
pa = m_paFactory.create("CUST_ID",
AttributeDataType.integerType, PhysicalAttributeRole.caseId );
applyData.addAttribute( pa );
m_dmeConn.saveObject( "treeApplyData_jdm", applyData, true );
// 2. Create & save ClassificationApplySettings
clasAS = m_applySettingsFactory.create();
// Add cost matrix
clasAS.setCostMatrixName( m_costMatrixName );
m_dmeConn.saveObject( "treeApplySettings_jdm", clasAS, true);
// 3. Create, store & execute apply Task
applyTask = m_dsApplyFactory.create(
"treeApplyData_jdm", "treeModel_jdm",
"treeApplySettings_jdm", "TREE_APPLY_OUTPUT2_JDM");
executeTask(applyTask, "treeApplyTask_jdm");
// 4. Display apply result -- Note that APPLY results do not need to be
// reverse transformed, as done in the case of model details. This is
// because class values of a classification target were not (required to
// be) binned or normalized.
// List ten customers (ordered by their id) along with likelihood and cost
// to use or reject the affinity card (Note: while this example has a
// binary target, such a query is useful in multi-class classification -
// Low, Med, High for example).
displayTable("TREE_APPLY_OUTPUT2_JDM",
"where ROWNUM < 21",
"order by CUST_ID, PREDICTION");
System.out.println("---------------------------------------------------");
System.out.println("--- Business case 3 ---");
System.out.println("--- Find the customers who work in Tech support ---");
System.out.println("--- and are under 25 who is going to response ---");
System.out.println("--- to the new affinity card program. ---");
System.out.println("---------------------------------------------------");
// 1. Create & save PhysicalDataSpecification
applyData =
m_pdsFactory.create( "MINING_DATA_APPLY_V", false );
pa = m_paFactory.create("CUST_ID",
AttributeDataType.integerType, PhysicalAttributeRole.caseId );
applyData.addAttribute( pa );
m_dmeConn.saveObject( "treeApplyData_jdm", applyData, true );
// 2. Create & save ClassificationApplySettings
clasAS = m_applySettingsFactory.create();
// Add source attributes
sourceAttrMap = new HashMap();
sourceAttrMap.put( "AGE", "AGE" );
sourceAttrMap.put( "OCCUPATION", "OCCUPATION" );
clasAS.setSourceDestinationMap( sourceAttrMap );
m_dmeConn.saveObject( "treeApplySettings_jdm", clasAS, true);
// 3. Create, store & execute apply Task
applyTask = m_dsApplyFactory.create(
"treeApplyData_jdm", "treeModel_jdm",
"treeApplySettings_jdm", "TREE_APPLY_OUTPUT3_JDM");
executeTask(applyTask, "treeApplyTask_jdm");
// 4. Display apply result -- Note that APPLY results do not need to be
// reverse transformed, as done in the case of model details. This is
// because class values of a classification target were not (required to
// be) binned or normalized.
// Find the customers who work in Tech support and are under 25 who is
// going to response to the new affinity card program.
displayTable("TREE_APPLY_OUTPUT3_JDM",
"where OCCUPATION = 'TechSup' " +
"and AGE < 25 " +
"and PREDICTION = 1 ",
"order by CUST_ID");
* This method stores the given task with the specified name in the DMS
* and submits the task for asynchronous execution in the DMS. After
* completing the task successfully it returns true. If there is a task
* failure, then it prints error description and returns false.
* @param taskObj task object
* @param taskName name of the task
* @return boolean returns true when the task is successful
* @exception JDMException if task execution failed
public static boolean executeTask(Task taskObj, String taskName)
throws JDMException
boolean isTaskSuccess = false;
m_dmeConn.saveObject(taskName, taskObj, true);
ExecutionHandle execHandle = m_dmeConn.execute(taskName);
System.out.print(taskName + " is started, please wait. ");
//Wait for completion of the task
ExecutionStatus status = execHandle.waitForCompletion(Integer.MAX_VALUE);
//Check the status of the task after completion
isTaskSuccess = status.getState().equals(ExecutionState.success);
if( isTaskSuccess ) //Task completed successfully
System.out.println(taskName + " is successful.");
else //Task failed
System.out.println(taskName + " failed.\nFailure Description: " +
status.getDescription() );
return isTaskSuccess;
private static void displayBuildSettings(
ClassificationSettings clasSettings, String buildSettingsName)
System.out.println("BuildSettings Details from the "
+ buildSettingsName + " table:");
displayTable(buildSettingsName, "", "order by SETTING_NAME");
System.out.println("BuildSettings Details from the "
+ buildSettingsName + " model build settings object:");
String objName = clasSettings.getName();
if(objName != null)
System.out.println("Name = " + objName);
String objDescription = clasSettings.getDescription();
if(objDescription != null)
System.out.println("Description = " + objDescription);
java.util.Date creationDate = clasSettings.getCreationDate();
String creator = clasSettings.getCreatorInfo();
String targetAttrName = clasSettings.getTargetAttributeName();
System.out.println("Target attribute name = " + targetAttrName);
AlgorithmSettings algoSettings = clasSettings.getAlgorithmSettings();
if(algoSettings == null)
System.out.println("Failure: clasSettings.getAlgorithmSettings() returns null");
MiningAlgorithm algo = algoSettings.getMiningAlgorithm();
if(algo == null) System.out.println("Failure: algoSettings.getMiningAlgorithm() returns null");
System.out.println("Algorithm Name: " + algo.name());
MiningFunction function = clasSettings.getMiningFunction();
if(function == null) System.out.println("Failure: clasSettings.getMiningFunction() returns null");
System.out.println("Function Name: " + function.name());
try {
String costMatrixName = clasSettings.getCostMatrixName();
if(costMatrixName != null) {
System.out.println("Cost Matrix Details from the " + costMatrixName
+ " table:");
displayTable(costMatrixName, "", "order by ACTUAL_TARGET_VALUE, PREDICTED_TARGET_VALUE");
} catch(Exception jdmExp)
System.out.println("Failure: clasSettings.getCostMatrixName()throws exception");
jdmExp.printStackTrace();
// List of DT algorithm settings
// treeAlgo.setBuildHomogeneityMetric(TreeHomogeneityMetric.gini);
// treeAlgo.setMaxDepth(7);
// ((OraTreeSettings)treeAlgo).setMinDecreaseInImpurity(0.1, SizeUnit.percentage);
// treeAlgo.setMinNodeSize( 0.05, SizeUnit.percentage );
// treeAlgo.setMinNodeSize( 10, SizeUnit.count );
// ((OraTreeSettings)treeAlgo).setMinDecreaseInImpurity(20, SizeUnit.count);
TreeHomogeneityMetric homogeneityMetric = ((OraTreeSettings)algoSettings).getBuildHomogeneityMetric();
System.out.println("Homogeneity Metric: " + homogeneityMetric.name());
int intValue = ((OraTreeSettings)algoSettings).getMaxDepth();
System.out.println("Max Depth: " + intValue);
double doubleValue = ((OraTreeSettings)algoSettings).getMinNodeSizeForSplit(SizeUnit.percentage);
System.out.println("MinNodeSizeForSplit (percentage): " + m_df.format(doubleValue));
doubleValue = ((OraTreeSettings)algoSettings).getMinNodeSizeForSplit(SizeUnit.count);
System.out.println("MinNodeSizeForSplit (count): " + m_df.format(doubleValue));
doubleValue = ((OraTreeSettings)algoSettings).getMinNodeSize();
SizeUnit unit = ((OraTreeSettings)algoSettings).getMinNodeSizeUnit();
System.out.println("Min Node Size (" + unit.name() +"): " + m_df.format(doubleValue));
doubleValue = ((OraTreeSettings)algoSettings).getMinNodeSize( SizeUnit.count );
System.out.println("Min Node Size (" + SizeUnit.count.name() +"): " + m_df.format(doubleValue));
doubleValue = ((OraTreeSettings)algoSettings).getMinNodeSize( SizeUnit.percentage );
System.out.println("Min Node Size (" + SizeUnit.percentage.name() +"): " + m_df.format(doubleValue));
* This method displayes DT model signature.
* @param model model object
* @exception JDMException if failed to retrieve model signature
public static void displayModelSignature(Model model) throws JDMException
String modelName = model.getName();
System.out.println("Model Name: " + modelName);
ModelSignature modelSignature = model.getSignature();
System.out.println("ModelSignature Deatils: ( Attribute Name, Attribute Type )");
MessageFormat mfSign = new MessageFormat(" ( {0}, {1} )");
String[] vals = new String[3];
Collection sortedSet = modelSignature.getAttributes();
Iterator attrIterator = sortedSet.iterator();
while(attrIterator.hasNext())
SignatureAttribute attr = (SignatureAttribute)attrIterator.next();
vals[0] = attr.getName();
vals[1] = attr.getDataType().name();
System.out.println( mfSign.format(vals) );
* This method displayes DT model details.
* @param treeModelDetails tree model details object
* @exception JDMException if failed to retrieve model details
public static void displayTreeModelDetailsExtensions(TreeModelDetail treeModelDetails)
throws JDMException
System.out.println( "\nTreeModelDetail: Model name=" + "treeModel_jdm" );
TreeNode root = treeModelDetails.getRootNode();
System.out.println( "\nRoot node: " + root.getIdentifier() );
// get the info for the tree model
int treeDepth = ((OraTreeModelDetail) treeModelDetails).getTreeDepth();
System.out.println( "Tree depth: " + treeDepth );
int totalNodes = ((OraTreeModelDetail) treeModelDetails).getNumberOfNodes();
System.out.println( "Total number of nodes: " + totalNodes );
int totalLeaves = ((OraTreeModelDetail) treeModelDetails).getNumberOfLeafNodes();
System.out.println( "Total number of leaf nodes: " + totalLeaves );
Stack nodeStack = new Stack();
nodeStack.push( root);
while( !nodeStack.empty() )
TreeNode node = (TreeNode) nodeStack.pop();
// display this node
int nodeId = node.getIdentifier();
long caseCount = node.getCaseCount();
Object prediction = node.getPrediction();
int level = node.getLevel();
int children = node.getNumberOfChildren();
TreeNode parent = node.getParent();
System.out.println( "\nNode id=" + nodeId + " at level " + level );
if( parent != null )
System.out.println( "parent: " + parent.getIdentifier() +
", children=" + children );
System.out.println( "Case count: " + caseCount + ", prediction: " + prediction );
Predicate predicate = node.getPredicate();
System.out.println( "Predicate: " + predicate.toString() );
Predicate[] surrogates = node.getSurrogates();
if( surrogates != null )
for( int i=0; i<surrogates.length; i++ )
System.out.println( "Surrogate[" + i + "]: " + surrogates[i] );
// add child nodes in the stack
if( children > 0 )
TreeNode[] childNodes = node.getChildren();
for( int i=0; i<childNodes.length; i++ )
nodeStack.push( childNodes[i] );
TreeNode[] allNodes = treeModelDetails.getNodes();
System.out.print( "\nNode identifiers by getNodes():" );
for( int i=0; i<allNodes.length; i++ )
System.out.print( " " + allNodes.getIdentifier() );
System.out.println();
// display the node identifiers
int[] nodeIds = treeModelDetails.getNodeIdentifiers();
System.out.print( "Node identifiers by getNodeIdentifiers():" );
for( int i=0; i<nodeIds.length; i++ )
System.out.print( " " + nodeIds[i] );
System.out.println();
TreeNode node = treeModelDetails.getNode(nodeIds.length-1);
System.out.println( "Node identifier by getNode(" + (nodeIds.length-1) +
"): " + node.getIdentifier() );
Rule rule2 = treeModelDetails.getRule(nodeIds.length-1);
System.out.println( "Rule identifier by getRule(" + (nodeIds.length-1) +
"): " + rule2.getRuleIdentifier() );
// get the rules and display them
Collection ruleColl = treeModelDetails.getRules();
Iterator ruleIterator = ruleColl.iterator();
while( ruleIterator.hasNext() )
Rule rule = (Rule) ruleIterator.next();
int ruleId = rule.getRuleIdentifier();
Predicate antecedent = (Predicate) rule.getAntecedent();
Predicate consequent = (Predicate) rule.getConsequent();
System.out.println( "\nRULE " + ruleId + ": support=" +
rule.getSupport() + " (abs=" + rule.getAbsoluteSupport() +
"), confidence=" + rule.getConfidence() );
System.out.println( antecedent );
System.out.println( "=======>" );
System.out.println( consequent );
* Display classification test metrics object
* @param testMetrics classification test metrics object
* @exception JDMException if failed to retrieve test metric details
public static void displayTestMetricDetails(
ClassificationTestMetrics testMetrics) throws JDMException
// Retrieve Oracle ABN model test metrics deatils extensions
// Test Metrics Name
System.out.println("Test Metrics Name = " + testMetrics.getName());
// Model Name
System.out.println("Model Name = " + testMetrics.getModelName());
// Test Data Name
System.out.println("Test Data Name = " + testMetrics.getTestDataName());
// Accuracy
System.out.println("Accuracy = " + m_df.format(testMetrics.getAccuracy().doubleValue()));
// Confusion Matrix
ConfusionMatrix confusionMatrix = testMetrics.getConfusionMatrix();
Collection categories = confusionMatrix.getCategories();
Iterator xIterator = categories.iterator();
System.out.println("Confusion Matrix: Accuracy = " + m_df.format(confusionMatrix.getAccuracy()));
System.out.println("Confusion Matrix: Error = " + m_df.format(confusionMatrix.getError()));
System.out.println("Confusion Matrix:( Actual, Prection, Value )");
MessageFormat mf = new MessageFormat(" ( {0}, {1}, {2} )");
String[] vals = new String[3];
while(xIterator.hasNext())
Object actual = xIterator.next();
vals[0] = actual.toString();
Iterator yIterator = categories.iterator();
while(yIterator.hasNext())
Object predicted = yIterator.next();
vals[1] = predicted.toString();
long number = confusionMatrix.getNumberOfPredictions(actual, predicted);
vals[2] = Long.toString(number);
System.out.println(mf.format(vals));
// Lift
Lift lift = testMetrics.getLift();
System.out.println("Lift Details:");
System.out.println("Lift: Target Attribute Name = " + lift.getTargetAttributeName());
System.out.println("Lift: Positive Target Value = " + lift.getPositiveTargetValue());
System.out.println("Lift: Total Cases = " + lift.getTotalCases());
System.out.println("Lift: Total Positive Cases = " + lift.getTotalPositiveCases());
int numberOfQuantiles = lift.getNumberOfQuantiles();
System.out.println("Lift: Number Of Quantiles = " + numberOfQuantiles);
System.out.println("Lift: ( QUANTILE_NUMBER, QUANTILE_TOTAL_COUNT, QUANTILE_TARGET_COUNT, PERCENTAGE_RECORDS_CUMULATIVE,CUMULATIVE_LIFT,CUMULATIVE_TARGET_DENSITY,TARGETS_CUMULATIVE, NON_TARGETS_CUMULATIVE, LIFT_QUANTILE, TARGET_DENSITY )");
MessageFormat mfLift = new MessageFormat(" ( {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9} )");
String[] liftVals = new String[10];
for(int iQuantile=1; iQuantile<= numberOfQuantiles; iQuantile++)
liftVals[0] = Integer.toString(iQuantile); //QUANTILE_NUMBER
liftVals[1] = Long.toString(lift.getCases((iQuantile-1), iQuantile));//QUANTILE_TOTAL_COUNT
liftVals[2] = Long.toString(lift.getNumberOfPositiveCases((iQuantile-1), iQuantile));//QUANTILE_TARGET_COUNT
liftVals[3] = m_df.format(lift.getCumulativePercentageSize(iQuantile).doubleValue());//PERCENTAGE_RECORDS_CUMULATIVE
liftVals[4] = m_df.format(lift.getCumulativeLift(iQuantile).doubleValue());//CUMULATIVE_LIFT
liftVals[5] = m_df.format(lift.getCumulativeTargetDensity(iQuantile).doubleValue());//CUMULATIVE_TARGET_DENSITY
liftVals[6] = Long.toString(lift.getCumulativePositiveCases(iQuantile));//TARGETS_CUMULATIVE
liftVals[7] = Long.toString(lift.getCumulativeNegativeCases(iQuantile));//NON_TARGETS_CUMULATIVE
liftVals[8] = m_df.format(lift.getLift(iQuantile, iQuantile).doubleValue());//LIFT_QUANTILE
liftVals[9] = m_df.format(lift.getTargetDensity(iQuantile, iQuantile).doubleValue());//TARGET_DENSITY
System.out.println(mfLift.format(liftVals));
// ROC
ReceiverOperatingCharacterics roc = testMetrics.getROC();
System.out.println("ROC Details:");
System.out.println("ROC: Area Under Curve = " + m_df.format(roc.getAreaUnderCurve()));
int nROCThresh = roc.getNumberOfThresholdCandidates();
System.out.println("ROC: Number Of Threshold Candidates = " + nROCThresh);
System.out.println("ROC: ( INDEX, PROBABILITY, TRUE_POSITIVES, FALSE_NEGATIVES, FALSE_POSITIVES, TRUE_NEGATIVES, TRUE_POSITIVE_FRACTION, FALSE_POSITIVE_FRACTION )");
MessageFormat mfROC = new MessageFormat(" ( {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7} )");
String[] rocVals = new String[8];
for(int iROC=1; iROC <= nROCThresh; iROC++)
rocVals[0] = Integer.toString(iROC); //INDEX
rocVals[1] = m_df.format(roc.getProbabilityThreshold(iROC));//PROBABILITY
rocVals[2] = Long.toString(roc.getPositives(iROC, true));//TRUE_POSITIVES
rocVals[3] = Long.toString(roc.getNegatives(iROC, false));//FALSE_NEGATIVES
rocVals[4] = Long.toString(roc.getPositives(iROC, false));//FALSE_POSITIVES
rocVals[5] = Long.toString(roc.getNegatives(iROC, true));//TRUE_NEGATIVES
rocVals[6] = m_df.format(roc.getHitRate(iROC));//TRUE_POSITIVE_FRACTION
rocVals[7] = m_df.format(roc.getFalseAlarmRate(iROC));//FALSE_POSITIVE_FRACTION
System.out.println(mfROC.format(rocVals));
private static void displayTable(String tableName, String whereCause, String orderByColumn)
StringBuffer emptyCol = new StringBuffer(" ");
java.sql.Connection dbConn =
((OraConnection)m_dmeConn).getDatabaseConnection();
PreparedStatement pStmt = null;
ResultSet rs = null;
try
pStmt = dbConn.prepareStatement("SELECT * FROM " + tableName + " " + whereCause + " " + orderByColumn);
rs = pStmt.executeQuery();
ResultSetMetaData rsMeta = rs.getMetaData();
int colCount = rsMeta.getColumnCount();
StringBuffer header = new StringBuffer();
System.out.println("Table : " + tableName);
//Build table header
for(int iCol=1; iCol<=colCount; iCol++)
String colName = rsMeta.getColumnName(iCol);
header.append(emptyCol.replace(0, colName.length(), colName));
emptyCol = new StringBuffer(" ");
System.out.println(header.toString());
//Write table data
while(rs.next())
StringBuffer rowContent = new StringBuffer();
for(int iCol=1; iCol<=colCount; iCol++)
int sqlType = rsMeta.getColumnType(iCol);
Object obj = rs.getObject(iCol);
String colContent = null;
if(obj instanceof java.lang.Number)
try
BigDecimal bd = (BigDecimal)obj;
if(bd.scale() > 5)
colContent = m_df.format(obj);
} else
colContent = bd.toString();
} catch(Exception anyExp) {
colContent = m_df.format(obj);
} else
if(obj == null)
colContent = "NULL";
else
colContent = obj.toString();
rowContent.append(" "+emptyCol.replace(0, colContent.length(), colContent));
emptyCol = new StringBuffer(" ");
System.out.println(rowContent.toString());
} catch(Exception anySqlExp) {
anySqlExp.printStackTrace();
}//Ignore
private static void createTableForTestMetrics(String applyOutputTableName,
String testDataName,
String testMetricsInputTableName)
//0. need to execute the following in the schema
String sqlCreate =
"create table " + testMetricsInputTableName + " as " +
"select a.id as id, prediction, probability, affinity_card " +
"from " + testDataName + " a, " + applyOutputTableName + " b " +
"where a.id = b.id";
java.sql.Connection dbConn = ((OraConnection) m_dmeConn).getDatabaseConnection();
Statement stmt = null;
try
stmt = dbConn.createStatement();
stmt.executeUpdate( sqlCreate );
catch( Exception anySqlExp )
System.out.println( anySqlExp.getMessage() );
anySqlExp.printStackTrace();
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
private static void clean()
java.sql.Connection dbConn =
((OraConnection) m_dmeConn).getDatabaseConnection();
Statement stmt = null;
// Drop apply output table
try
stmt = dbConn.createStatement();
stmt.executeUpdate("DROP TABLE TREE_APPLY_OUTPUT1_JDM");
} catch(Exception anySqlExp) {}//Ignore
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
try
stmt = dbConn.createStatement();
stmt.executeUpdate("DROP TABLE TREE_APPLY_OUTPUT2_JDM");
} catch(Exception anySqlExp) {}//Ignore
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
try
stmt = dbConn.createStatement();
stmt.executeUpdate("DROP TABLE TREE_APPLY_OUTPUT3_JDM");
} catch(Exception anySqlExp) {}//Ignore
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
// Drop apply output table created for test metrics task
try
stmt = dbConn.createStatement();
stmt.executeUpdate("DROP TABLE DT_TEST_APPLY_OUTPUT_COST_JDM");
} catch(Exception anySqlExp) {}//Ignore
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
try
stmt = dbConn.createStatement();
stmt.executeUpdate("DROP TABLE DT_TEST_APPLY_OUTPUT_JDM");
} catch(Exception anySqlExp) {}//Ignore
finally
try
stmt.close();
catch( SQLException sqlExp ) {}
//Drop the model
try {
m_dmeConn.removeObject( "treeModel_jdm", NamedObject.model );
} catch(Exception jdmExp) {}
// drop test metrics result: created by TestMetricsTask
try {
m_dmeConn.removeObject( "dtTestMetricsWithCost_jdm", NamedObject.testMetrics );
} catch(Exception jdmExp) {}
try {
m_dmeConn.removeObject( "dtTestMetrics_jdm", NamedObject.testMetrics );
} catch(Exception jdmExp) {}Hi
I am not sure whether this will help but someone else was getting an error with a java.sql.SQLexception: Unsupported feature. Here is a link to the fix: http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=3&t=007947
Best wishes
Michael -
Reading an XML file and write the contents to another xml file in java
Hi,
I am new to xml parsing.My requirement is that I am getting a message (xml) using ibm MQ in the ByteArrayInputStream format.I have to read this xml message and write to another file.
I am creating a POC for this.
First I used simple reading and writing concept but the output is "java.io.FileInputStream@3e25a5 "
Sample xml file
- <Client>
<ClientId>1234</ClientId>
<ClientName>STechnology</ClientName>
<DTU_ID>567</DTU_ID>
<ClientStatus>ACTIVE</ClientStatus>
- <LEAccount>
<ClientLE>678989</ClientLE>
<LEId>56743</LEId>
- <Account>
<AccountNumber>9876543678</AccountNumber>
</Account>
</LEAccount>
- <Service>
<Cindicator>Y2Y</Cindicator>
<PrefCode>980</PrefCode>
<BSCode>876</BSCode>
<MandatoryContent>MSP</MandatoryContent>
</Service>
</Client>
code:
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
public static void main(String srg[]) throws IOException{
InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
byte currentXMLBytes[] = inputStream.toString().getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
int read=0;
byte[] bytes = new byte[1024];
while((read = byteArrayInputStream.read(bytes))!= -1){
out.write(bytes, 0, read);
out.write( '\n' );
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
Please suggest me how can I use DOM/SAX parser ,I can see several code on net for reading xml file using SAX/DOM parser but writing an xml file after reading it using ByteArrayInputStream I am not getting .A help through some example Link will also be helpful for me.
Thanks
Sumit
Edited by: user8687839 on Apr 30, 2012 2:37 AM
Edited by: user8687839 on Apr 30, 2012 2:43 AMThanks I got the result.
package com.sumit.collections;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
public static void main(String srg[]) throws IOException{
InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead; byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead); } buffer.flush();
byte currentXMLBytes[]= buffer.toByteArray();
/* byte currentXMLBytes[] = inputStream.toString().getBytes();*/
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
int read=0;
byte[] bytes = new byte[1024];
while((read = byteArrayInputStream.read(bytes))!= -1){
out.write(bytes, 0, read);
out.write( '\n' );
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} -
Implementing XAdES in Java XML Digital Signature API
Hi,
I've got some problems with implementing XAdES standard with Java XML Digital Signature API. Below is a code (SignatureTest1), that produces a digital signature with some XAdES tags placed in <ds:Object> tag. The signature is later validated with a Validator class. Everything works fine, until I set a XAdES namespace (SignatureTest1.xadesNS="http://uri.etsi.org/01903/v1.3.2#"). In this case validation of XAdES elements fails.
The reason of validation failture is a difference between arguments passed to a digest method when document is being signed and validated. When the document is being signed a log looks like this:
FINER: Pre-digested input:
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.DigesterOutputStream write
FINER: <SignedProperties xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SignP"></SignedProperties>
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference digest
FINE: Reference object uri = #SignP
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference digest
FINE: Reference digesting completed,but while validating:
FINER: Pre-digested input:
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.DigesterOutputStream write
FINER: <SignedProperties xmlns="http://uri.etsi.org/01903/v1.3.2#" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SignP"></SignedProperties>
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference validate
FINE: Expected digest: MAQ/vctdkyVHVzoQWnOnQdeBw8g=
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference validate
FINE: Actual digest: D7WajkF0U5t1GnVJqj9g1IntLQg=
2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMXMLSignature validate
FINE: Reference[#SignP] is valid: falseHow can I fix this?
Signer class:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLObject;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.sun.org.apache.xml.internal.security.utils.IdResolver;
public class SignatureTest1 {
public static String xadesNS=null;//"http://uri.etsi.org/01903/v1.3.2#";
public static String signatureID="Sig1";
public static String signedPropID="SignP";
public static void main(String[] arg) {
try{
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
List<Reference> refs = new ArrayList<Reference>();
Reference ref1 = fac.newReference
("", fac.newDigestMethod(DigestMethod.SHA1, null),
Collections.singletonList
(fac.newTransform
(Transform.ENVELOPED, (TransformParameterSpec) null)),
null, null);
refs.add(ref1);
Reference ref2 = fac.newReference("#"+signedPropID,fac.newDigestMethod(DigestMethod.SHA1,null),null,"http://uri.etsi.org/01903/v1.3.2#SignedProperties",null);
refs.add(ref2);
SignedInfo si = fac.newSignedInfo
(fac.newCanonicalizationMethod
(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
refs);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc =
dbf.newDocumentBuilder().parse("purchaseOrder.xml");
DOMSignContext dsc = new DOMSignContext
(kp.getPrivate(), doc.getDocumentElement());
dsc.putNamespacePrefix(XMLSignature.XMLNS, "ds");
Element QPElement = createElement(doc, "QualifyingProperties",null,xadesNS);
QPElement.setAttributeNS(null, "Target", signatureID);
Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
SPElement.setAttributeNS(null, "Id", signedPropID);
IdResolver.registerElementById(SPElement, signedPropID);
QPElement.appendChild(SPElement);
Element UPElement = createElement(doc, "UnsignedProperties", null,xadesNS);
QPElement.appendChild(UPElement);
DOMStructure qualifPropStruct = new DOMStructure(QPElement);
List<DOMStructure> xmlObj = new ArrayList<DOMStructure>();
xmlObj.add(qualifPropStruct);
XMLObject object = fac.newXMLObject(xmlObj,"QualifyingInfos",null,null);
List objects = Collections.singletonList(object);
XMLSignature signature = fac.newXMLSignature(si, ki,objects,signatureID,null);
signature.sign(dsc);
OutputStream os = new FileOutputStream("signedPurchaseOrder.xml");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
}catch(Exception e){
e.printStackTrace();
try{
Validator.main(null);
}catch(Exception e){
System.out.println("Validator exception");
e.printStackTrace();
public static Element createElement(Document doc, String tag,String prefix, String nsURI) {
String qName = prefix == null ? tag : prefix + ":" + tag;
return doc.createElementNS(nsURI, qName);
}Validator class:
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dom.*;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.*;
import java.io.FileInputStream;
import java.security.*;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
* This is a simple example of validating an XML
* Signature using the JSR 105 API. It assumes the key needed to
* validate the signature is contained in a KeyValue KeyInfo.
public class Validator {
// Synopsis: java Validate [document]
// where "document" is the name of a file containing the XML document
// to be validated.
public static void main(String[] args) throws Exception {
// Instantiate the document to be validated
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc =
dbf.newDocumentBuilder().parse(new FileInputStream("signedPurchaseOrder.xml"));
// Find Signature element
NodeList nl =
doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("Cannot find Signature element");
// Create a DOM XMLSignatureFactory that will be used to unmarshal the
// document containing the XMLSignature
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
// Create a DOMValidateContext and specify a KeyValue KeySelector
// and document context
DOMValidateContext valContext = new DOMValidateContext
(new KeyValueKeySelector(), nl.item(0));
// unmarshal the XMLSignature
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
// Validate the XMLSignature (generated above)
boolean coreValidity = signature.validate(valContext);
// Check core validation status
if (coreValidity == false) {
System.err.println("Signature failed core validation");
boolean sv = signature.getSignatureValue().validate(valContext);
System.out.println("signature validation status: " + sv);
// check the validation status of each Reference
Iterator i = signature.getSignedInfo().getReferences().iterator();
for (int j=0; i.hasNext(); j++) {
boolean refValid =
((Reference) i.next()).validate(valContext);
System.out.println("ref["+j+"] validity status: " + refValid);
} else {
System.out.println("Signature passed core validation");
* KeySelector which retrieves the public key out of the
* KeyValue element and returns it.
* NOTE: If the key algorithm doesn't match signature algorithm,
* then the public key will be ignored.
private static class KeyValueKeySelector extends KeySelector {
public KeySelectorResult select(KeyInfo keyInfo,
KeySelector.Purpose purpose,
AlgorithmMethod method,
XMLCryptoContext context)
throws KeySelectorException {
if (keyInfo == null) {
throw new KeySelectorException("Null KeyInfo object!");
SignatureMethod sm = (SignatureMethod) method;
List list = keyInfo.getContent();
for (int i = 0; i < list.size(); i++) {
XMLStructure xmlStructure = (XMLStructure) list.get(i);
if (xmlStructure instanceof KeyValue) {
PublicKey pk = null;
try {
pk = ((KeyValue)xmlStructure).getPublicKey();
} catch (KeyException ke) {
throw new KeySelectorException(ke);
// make sure algorithm is compatible with method
if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
return new SimpleKeySelectorResult(pk);
throw new KeySelectorException("No KeyValue element found!");
//@@@FIXME: this should also work for key types other than DSA/RSA
static boolean algEquals(String algURI, String algName) {
if (algName.equalsIgnoreCase("DSA") &&
algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
return true;
} else if (algName.equalsIgnoreCase("RSA") &&
algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
return true;
} else {
return false;
private static class SimpleKeySelectorResult implements KeySelectorResult {
private PublicKey pk;
SimpleKeySelectorResult(PublicKey pk) {
this.pk = pk;
public Key getKey() { return pk; }
}PurchaseOrder.xml
<?xml version="1.0" encoding="UTF-8"?>
<PurchaseOrder>
<Item number="130046593231">
<Description>Video Game</Description>
<Price>10.29</Price>
</Item>
<Buyer id="8492340">
<Name>My Name</Name>
<Address>
<Street>One Network Drive</Street>
<Town>Burlington</Town>
<State>MA</State>
<Country>United States</Country>
<PostalCode>01803</PostalCode>
</Address>
</Buyer>
</PurchaseOrder>signedPurchaseOrder.xml with XAdES namespace:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><PurchaseOrder>
<Item number="130046593231">
<Description>Video Game</Description>
<Price>10.29</Price>
</Item>
<Buyer id="8492340">
<Name>My Name</Name>
<Address>
<Street>One Network Drive</Street>
<Town>Burlington</Town>
<State>MA</State>
<Country>United States</Country>
<PostalCode>01803</PostalCode>
</Address>
</Buyer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Sig1"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>tVicGh6V+8cHbVYFIU91o5+L3OQ=</ds:DigestValue></ds:Reference><ds:Reference Type="http://uri.etsi.org/01903/v1.3.2#SignedProperties" URI="#SignP"><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>MAQ/vctdkyVHVzoQWnOnQdeBw8g=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>lSgzfZCRIlgrgr6YpNOdB3XWdF9P9TEiXfkNoqUpAru/I7IiyiFWJg==</ds:SignatureValue><ds:KeyInfo><ds:KeyValue><ds:DSAKeyValue><ds:P>/KaCzo4Syrom78z3EQ5SbbB4sF7ey80etKII864WF64B81uRpH5t9jQTxeEu0ImbzRMqzVDZkVG9
xD7nN1kuFw==</ds:P><ds:Q>li7dzDacuo67Jg7mtqEm2TRuOMU=</ds:Q><ds:G>Z4Rxsnqc9E7pGknFFH2xqaryRPBaQ01khpMdLRQnG541Awtx/XPaF5Bpsy4pNWMOHCBiNU0Nogps
QW5QvnlMpA==</ds:G><ds:Y>p48gU203NGPcs9UxEQQQzQ19KBtDRGfEs3BDt0cbCRJHMh3EoySpeqOnuTeKLXuFr96nzAPq4BEU
dNAc7XpDvQ==</ds:Y></ds:DSAKeyValue></ds:KeyValue></ds:KeyInfo><ds:Object Id="QualifyingInfos"><QualifyingProperties Target="Sig1" xmlns="http://uri.etsi.org/01903/v1.3.2#"><SignedProperties Id="SignP"/><UnsignedProperties/></QualifyingProperties></ds:Object></ds:Signature></PurchaseOrder>I believe the problem is that you are not explicitly adding the xades namespace
attribute to the SignedProperties element before generating the signature. Thus,
the namespace attribute is not visible when canonicalizing, but when you serialize the
DOM tree to an output stream, (for reasons I'm not entirely sure why), the namespace
attribute is visible and is added to the SignedProperties element, which breaks the
signature.
You must always explicitly add namespace attributes using the Element.setAttributeNS
method. Try changing the following code from:
Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
to:
Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
SPElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", xadesNS);
Maybe you are looking for
-
Embedding links in GB-authored podcasts to open a new browser window
Hi - does anyone have advice for me on how to embed url links in an enhanced podcast that I'm authoring in GarageBand that will open a new window when selected (or employ some other strategy to keep the podcast from being interrupted) when the podcas
-
Installing the same operating System from recovery DVD
Hi there, I have windows 8.1 in my laptop. But The only partition I have is the windows drive. Now I want to partition my hard disk and install windows in one of the partition. I have a recovery partition also. I have made recovery disk from this par
-
cant download my music to ipod bc ipod wont show up when it is connected to the computer HELP!!!!!
-
Can I use ipad 2 (64GB) with Wi-Fi 3G in Nigeria?
Please let someone help me out, I want to buy this stuff in Nigeria.
-
WRT54G-CA slow to connect to internet after booting Windows XP
Just bought a WRT54G-CA wireless router to replace my regular wired one. After i boot Windows XP now it takes about 2 minutes before internet explorer and outlook express can access the internet. In fact outlook express won't even load for those 2 mi