Java XML realtime transaction
I have a servlet that is doing an http get on an xml file and then is storing its data in an array. I have classes that I created through Websphere that I need to use to parse the xml, but I do not know how to pass in this array. It will work if I use a hard-coded path to an xml document on my drive. Here is the API for the DocumentBuilder that is called by the Factory class:
public Document parse(InputStream arg)
public Document parse(InputStream arg, String arg)
public Document parse(String arg)
public Document parse(File arg)
abstract public Document parse(InputSource arg)
How should I go about parsing this data?
Shouldn't be a problem. Here's the version of the method you need:
"abstract public Document parse(InputSource arg)"
Oh, you don't know what an InputSource is? Conveniently the API documentation has a link to find out. Follow that link.
Similar Messages
-
Using Java XML 1.5 toolkit instead of sapxmltoolkit for xslt mappings
Hi All
We have a case whereby our xlst requires a number of customised java class functions as we are porting webmethods systems across to PI.
eg in the xslt adding
<xsl:when test="function-available('java:concat">
<xsl:value-of select="java:concat($first, $last, $inputparam)"/>
We are running sap PI 7.1 ehp1. I have been referring to a number of posts on how to complete these tasks.
namely we have implemented the example as provided in:
http://help.sap.com/saphelp_nwpi71/helpdata/EN/73/f61eea1741453eb8f794e150067930/frameset.htm
This only works if "Sap XML Toolkit" is enabled in the operational mapping.
Left unticked (default setting in the mapping) whenever a testcase is run I end up with the error "could not compile sytle sheet".
I would like to use the Java 1.5 xml processing capability as it is supposed to perform better than the sapxmltoolkit option and support for the latter will be discontinued in future.
Has anyone been able run the case with sapxmltoolkit enabled?
If so did you add any other libraries for java xml 1.5?
thanksThanks, I would have thought as much, but theres no guide on the deployment.
For now i assume this will fit into the java/ext area and Pi would need a reboot after the libraries are copied.
Has anyone deployed the additional libraries to PI. -
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); -
Java XML Parser:Null Pointer exception in EntityReader
I got NullPointer Exception when trying to parse a XML file which
is pointed by a net URL, (say "http://www..."). The code causing
problem is like:
parser.parse(new URL("http://www.../demo.xml"));
the exception I got is:
java.lang.NullPointerException
java.lang.NullPointerException
at oracle.xml.parser.EntityReader.initXMLInput(Compiled
Code)
at
oracle.xml.parser.EntityReader.<init>(EntityReader.java:64)
at oracle.xml.parser.XMLParser.parse(XMLParser.java:245)
at DemoXML.main(DemoXML.java:47)
The very same code works fine with a simple local file URL and we
also know that the URL exists in correct in XML format because we
can open the URL with IE5.
Another question - where can we get the source for the Java XML
Parser.
nullThis bug has already been reported and will be fixed in our next
release.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Fiona Lu (guest) wrote:
: I got NullPointer Exception when trying to parse a XML file
which
: is pointed by a net URL, (say "http://www..."). The code
causing
: problem is like:
: parser.parse(new URL("http://www.../demo.xml"));
: the exception I got is:
: java.lang.NullPointerException
: java.lang.NullPointerException
: at oracle.xml.parser.EntityReader.initXMLInput
(Compiled
: Code)
: at
: oracle.xml.parser.EntityReader.<init>(EntityReader.java:64)
: at oracle.xml.parser.XMLParser.parse
(XMLParser.java:245)
: at DemoXML.main(DemoXML.java:47)
: The very same code works fine with a simple local file URL and
we
: also know that the URL exists in correct in XML format because
we
: can open the URL with IE5.
: Another question - where can we get the source for the Java
XML
: Parser.
null -
"package java.xml.registry does not exist" error in NetBeans
Hi all
I'm using netbeans for developing webservices and and have to use JAXR. I have downloaded and installed jwsdp1.5.
When I view the source code for the JAXR sample java files that accompany the java EE tutorial in the NetBeans IDE Source Editor, I get the error : package java.xml.registry does not exist.
However, the release note for NetBeans says that it supports JAXR.
Also, when I compile and run the same files using DOS and the ant command, the files work.
Can someone please tell me what to do and how to work on JAXR clients in NetBeans because the Help files don't have any documentation on it nor does the NeBeans Field Guide?Do you have the jaxrpc-api.jar and jaxprc-ri.jar in your classpath?
They are in <wspack1.1 installation>/jaxrpc-1.0.2/lib
Regards,
Bhakti -
Hi all,,
Im just looking for some help with a java xml passer program. Im trying to create a program that will read specific tags and the values that are represented by these tags in the xml file..I have found the following code
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ReadAndPrintXMLFile{
public static void main (String argv []){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
//System.exit (0);
}//end of main
}Im trying to develop this code to work with podcast xml files..Im having a few issuses with this program.. Is there anyone out there that has created a program like this that works with podcast xml files??
Anyone got any suggestions.Please.XML and XSL transformations can be done using most languages and in Java there is strong support for these techniques.
It worries me a little bit that you ask this question though. XML and XSL are no more than a tool to solve SOME problems, but I get the idea that you want to put them on your resume as if they are your main talent. The tool set of the developer is much broader than just some techniques to format and transform data, you need to be able to solve problems in the most efficient way possible, not limiting yourself to only a handful of techniques that you just happen to know a lot about.
What I am trying to say is: it is always good to have knowledge of these techniques, but don't go thinking it is going to guarantee you a job. -
Query on XML Beans replacing Castor Java -XML Bindings
Hello,
We use Castor XML Framework for today Java - XML bindings and were looking for XML Beans replacement.
One of the key problems we face in using XML (maybe a flawed design) is we create XSD for our applications and run Castor to generate Java Classes as Libraries (XMLFramework.jar).
Applications are compiled with these Java libraries and Castor is used to Marshal the Java Object as XML Document when invoking a remote API and at the receiving side it is used to unmarshal back the XML document to Java Object.
Major issues we have seen is that if any XSD (that defines application ICD) changes, we need to re-generate Castor Java classes (new XMLFramework.jar) and re-compile applications that were using these classes with new JAR files..... Thus for small XSD changes the impact is in lot of applications (where an application is an EAR deployed on WLS)
Does XMLBeans help here that I can change XSD without changing all the end-points that use Classes generated out of these XSDs (when additing mandatory or optinal elements) ?
Or there is a flaw in which we have used the Java-XML binding framework like Castor and XMLBeans do not help much ?Can someone please suggest on how I can go about
converting an XML file into word format using Java
?How about POI? -
Java user-defined transaction management not working correctly???
Hi everyone,
I have encountered a problem when using Java user-defined transaction management in my session bean. It threw an exception but I could not work out what that means. Could anyone comment on this? Thanks.
This BrokerBean is a stateless session calling other entities bean to perform some simple operations. There are 2 Cloudscape databases in use. Invoices (EB) use InvoiceDB and all the other EBs use StockDB.
If I comment out the user-defined transaction management code, then everything works fine. Or if I comment out the Invoices EB code, it is fine as well. It seemed to me that there is something wrong in transaction management when dealing with distributed databases.
--------------- source code ----------------------
public void CreateInvoices(int sub_accno) {
try {
utx = context.getUserTransaction();
utx.begin();
SubAcc subAcc = subAccHome.findByPrimaryKey(new SubAccPK(sub_accno));
String sub_name = subAcc.getSubName();
String sub_address = subAcc.getSubAddress();
Collection c = stockTransHome.findBySubAccno(sub_accno);
Iterator i = c.iterator();
ArrayList a = new ArrayList();
while (i.hasNext()) {
StockTrans stockTrans = (StockTrans)i.next();
int trans_id = stockTrans.getTransID();
String tran_type = stockTrans.getTranType();
int stock_id = stockTrans.getStockID();
float price = stockTrans.getPrice();
Invoices invoices = invoicesHome.create(sub_accno, sub_name, sub_address, trans_id, stock_id, tran_type, price);
stockTrans = stockTransHome.findByPrimaryKey(new StockTransPK(trans_id));
stockTrans.remove();
utx.commit();
utx = null;
} catch (Exception e) {
if (utx != null) {
try {
utx.rollback();
utx = null;
catch (Exception ex) {}
// e.printStackTrace();
throw new EJBException("BrokerBean.CreateInvoices(): " + e.getMessage());
--------------- exception ----------------------
Initiating login ...
Enter Username:
Enter Password:
Binding name:`java:comp/env/ejb/BrokerSB`
EJB test succeed
Test BuyStock!
Test BuyStock!
Test BuyStock!
Test BuyStock!
Test SellStock!
Test SellStock!
Caught an exception.
java.rmi.ServerException: RemoteException occurred in server thread; nested exce
ption is:
java.rmi.RemoteException: BrokerBean.CreateInvoices(): CORBA TRANSACTION
_ROLLEDBACK 9998 Maybe; nested exception is:
org.omg.CORBA.TRANSACTION_ROLLEDBACK: vmcid: 0x2000 minor code: 1806
completed: Maybe
at com.sun.corba.ee.internal.iiop.ShutdownUtilDelegate.mapSystemExceptio
n(ShutdownUtilDelegate.java:64)
at javax.rmi.CORBA.Util.mapSystemException(Util.java:65)
at BrokerStub.CreateInvoices(Unknown Source)
at Client.main(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:22
9)
at com.sun.enterprise.appclient.Main.main(Main.java:155)
Caused by: java.rmi.RemoteException: BrokerBean.CreateInvoices(): CORBA TRANSACT
ION_ROLLEDBACK 9998 Maybe; nested exception is:
org.omg.CORBA.TRANSACTION_ROLLEDBACK: vmcid: 0x2000 minor code: 1806
completed: Maybe
at com.sun.enterprise.iiop.POAProtocolMgr.mapException(POAProtocolMgr.ja
va:389)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:43
1)
at BrokerBean_EJBObjectImpl.CreateInvoices(BrokerBean_EJBObjectImpl.java
:265)
at BrokerBeanEJBObjectImpl_Tie._invoke(Unknown Source)
at com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispatchToServant(Ge
nericPOAServerSC.java:520)
at com.sun.corba.ee.internal.POA.GenericPOAServerSC.internalDispatch(Gen
ericPOAServerSC.java:210)
at com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispatch(GenericPOAS
erverSC.java:112)
at com.sun.corba.ee.internal.iiop.ORB.process(ORB.java:255)
at com.sun.corba.ee.internal.iiop.RequestProcessor.process(RequestProces
sor.java:84)
at com.sun.corba.ee.internal.orbutil.ThreadPool$PooledThread.run(ThreadP
ool.java:99)Three things:
first, maybe you should think of putting ut.begin() just before the invoicesHome.create() method and ut.commit() just after the stockTrans.remove() method.It wont solve the current problem but will help in performance once the problem is solved.
second, your utx.commit() is outside the try block. how come the code is compiling then??
third, try doing a SOP call before and after invoicesHome.create() method and see where the problem actually lies.
let us know...
Hi SteveW2,
Thanks for being so helpful. Here are my replies:
Can I just ask why you're not using containermanaged
transactions?The reason why I didn't use container managed
transactions is because I don't really know how to do
that. I am more familiar with this user-defined
transaction handling.
I have attempted to implement the same method in an
entity bean and just let the container manage the
rollback itself. The same exception was thrown when
running the client.
Also, the transaction behaviour is likely to relateto
the app server youre using - which is it?What do you mean by the app server? I am using J2EE
1.3.1 if that is what you meant.
Finally, if your code has a problem rolling back,and
throws an exception, you discard your exception
thereby losing useful information.I have tried to print the exception stack as well, but
it is the same as just printing the general
exception.
This problem is very strange cause if I comment out
the transaction management thing, then everything
works fine. Or if I am only working with 1 single
database, with this user-defined transaction handling,
everything works fine as well.
Here is the error log from J2EE server if you are
interested.
------------ error log ---------------
javax.ejb.TransactionRolledbackLocalException:
Exception thrown from bean; nested exception is:
javax.ejb.EJBException: ejbCreate: Connection
previously closed, open another Connection
javax.ejb.EJBException: ejbCreate: Connection
previously closed, open another Connection
at InvoicesBean.ejbCreate(Unknown Source)
at
InvoicesBean_RemoteHomeImpl.create(InvoicesBean_Remote
omeImpl.java:31)
at InvoicesHomeStub.create(Unknown Source)
at BrokerBean.CreateInvoices(Unknown Source)
at
BrokerBean_EJBObjectImpl.CreateInvoices(BrokerBean_EJB
bjectImpl.java:261)
at BrokerBeanEJBObjectImpl_Tie._invoke(Unknown
Source)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispa
chToServant(GenericPOAServerSC.java:520)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.inter
alDispatch(GenericPOAServerSC.java:210)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispa
ch(GenericPOAServerSC.java:112)
at
com.sun.corba.ee.internal.iiop.ORB.process(ORB.java:25
at
com.sun.corba.ee.internal.iiop.RequestProcessor.proces
(RequestProcessor.java:84)
at
com.sun.corba.ee.internal.orbutil.ThreadPool$PooledThr
ad.run(ThreadPool.java:99)
javax.ejb.TransactionRolledbackLocalException:
Exception thrown from bean; nested exception is:
javax.ejb.EJBException: ejbCreate: Connection
previously closed, open another Connection
at
com.sun.ejb.containers.BaseContainer.checkExceptionCli
ntTx(BaseContainer.java:1434)
at
com.sun.ejb.containers.BaseContainer.postInvokeTx(Base
ontainer.java:1294)
at
com.sun.ejb.containers.BaseContainer.postInvoke(BaseCo
tainer.java:403)
at
InvoicesBean_RemoteHomeImpl.create(InvoicesBean_Remote
omeImpl.java:37)
at InvoicesHomeStub.create(Unknown Source)
at BrokerBean.CreateInvoices(Unknown Source)
at
BrokerBean_EJBObjectImpl.CreateInvoices(BrokerBean_EJB
bjectImpl.java:261)
at BrokerBeanEJBObjectImpl_Tie._invoke(Unknown
Source)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispa
chToServant(GenericPOAServerSC.java:520)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.inter
alDispatch(GenericPOAServerSC.java:210)
at
com.sun.corba.ee.internal.POA.GenericPOAServerSC.dispa
ch(GenericPOAServerSC.java:112)
at
com.sun.corba.ee.internal.iiop.ORB.process(ORB.java:25
at
com.sun.corba.ee.internal.iiop.RequestProcessor.proces
(RequestProcessor.java:84)
at
com.sun.corba.ee.internal.orbutil.ThreadPool$PooledThr
ad.run(ThreadPool.java:99)
What is "connection previously closed, open another
connection"? This might be the cause of the
exception.
I'll keep trying till I solve the problem.
Thanks,
Sasuke -
Hi ,
I use weblogic 9.2 server . I got this error and am getting this again and again ...
actually this is a test bed environment , newly setup one based on production environment.
can any one help me out ??
Caused by: java.rmi.RemoteException: Transaction Rolledback.; nested exception is:
weblogic.transaction.internal.TimedOutException: Transaction timed out after 122 seconds
BEA1-0012E646C6D14C8E60D6
at weblogic.ejb.container.internal.EJBRuntimeUtils.throwRemoteException(EJBRuntimeUtils.java:95)
at weblogic.ejb.container.internal.BaseEJBObject.postInvoke1(BaseEJBObject.java:514)
at weblogic.ejb.container.internal.StatelessEJBObject.postInvoke1(StatelessEJBObject.java:72)
at weblogic.ejb.container.internal.BaseEJBObject.postInvokeTxRetry(BaseEJBObject.java:374)
at com.mountain.molehill.ejb.controller.HandleSystemAdminEJB_rbrj0q_EOImpl.handleEvent(HandleSystemAdminEJB_rbrj0q_EOImpl.java:365)
... 29 more
Caused by: weblogic.transaction.internal.TimedOutException: Transaction timed out after 122 seconds
BEA1-0012E646C6D14C8E60D6
at weblogic.transaction.internal.ServerTransactionImpl.wakeUp(ServerTransactionImpl.java:1721)
at weblogic.transaction.internal.ServerTransactionManagerImpl.processTimedOutTransactions(ServerTransactionManagerImpl.java:1560)
at weblogic.transaction.internal.TransactionManagerImpl.wakeUp(TransactionManagerImpl.java:1919)
at weblogic.transaction.internal.ServerTransactionManagerImpl.wakeUp(ServerTransactionManagerImpl.java:1468)
at weblogic.transaction.internal.WLSTimer.timerExpired(WLSTimer.java:35)
at weblogic.timers.internal.TimerImpl.run(TimerImpl.java:265)
at weblogic.work.ServerWorkManagerImpl$WorkAdapterImpl.run(ServerWorkManagerImpl.java:518)
... 2 more
DO I NEED TO CHANGE ANYTHING IN THE CONFIGURATION
Thanks in advanceAdding to the above post >>>
I also get the following errors
java.sql.SQLException: The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 121 seconds
BEA1-0011E646C6D14C8E60D6]'. No further JDBC access is allowed within this transaction.
at weblogic.jdbc.wrapper.JTSConnection.checkIfRolledBack(JTSConnection.java:192)
at weblogic.jdbc.wrapper.JTSConnection.checkConnection(JTSConnection.java:202)
at weblogic.jdbc.wrapper.ResultSet.preInvocationHandler(ResultSet.java:59)
at weblogic.jdbc.wrapper.ResultSet_oracle_jdbc_driver_OracleResultSetImpl.getString(Unknown Source)
at org.hibernate.type.StringType.get(StringType.java:16)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:77)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:68)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:80)
at org.hibernate.type.ComponentType.hydrate(ComponentType.java:422)
at org.hibernate.type.ComponentType.nullSafeGet(ComponentType.java:182)
at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:726)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:284)
at org.hibernate.loader.Loader.doQuery(Loader.java:395)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:210)
at org.hibernate.loader.Loader.doList(Loader.java:1562)
at org.hibernate.loader.Loader.list(Loader.java:1545)
at org.hibernate.hql.classic.QueryTranslatorImpl.list(QueryTranslatorImpl.java:886)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:840)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:74)
2007-11-19 03:19:53,358|WARN|org.hibernate.util.JDBCExceptionReporter|logExceptions|SQL Error: 0, SQLState: null
2007-11-19 03:19:53,358|ERROR|org.hibernate.util.JDBCExceptionReporter|logExceptions|The transaction is no longer active - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException: Transaction timed out after 121 seconds
BEA1-0011E646C6D14C8E60D6]'. No further JDBC access is allowed within this transaction. -
How to install JAVA , XML on 10.2.0.4.0 (AIX).
Hi All,
How to install JAVA , XML on 10.2.0.4.0 (AIX).
Any document/link/ metalink doc would be highly appreciated
Thanks In advance
ivwThanks for reply.
I dont have dbca .. only ssh access, no gui
sqlplus '/ as sysdba'
SQL*Plus: Release 10.2.0.4.0 - Production on Fri Aug 21 02:24:59 2009
Copyright (c) 1982, 2007, Oracle. All Rights Reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, Data Mining and Real Application Testing options
SQL> select count(*), owner from all_objects
where object_type like '%JAVA%' group by owner;
no rows selected
so java is not loaded in the database
I believe in 9i we have to run this
@?/javavm/install/initjvm.sql
@?/xdk/admin/initxml.sql
@?/xdk/admin/xmlja.sql
@?/rdbms/admin/catjava.sql
Is there is any change in 10g regarding these above steps?
Edited by: ivw on Aug 20, 2009 9:28 PM -
Learning Path: Java & XML
Right now I'm learning my way through Java as a novice to programming aside from a little bit of script language knowledge. I want to start developing Web Services using Java, XML/SOAP. Being a beginner should I wait until I have a strong foundation in Java or can XML/SOAP be learned concurrently to Java?
As for specific Java technologies is ther ea specific path that should be followed? I'd like to learn JavaBeans and JSP, should one be studied before the other?One doesn't really build on the other, so there's no required path to follow. Since XML is as OO as a scripting language gets, there's no reason you can't learn it along with Java; but using XML doesn't require a strong programming background.
As for JavaBeans and JSPs, again they're totally separate and one doesn't require the other. If you're doing a lot of GUI building and writing code you plan to reuse, learn about JavaBeans soon. On the other hand, if you're main goal is web development, you'll want to pick up Servlets and JSPs sooner. -
Which Book is good for e-commerce using JAVA & XML
I want to find a Book that is good for e-commerce using JAVA & XML,
or where can find JAVA & XML new and develop?
can you suggest me?
Thanks very much!I can recommend "Java and XML" from O'Reilly. It's a very good book.
-
I Downloaded the JavaXMLPack-summer-02_01 and am a little unsure about configuration and use...
The documentation says:"
To use the Java XML Pack technologies, you need to set the home directory for each technology as follows:
JAVA_XML_PACK_HOME to the directory where the java xml pack has been installed.
JAXM_HOME to <JAVA_XML_PACK_INSTALL>/java_xml_pack-summer-02_01/jaxm-1.1_01
JAXP_HOME to <JAVA_XML_PACK_INSTALL>/java_xml_pack-summer-02_01/jaxp-1.2_01
JAXR_HOME to <JAVA_XML_PACK_INSTALL>/java_xml_pack-ummer-02_01/jaxr-1.0_02
JAXRPC_HOME to <JAVA_XML_PACK_INSTALL>/java_xml_pack-ummer-02_01/jaxrpc-1.0_01
but nothing about where to set this...
I tried to set those as environment variables- s�that right???
Next thing:
When I want to use the JAXM Libraries I have to set the .JAR Files as Classpath - Seems strage to me...
And now the Problem:
I compiled the StandeAlone.java Sample from "/jaxm-1.1_01/samples/standalone"
And when I start the class File I get the Error message
java.lang.NoClassDefFoundError: javax/xml/soap/SOAPBody
at DataExchange.<init>(EOS.java:67)
at EOS.init(EOS.java:14)
at sun.applet.AppletPanel.run(AppletPanel.java:341)
at java.lang.Thread.run(Thread.java:536)I have been having similar problems. I have set the variables you mentioned in my .bashrc file and set the classpath variable to include them. However the compiler still can't find them and I get a slew of NoClassDefFoundError exceptions when trying to compile code which uses the xml stuff.
The strange thing is that the classpath variable was empty before I added the java xml stuff to it so I don't know how it finds the core java classes. It gets this information from somewhere and if I could find out where this is then I could add the xml stuff to it and everything will be fine.
Any ideas on where java is getting the location of the core classes from? -
TYLAR Java/XML binding technology
In WL10, when using the default TYLAR Java/XML data bindings for our web service implementation, is there a way to get the XML that was used to produce an instance of the TYLAR-generated object? I would assume WebLogic exposes an API that I could use to accomplish this. Thanks.
AFAIK, Tylar binding is for internal used (implement JAX-RPC 1.1 specification). If you want to handle Xml Databinding, you should try XmlBeans or JAXB in JAXWS.
-LJ -
Java XML Digital Signature API, how to sign different files
Hello,
I need to sign several files: binary and/or xml (in some cases just part of xml), and to implement digitla signatures in xAdes standard. So I'm looking to use Java XML Digital signature API, but can't find any examples, that would cover issues I encountered:
How to sign binary file?
Just to sign some simple "aaa.png" file and have it's signature in XML. How in right way to create referece?
(should it be something like: Reference ref = fac.newReference("aaa.png", fac.newDigestMethod(DigestMethod.SHA1, null), null, null, null); )
And how to pass file for signing? what to add/change to this code:
Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("aaa.png"));
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
(I have only found some information about needing to "dereference" or so - but no examples, how to make things work.)
How to sing several different files?
As I wrote before, several files needs to be signed, but in all examples, it's only one Document object (and only one file), how/where to add more files and if API will be capable to deal with such thing?
In one of examples what I have to achive was such code:
<Reference URI="aaa.png" xmlns="http://www.w3.org/2000/09/xmldsig#">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>8rl/xzjAnE4yQQ2LTBvFTU2JH+c=</DigestValue>
</Reference>
If I do write code like: "fac.newReference("aaa.png", <...> );
I'll get an error during signing: signature.sign(dsc);
*"java.net.MalformedURLException: no protocol: aaa.png"*
How to avoid this?
Also, from exmaple (what to reach) above:
<Reference URI="aaa.png" xmlns="http://www.w3.org/2000/09/xmldsig#">
There is additional attribute "xmlns=<...>" - the question is if it is possible to add it by XMLSignatureFactory.newReference ?
Java API adds a lot of prefixes "ds:" , like:
<...>
<ds:Reference URI="file:/D:/try5/SignableMetadata0.xml">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</ds:Transforms>
<...>
Is it possible to avoid them?
Any help on any of these questions would be very appreciatedHi,
I would like to sign a specific part of a xml message [Only the contents under the <Buyer> tag]. I have also pasted the code which i used to do this. I am getting an output xml after the xml is signed, but when I validate the xml , the xml is valid even after I change the xml contents. Could you pls tell me what I am doing wrong here. I want to know whether the xpath implementation which I have done is correct.
<?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>
// The code which i have used to perform the xpath transformation.
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
XPathFilterParameterSpec xpathFilter = new XPathFilterParameterSpec("PurchaseOrder/Buyer");
javax.xml.crypto.dsig.Reference ref = fac.newReference
("", fac.newDigestMethod(DigestMethod.SHA1, null),
Collections.singletonList
(fac.newTransform
(Transform.XPATH, xpathFilter)),
null, null);
SignedInfo si = fac.newSignedInfo
(fac.newCanonicalizationMethod
(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
KeyStore ks = KeyStore.getInstance("JKS");
char[] password = "changeme".toCharArray();
ks.load(new FileInputStream("c:\\KeyStore"), password);
KeyStore.PrivateKeyEntry keyEntry =
(KeyStore.PrivateKeyEntry) ks.getEntry
("EISKeys", new KeyStore.PasswordProtection(password));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// System.out.println("X509Certificate:"+cert);
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Instantiate the document to be signed.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse
(new FileInputStream("C:\\Life2012\\DigSign\\ACORD_Request.xml"));
NodeList rootChildList = doc.getDocumentElement().getChildNodes();
Node bodyNode = null;
for(int i=0;i<rootChildList.getLength();i++){
if("Buyer".equalsIgnoreCase(rootChildList.item(i).getLocalName())){
bodyNode = rootChildList.item(i);
System.out.println("Body Node is obtained"+bodyNode);
break;
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
//DOMSignContext dsc = new DOMSignContext
// (keyEntry.getPrivateKey(), doc.getDocumentElement());
// Sign only the body node
DOMSignContext dsc = new DOMSignContext
(keyEntry.getPrivateKey(), bodyNode);
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
Maybe you are looking for
-
Cannot change table-name in persistent.xml
I've successful deployed a Entity EJB on "SAP Enterprise Portal 6.0 SP4 NetWeaver Developer Sneak Preview" After changing the Table Name in persistent.xml and re-deploying the new EAR, the Entity EJB still writes to the old table. How can I get SAP W
-
How to select a specific XML node with XPath
Hi, I'm trying to a select a specific node from my XML data using the XPath Builder. For example, say I have a process variable 'xmlData' with the following contents: User 1 101 User 2 102 I can successfully use the following express
-
MIRO and Payment document link
Dear Experts, Please guide me, How to get the link between payment document and Miro document , any table or report? Regards Chandu
-
HI, PL GIVE THE SYSTEM CONFIGURATION DETAILS FOR INSTALLING SAP-ECC 6.0.
-
I have a powermac g4 quicksilver in which I have installed a normal airport wireless card in the dedicated slot. How can I connect to my router? It is not an apple airbase station but does it need to be? How can I connect to my router?