VeriSign Java Object Signing (Class 3) Digital ID
Hi,
I have a VeriSign Java Object Signing (Class 3) Digital ID.
How do i convert this to a file i can use for signing?
I previously had a '.p12' file and used jarsigner which worked.
Any help would be greatly appreciated!
Thanks,
J
I just received our Verisign "Java Object Signing
(Class 3) Digital ID". When I try to import it I get
the following error:
keytool error: java.lang.Exception: Input not an X.509
certificate.
The command I am using to import the cert is :
keytool -import -alias pcs -file cert.cer -keystore
vs.keystore -trustcacerts
Any idea what I am doing wrong? I am using JDK 1.3,
do I need to upgrade to 1.4 to import certs currently
being provided by Verisign?
Thanks,
JimIf you did as I did and ordered a rsa certificate, you need to add the option
-keyalg rsa
to your command line.
lmd
Similar Messages
-
XSLT - How to pass a Java object to the xslt file ?
Hi ,
I need help in , How to pass a java object to xslt file.
I am using javax.xml.transform.Tranformer class to for the xsl tranformation. I need to pass a java object eg
Class Employee {
private String name;
private int empId;
public String getName() {
return this.name;
public String getEmpId() {
return this.empId;
public String setName(String name) {
this.name = name;
public String setEmpId(int empId){
this.empId = empId;
How can i access this complete object in the xsl file ? is there any way i can pass custom objects to xsl using Transformer class ?This is elementary. Did you ask google ? http://www.google.com/search?q=calling+java+from+xsl
ram. -
Tool to create Java Object classes using the Database Tables
Hi,
Is their any tools or utility available to create the Java Object Classes using the Database Tables as input.
Lets Say I am having the Employee, Employee_Salary tables in the Database.The utility has to create the Java Object classes with the relation.
Please Help...
Thx..Hm, for generating regular Java classes I wouldn't know one from memory. But I suggest you start searching in for example the Eclipse marketspace for a third party plugin that can do it. If all fail, you could always use Hibernate Tools from the Jboss Tools Eclipse plugin set to generate Hibernate/JPA entities and then strip the annotations from them to turn them into regular POJO classes.
How many tables are we talking about anyway? It might be less effort to just create the classes with properties and then use an IDE to generate getters and setters for them. -
How to print the image data stored in object of 'java.io.File' Class in jsp
I have created a file object for the image file in the system temporary directory.Now I want to display it in my page. please tell,How to print the image data stored in object(in my program it is imgr) of 'java.io.File' Class in jsp
Create a servlet which gets an InputStream of the file and writes it to the OutputStream of the response and call this servlet in `src` attribute. That's basically all.
Here's an example which covers the most of the minimum needs: [http://balusc.blogspot.com/2007/04/imageservlet.html]. -
How to reload class file for java objects in CF MX7
I'm trying to create a simple java object for use in a CFML
page. According to the topic "About ColdFusion and Java objects" in
the CF developer's guide, I can compile my java module and put the
.class file in the CFusionMX7/wwwroot/WEB-INF/classes directory and
it'll be dynamically reloaded any time CF sees a new .class file
there. But the dynamic reload isn't happening; I have to restart
the CF server to get it to pick up a new version.
I don't believe this directory is in the "general JVM
classpath"; I don't find "classes" in the Java Class Path in the CF
Administrator's System Information page. And I have all the caching
options turned off on the "Server Settings > Caching" page, if
that has any bearing on it.
Are there any known issues around this dynamic reload
capability, or maybe a more definitive way to make sure the
WEB-INF/classes directory isn't in the classpath?
Thanks,
JamesYes, I understand. But if I'm reading it correctly, what
you're saying seems to contradict the documentation
http://livedocs.adobe.com/coldfusion/7/htmldocs/00001561.htm
ColdFusion dynamically loads classes that are either .class
files in the web_root/WEB-INF/classes directory or in JAR files in
the web_root/WEB-INF/lib directory. ColdFusion checks the time
stamp on the file when it creates an object that is defined in
either directory, even when the class is already in memory. If the
file that contains the class is newer than the class in memory,
ColdFusion loads the class from that directory.
http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_18228&sliceId=1
Dynamic class reloading for Java servlets classes and
forcfobject (sic) Java classes is disabled by default in
ColdFusion MX. To enable dynamic class reloading, do the following:
Also, I seem to recall that setting worked in a prior
version. Though I would have to test it again on another machine to
be certain. -
Using java.lang.Float.class causing Cannot format given Object as a Number
hi,
I have table and its model is default table model.
model = new javax.swing.table.DefaultTableModel(data,col) {Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Float.class, java.lang.Integer.class
}; public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}};I want to force the user to enter float number to fourth column and integer number to fifth column. but I am gettin an error "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number" like this. cause of this error is "java.lang.Float.class". and when I use Integer instead of Float the is no problem. Could you please help ?It depends on model data.
-
Problem in casting a database object to Java object
hi everyone,
Iam trying to execute following example which was provided in oracle documentation. iam planning to implement this concept in my project...But, i am not able to run...iam herewith enclosing the sample code and its error...Kindly help me out
import java.sql.*;
import java.io.*;
import java.util.*;
import java.math.BigDecimal;
import oracle.sql.*;
import oracle.jdbc.*;
public class PersonObject
public static void main (String args [])
throws Exception
// Register the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
// Connect to the database
// You need to put your database name after the @ sign in
// the connection URL.
// The sample retrieves an object of type "STUDENT",
// materializes the object as an object of type ADT.
// The Object is then modified and inserted back into the database.
Connection conn =
DriverManager.getConnection ("jdbc:oracle:thin:@raman.monsanto.com:1521:ramdevl","multispec", "mspec");
// It's faster when auto commit is off
conn.setAutoCommit (false);
// Create a Statement
Statement stmt = conn.createStatement ();
try
stmt.execute ("drop table people");
stmt.execute ("drop type PERSON FORCE");
stmt.execute ("drop type ADDRESS FORCE");
catch (SQLException e)
System.out.println("Error during executing a statement: "+ e);
stmt.execute ("create type ADDRESS as object (street VARCHAR (30), num NUMBER)");
stmt.execute ("create type PERSON as object (name VARCHAR (30), home ADDRESS)");
stmt.execute ("create table people (empno NUMBER, empid PERSON)");
stmt.execute ("insert into people values(101, PERSON ('Greg', ADDRESS ('Van Ness', 345)))");
stmt.execute ("insert into people values(102, PERSON ('John', ADDRESS ('Geary', 229)))");
ResultSet rs = stmt.executeQuery ("select * from people");
System.out.println("This application works till extraction of data\n");
showResultSet (rs);
rs.close();
stmt.close();
conn.close();
public static void showResultSet (ResultSet rs)
throws SQLException
while (rs.next ())
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("the no of columns: "+rsmd.getColumnCount());
for(int i=0;i<rsmd.getColumnCount();i++)
System.out.println("The column no "+(i+1)+"is of type: "+rsmd.getColumnTypeName(i+1) );
int empno = rs.getInt (1);
// retrieve the STRUCT
(This line throws the error----->) STRUCT person_struct = (STRUCT)rs.getObject (2);
Object person_attrs[] = person_struct.getAttributes();
System.out.println ("person name: " + (String) person_attrs[0]);
STRUCT address = (STRUCT) person_attrs[1];
System.out.println ("person address: ");
Object address_attrs[] = address.getAttributes();
System.out.println ("street: " + (String) address_attrs[0]);
System.out.println ("number: " +
((BigDecimal) address_attrs[1]).intValue());
System.out.println ();
The error message is as follows:
sj -make -cdb newmodeltest.cdb -g -d D:\VisualCafe\Projects\ -classpath
D:\jdk1.3\jre\lib\classes12.zip;D:\VisualCafe\Projects\;D:\VISUALCAFE\JAVA\LIB\;D:\VISUALCAFE\JAVA\LIB\SYMCLASS.ZIP;D:\VISUALCAFE\JAVA\LIB\CLASSES.ZIP;D:\VISUALCAFE\JFC\SWINGALL.JAR;D:\VISUALCAFE\swing
-1.1\SWINGALL.JAR;D:\VISUALCAFE\JAVA\LIB\RT.JAR;D:\VISUALCAFE\BIN\COMPONENTS\SFC.JAR;D:\VISUALCAFE\BIN\COMPONENTS\SYMBEANS.JAR;D:\VISUALCAFE\JAVA\LIB\icebrowserbean.jar;D:\VISUALCAFE\JAVA\LIB\jsdk.jar;
D:\VISUALCAFE\JAVA\LIB\SYMTOOLS.JAR;D:\VISUALCAFE\BIN\COMPONENTS\TEMPLATES.JAR D:\VisualCafe\Projects\PersonObject.java
Build Successful
loading PersonObject.class for debugging...
PersonObject.class successfully loaded
This application works till extraction of data
the no of columns: 2
The column no 1is of type: NUMBER
The column no 2is of type: MULTISPEC.PERSON
java.lang.IncompatibleClassChangeError: class java.util.Hashtable does not implement interface java.util.Map
at oracle.sql.StructDescriptor.getClass(StructDescriptor.java:418)
at oracle.sql.STRUCT.toJdbc(STRUCT.java:365)
at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4195)
at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4123)
at oracle.jdbc.driver.OracleResultSetImpl.getObject(OracleResultSetImpl.java:401)
at PersonObject.showResultSet(PersonObject.java:106)
at PersonObject.main(PersonObject.java:54)
at symantec.tools.debug.MainThread.run(Agent.java:48)
Thanks in advance
Sudarshan.KSince that implementation has existed since 1.2 and
the original post suggested that 1.3 was being used,I
don't see that a newer version would help any.That's not a good assumption. There could have been a
bug fix.
Could be. But for the particular error (IncompatibleClassChangeError) I would consider the chance almost non-existent until all other possibilities have been exhausted. -
Initializing Factory class with Digital Signature
Hi All,
I am trying to Initialize the Factory class using digital signature. These are the steps I fallowed.
1. Created a Java application "Application1" in Jdeveloper.
2. Copied config, ext, lib folder from the Design console directory to the Application1/Project1 folder.
3. added the lib and ext jars to the project properties.
4. Modified the run/debug profile in the project properties to point to the xlconfig file in config folder.
5. added the "-DXL.HomeDir=. -Djava.security.auth.login.config=config\authwl.conf" in the java options.
Java code:
public class SignatureLogin {
public static void main(String[] args) throws Exception {
Properties jndi =
ConfigurationClient.getComplexSettingByPath("Discovery.CoreServer").getAllSettings();
tcSignatureMessage signedMsg = tcCryptoUtil.sign("xelsysadm", "PrivateKey");
tcUtilityFactory factory = new tcUtilityFactory(jndi, signedMsg);
tcUserOperationsIntf usrIntf = (tcUserOperationsIntf)factory.getUtility("Thor.API.Operations.tcUserOperationsIntf");
System.out.println("signature login complete");
// Do something with usrIntf here
Map filter = new HashMap();
filter.put("Users.Key", "7464");
tcResultSet rSet = usrIntf.findAllUsers(filter);
rSet.goToRow(0);
System.out.println(rSet.toString());
factory.close();
System.out.println("logout complete");
System.exit(0);
Then ran the java class. I am able to get the connection but when I am using findAllUsers(map) method to search the usr table I am get a nullpointer exception.
Exception in thread "main" java.lang.NullPointerException
at Thor.API.Operations.tcUserOperationsClient.findAllUsers(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at Thor.API.Base.SecurityInvocationHandler$1.run(Unknown Source)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.security.Security.runAs(Security.java:41)
at Thor.API.Security.LoginHandler.weblogicLoginSession.runAs(Unknown Source)
at Thor.API.Base.SecurityInvocationHandler.invoke(Unknown Source)
at $Proxy0.findAllUsers(Unknown Source)
at com.ssi.utils.custom.code.SignatureLogin.main(SignatureLogin.java:26)
I need some help to fix this.
ThanksHi,
Were you able to resolve the issue as I am facing same issue.
I have a custom application deployed on same weblogic managed server where OIM is installed but when I try to find user in OIM it gives me null pointer exception.
I have even checked the username with which connection is established using ioUtilityFactory.getUserName() and it gives me the correct user.
Thanks
Edited by: user1105482 on 26-Apr-2011 04:38 -
Question about java objects and handles?
Let me see if I can explain what I have. Inside my originating Java code, I create an object, let's call it object A, from a class I that I DON'T have the source for. It's not my class. Object A in turn creates an object, let's call it Object B, from a class I don't have the source for. Then Object A creates another object, let's call it Object C, that I DO have the source for, and passes it the reference to Object B that it created. My question is this: In my originating Java code, how do I get a reference to Object B? Or, how can I get the reference to Object C, which would allow me to get the reference to Object B?
Hope everyone understands that?Thanks for the reply. Perhaps I should have mentioned that Object A does not have a method to return a referenece to Objects B and C. That's my problem. Was just wondering if there is some other way to obtain those refereneces. The reason I mentioned that I don't have the source code for Object A is because if I did, I could obviously write a method that would return me the references.
I'm not new to Java, nor am I an expert either. I'm pretty well up-to-speed on object oriented design though.
I'll provide more specifics on my problem just in case there is a solution to my problem. My code (class) is attempting to establish a connection with a mainframe computer through a web server portal using terminal emulation software provided by a 3rd party vendor. They provide an SDK that contains all the java classes necessary to establsih the connection. To establish the connection, you are required to build a java Properties object that contains all the parameters for the connection (host id, etc.) and pass that properties object to the constructor for the "Object A" class. That object actually establishes the session object using the parameters object you pass it. The session gets displayed in a standalone Applet ("Object A" class extends Applet). You can click on the applet, sign in to the system, and do whatever just fine using your keyboard. However, I wish to send commands to the session from my originating java code. The session object has a method to send commands to the session, but to do that, I need a handle to the session object that was created. I don't have that, and it appears they don't provide a method to get that. Looks like the vendor's intent was just for the user to interface with the session/Applet via the keyboard. -
Hi. I've been trying to figure this out for over a week now, and customer support at Thawte is not very helpful.
I purchased the netscape object signing certificate from Thawte. I used it to sign a .jar file compiled and archived by jdk1.1.8(using signtool 1.3). But when I try to load it I get "Applet testApplet class testApplet could not be loaded" If I try to load the unsigned .jar file, it loads fine. When I run the unsigned applet from a local hard drive, it actually asks for permission and can access routines out of the sandbox(and actually works), but when it is run from the server it stops asking for permission(does not work). In either case the signed applet does not load.
Thanks in advance for your help.Certificate if purchased from Thawte. No security dialog. Using Netscape JVM (no plug-in installed on Netscape).
I don't know what you mean by java console...nothing loads on the browser, and the error message I mentioned in the first posting appears on the bottom of the browser. -
Generation of XML file from Java objects using castor
I have the following java file(Customer.java).
public class Customer
private String ID;
private FirstName firstName;
private MiddleName middleName;
private LastName lastName;
private ArrayList address;
public ArrayList getAddress() {
return address;
public void setAddress(ArrayList address) {
this.address = address;
public FirstName getFirstName() {
return firstName;
public void setFirstName(FirstName firstName) {
this.firstName = firstName;
public String getID() {
return ID;
public void setID(String id) {
ID = id;
public LastName getLastName() {
return lastName;
public void setLastName(LastName lastName) {
this.lastName = lastName;
public MiddleName getMiddleName() {
return middleName;
public void setMiddleName(MiddleName middleName) {
this.middleName = middleName;
Using castor i have created an xml file(customer.xml) which has the following format.
<?xml version="1.0" encoding="UTF-8" ?>
- <customer ID="fbs0001">
<FIRSTNAME>Fred</FIRSTNAME>
<MIDDLENAME>B</MIDDLENAME>
<LASTNAME>Scerbo</LASTNAME>
- <ADDRESS>
<FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
<SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
</ADDRESS>
- <ADDRESS>
<FIRSTLINE>ITPL</FIRSTLINE>
<SECONDLINE>Whitefield Bangalore</SECONDLINE>
</ADDRESS>
</customer>
I have used a mapping file to get this output.Is there a way where i can get the output xml in the following format without changing the Java object structure.If yes then please suggest how this can be done.
<?xml version="1.0" encoding="UTF-8" ?>
- <customer ID="fbs0001">
<FIRSTNAME>Fred</FIRSTNAME>
<MIDDLENAME>B</MIDDLENAME>
<LASTNAME>Scerbo</LASTNAME>
</customer>
<ADDRESS>
<FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
<SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
</ADDRESS>
- <ADDRESS>
<FIRSTLINE>ITPL</FIRSTLINE>
<SECONDLINE>Whitefield Bangalore</SECONDLINE>
</ADDRESS>
I mean the output xml file should have the address as a separate tag not withing the root tag customer.Hello,
Castor's own discussion groups might be able to point you to the solution you're looking for (if this use case is possible using Castor).
Oracle has its own object-to-XML mapping tool that is part of the TopLink product. It allows you to map existing objects to an existing XML Schema. This can be done visually using the TopLink Workbench, or programmatically using the TopLink APIs. TopLink OXM also supports the JAXB specification.
Using TopLink OXM to get the desired XML result I would recommend the following. Map the Customer and Address classes to XML, but don't map the relationship between Customer and Address. Then make the calls to the marshaller something like the following:
marshaller.marshal(aCustomer, System.out);
for(int x=0; x<aCustomer.getAddress().size(); x++) {
marshal(aCustomer.getAddress().get(x), System.out);
Example - Using TopLink OXM to map an existing object model to an existing XML Schema:
http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/howto/ox/index.htm
For more information on TopLink object-to-XML mapping:
http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/objectxml/index.html
-Blaise -
Problem with XMLEncoder for complex java object i
Hi All.
My problem with XMLEncoder is it doesnt transfrom java objects without default no arguement constructor. I was able to resolve this in my main java object class, by setting a new persistence delegate, but for other classes that are contained in the main class, they are not being encoded.
Thanks in advance for your answersBetter to put this in java forum :-)
Just check, if this helps.
http://forum.java.sun.com/thread.jspa?threadID=379614&messageID=1623434 -
How to reference multiple instances of the same Java object from PL/SQL?
Dear all,
I'm experimenting with calling Java from PL/SQL.
My simple attempts work, which is calling public static [java] methods through PL/SQL wrappers from SQL (and PL/SQL). (See my example code below).
However it is the limitation of the public static methods that puzzels me.
I would like to do the following:
- from PL/SQL (in essence it needs to become a forms app) create one or more objects in the java realm
- from PL/SQL alter properties of a java object
- from PL/SQL call methods on a java object
However I fail to see how I can create multiple instances of an object and reference one particular object in the java realm through public static methods.
My current solution is the singleton pattern: of said java object I have only 1 copy, so I do not need to know a reference to it.
I can just assume that there will only ever be 1 of said object.
But I should be able to make more then 1 instance of an object.
To make it more specific:
- suppose I have the object car in the java realm
- from PL/SQL I want to create a car in the java realm
- from PL/SQL I need to give it license plates
- I need to start the engine of a scpecific car
However if I want more then 1 car then I need to be able to refrence them. How is this done?
Somehow I need to be able to execute the following in PL/SQL:
DECLARE
vMyCar_Porsche CAR;
vMyCar_Fiat CAR;
BEGIN
vMyCar_Porsche = new CAR();
vMyCar_Fiat = new CAR();
vMyCar_Porsche.setLicensePlates('FAST');
vMyCar_Porsche.startEngine();
vMyCar_Fiat.killEngine();
END;
Thanks in advance.
Best Regards,
Ruben
My current example code is the following:
JAVA:
===
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED CODAROUL."RMG/BO/RMG_OBJECT" as package RMG.BO;
public class RMG_OBJECT {
private static RMG_OBJECT instance = new RMGOBJECT();
private String rmgObjectNaam;
private RMG_OBJECT(){
this.rmgObjectNaam = "NonDetermined";
public static String GET_RMGOBJECT_NAAM () {
String toestand = null;
if (_instance == null) {toestand = "DOES NOT EXIST";} else { toestand = "EXISTS";};
System.out.println("instance : " + toestand);
System.out.println("object name is : " + _instance.rmgObjectNaam);
return _instance.rmgObjectNaam;
public static Integer SET_RMGOBJECT_NAAM (String IN)
try
_instance.rmgObjectNaam = IN;
return 1;
catch (Exception e)//catch
System.out.println("Other Exception: " + e.toString());
e.printStackTrace();
return 5;
} //catch
PL/SQL Wrapper:
==========
CREATE OR REPLACE FUNCTION CODAROUL.SET_RMGOBJECT_NAAM(NAAM IN VARCHAR2) return NUMBER AS
LANGUAGE JAVA NAME 'RMG.BO.RMG_OBJECT.SET_RMGOBJECT_NAAM (java.lang.String) return java.lang.Integer';
Calling from SQL:
==========
CALL dbms_java.set_output(2000);
select CODAROUL.GET_RMGOBJECT_NAAM() from dual;
Edited by: RubenS_BE on Apr 6, 2012 5:35 AM
Edited by: 925945 on Apr 6, 2012 5:41 AMYou can do this by manually creating a new iterator binding in your binding tab.
So instead of dragging the VO directly to the page, go to the binding tab, add a new executable iterator binding, and point to that one from your ELs in the page itself. -
How to use Java code signing certificate in oracle 11i
Hello,
I am try to configure java code signing certificate in 11.5.10.2 application. we got java sign certificate from verisgin. SA's imported the certificate and created alias XXX_XXX with password and passphrase.
I am able to see the my certificate. keytool -list -v -keystore xxx_xxxx.jks -storepass Password.
how do I use it. I am using Enhance Jar Signing for EBS DOC ID 1591073.1.
could you please give me some advice on it?
Thanks
PrinceHussien,
I find out apps keystore keypassword and storepassword, I imported the java code sign certificate. I generated Jar files through adadmin, but I am getting warning error
adogif() unable to generate Jar Filers under JAVA_TOP.
executing /usr/jdk/jdk1.6.0_45/bin/java sun.security.tools.JarSigner keysotre **** -sigfile CUST Signer /apps/......
Error JarSigner subcommand Exited With status 1.
No standard output from jarsigner JarSigner error output: Exception in thread "main" java.lang.NoClassDefFoundError: sun/security/tools/JarSigner Caused by: java.lang.ClassNotFoundException: sun.security.tools.JarSigner at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) Could not find the main class: sun.security.tools.JarSigner. Program will exit. WARNING: The following path(s), defined in /apps2/property/product/tst/appl/cz/11.5.0/java/make/czjar.dep as elements of the output: oracle/apps/cz/runtime/tag WARNING: Copying cztag.lst from the old fndlist.jar ... About to Analyze flmkbn.jar : Fri Nov 22 2013 10:45:51
Please let me know if you have any idea. Thanks Prince -
How can I use XStream to persist complicated Java Object to XML & backward
Dear Sir:
I met a problem as demo in my code below when i use XTream to persist my Java Object;
How can I use XStream to persist complicated Java Object to XML & backward??
See
[1] main code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class PhoneList {
ArrayList<PhoneNumber> phones;
ArrayList<Person> person;
private PhoneList myphonelist ;
private LocationTest location;
private PhoneList(String name) {
phones = new ArrayList<PhoneNumber>();
person = new ArrayList<Person>();
public ArrayList<PhoneNumber> getphones() {
return phones;
public ArrayList<Person> getperson() {
return person;
public void addPhoneNumber(PhoneNumber b1) {
this.phones.add(b1);
public void removePhoneNumber(PhoneNumber b1) {
this.phones.remove(b1);
public void addPerson(Person p1) {
this.person.add(p1);
public void removePerson(Person p1) {
this.person.remove(p1);
public void BuildList(){
location = new LocationTest();
XStream xstream = new XStream();
myphonelist = new PhoneList("PhoneList");
Person joe = new Person("Joe, Wallace");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
Person geo= new Person("George Nixson");
geo.setPhone(new PhoneNumber(925, "228-9999"));
geo.getPhone().setLocationTest(location);
myphonelist.addPerson(joe);
myphonelist.addPerson(geo);
public PhoneList(){
XStream xstream = new XStream();
BuildList();
saveStringToFile("C:\\temp\\test\\PhoneList.xml",convertToXML(myphonelist));
public void saveStringToFile(String fileName, String saveString) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(
new FileWriter(fileName));
try {
bw.write(saveString);
finally {
bw.close();
catch (IOException ex) {
ex.printStackTrace();
//return saved;
public String getStringFromFile(String fileName) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
try {
String s;
while ((s = br.readLine()) != null) {
// add linefeed (\n) back since stripped by readline()
sb.append(s + "\n");
finally {
br.close();
catch (Exception ex) {
ex.printStackTrace();
return sb.toString();
public String convertToXML(PhoneList phonelist) {
XStream xstream = new XStream(new DomDriver());
xstream.setMode(xstream.ID_REFERENCES) ;
return xstream.toXML(phonelist);
public static void main(String[] args) {
new PhoneList();
}[2].
import java.io.Serializable;
import javax.swing.JFrame;
public class PhoneNumber implements Serializable{
private String phone;
private String fax;
private int code;
private String number;
private String address;
private String school;
private LocationTest location;
public PhoneNumber(int i, String str) {
setCode(i);
setNumber(str);
address = "4256, Washington DC, USA";
school = "Washington State University";
public Object getPerson() {
return null;
public void setPhone(String phone) {
this.phone = phone;
public String getPhone() {
return phone;
public void setFax(String fax) {
this.fax = fax;
public String getFax() {
return fax;
public void setCode(int code) {
this.code = code;
public int getCode() {
return code;
public void setNumber(String number) {
this.number = number;
public String getNumber() {
return number;
public void setLocationTest(LocationTest bd) {
this.location = bd;
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(location);
f.getContentPane().add(location.getControls(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
public LocationTest getLocationTest() {
return location;
}[3].
package test.temp;
import java.io.Serializable;
public class Person implements Serializable{
private String fullname;
@SuppressWarnings("unused")
private PhoneNumber phone;
@SuppressWarnings("unused")
private PhoneNumber fax;
public Person(){
public Person(String fname){
fullname=fname;
public void setPhone(PhoneNumber phoneNumber) {
phone = phoneNumber;
public void setFax(PhoneNumber phoneNumber) {
fax = phoneNumber;
public PhoneNumber getPhone() {
return phone ;
public PhoneNumber getFax() {
return fax;
public String getName() {
return fullname ;
public void setName(String name) {
this.fullname = name;
public String toString() {
return getName();
}[4]. LocationTest.java
package test.temp;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class LocationTest extends JPanel implements ChangeListener
Ellipse2D.Double ball;
Line2D.Double line;
JSlider translate;
double lastTheta = 0;
public void stateChanged(ChangeEvent e)
JSlider slider = (JSlider)e.getSource();
String name = slider.getName();
int value = slider.getValue();
if(name.equals("rotation"))
tilt(Math.toRadians(value));
else if(name.equals("translate"))
moveBall(value);
repaint();
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(ball == null)
initGeom();
g2.setPaint(Color.green.darker());
g2.draw(line);
g2.setPaint(Color.red);
g2.fill(ball);
private void initGeom()
int w = getWidth();
int h = getHeight();
int DIA = 30;
int padFromEnd = 5;
line = new Line2D.Double(w/4, h*15/16, w*3/4, h*15/16);
double x = line.x2 - padFromEnd - DIA;
double y = line.y2 - DIA;
ball = new Ellipse2D.Double(x, y, DIA, DIA);
// update translate slider values
int max = (int)line.getP1().distance(line.getP2());
translate.setMaximum(max);
translate.setValue(max-padFromEnd);
private void tilt(double theta)
// rotate line from left end
Point2D pivot = line.getP1();
double lineLength = pivot.distance(line.getP2());
Point2D.Double p2 = new Point2D.Double();
p2.x = pivot.getX() + lineLength*Math.cos(theta);
p2.y = pivot.getY() + lineLength*Math.sin(theta);
line.setLine(pivot, p2);
// find angle from pivot to ball center relative to line
// ie, ball center -> pivot -> line end
double cx = ball.getCenterX();
double cy = ball.getCenterY();
double pivotToCenter = pivot.distance(cx, cy);
// angle of ball to horizon
double dy = cy - pivot.getY();
double dx = cx - pivot.getX();
// relative angle phi = ball_to_horizon - last line_to_horizon
double phi = Math.atan2(dy, dx) - lastTheta;
// rotate ball from pivot
double x = pivot.getX() + pivotToCenter*Math.cos(theta+phi);
double y = pivot.getY() + pivotToCenter*Math.sin(theta+phi);
ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
lastTheta = theta; // save theta for next time
private void moveBall(int distance)
Point2D pivot = line.getP1();
// ball touches line at distance from pivot
double contactX = pivot.getX() + distance*Math.cos(lastTheta);
double contactY = pivot.getY() + distance*Math.sin(lastTheta);
// find new center location of ball
// angle lambda = lastTheta - 90 degrees (anti-clockwise)
double lambda = lastTheta - Math.PI/2;
double x = contactX + (ball.width/2)*Math.cos(lambda);
double y = contactY + (ball.height/2)*Math.sin(lambda);
ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
JPanel getControls()
JSlider rotate = getSlider("rotation angle", "rotation", -90, 0, 0, 5, 15);
translate = getSlider("distance from end", "translate", 0, 100, 100,25, 50);
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(rotate);
panel.add(translate);
return panel;
private JSlider getSlider(String title, String name, int min, int max,
int value, int minorSpace, int majorSpace)
JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
slider.setBorder(BorderFactory.createTitledBorder(title));
slider.setName(name);
slider.setPaintTicks(true);
slider.setMinorTickSpacing(minorSpace);
slider.setMajorTickSpacing(majorSpace);
slider.setPaintLabels(true);
slider.addChangeListener(this);
return slider;
}OK, My questions are:
[1]. what I generated XML by XSTream is very complicated, especially for object LocationTest, Can we make it as simple as others such as Person object??
[2]. after I run it, LocationTest will popup and a red ball in a panel will dsiplay, after I change red ball's position, I hope to persist it to xml, then when I read it back, I hope to get same picture, ie, red ball stiil in old position, How to do that??
Thanks a lot!!Positive feedback? Then please take this in a positive way: if you want to work on persisting Java objects into XML, then GUI programming is irrelevant to that goal. The 1,000 lines of code you posted there appeared to me to have a whole lot of GUI code in it. You should produce a smaller (much smaller) example of what you want to do. Calling the working code from your GUI program should come later.
Maybe you are looking for
-
Windows 8 upgrade problems (touch screen and audio)
my computer is HP touchsmart 600 1005xt and recently upgraded from windows 7 to windows 8 (64-bit) after up grading I noticed that the touch screen does not work and and the speakers also did not work
-
What is utp and who will do this ?how you do unit testing?
Hi.... he asked me like this 1...what is utp and who will do this ?how you do unit testing? thanks and regards, k.swaminath reddy.
-
We currently operate Cisco Prime LMS v4.1 and we're looking to upgrade Cisco PI (Prime Infrastructure) in the next few weeks. Is there an upgrade path from Cisco LMS to PI? The reading I have completed seems to indicate that an upgrade can only be c
-
Assigning Subject to Transaction Type-SDCR
Hi, I want to assign subject 'Urget Correct(Maintenence)' only to Change Request(SDCR). When we create Chnage Request, subject 'Urget Correton' should appear by default. Currently in Subject I can see following options: Development(Implementation) Ad
-
hi, i have created a datalog.txt file to store my test data, i hope transfer these data to excel file and plot xy scale graph, can anybody post a sample for me? thank a lot. actually i saw somebody post some solutions before, because i am using labvi