Java 1.4 Logging API

I am having some problem with the Formatter. I have a ConsoleHandler. I set its formatter to my custom formatter. My custom formatter simply extends Formatter class and implement formate(LogRecord) method.
when I run my program, the ConsoleHandler not only print out my formatted output, but also a SimpleFormatter formatted output. Do I need to create my own StreamHandler instead of using ConsoleHandler?
Has anybody had this problem before?
Thanks,

Could you post some code? My initial reaction is that you probably did not make a call to LoggerInstance.setParentHandlers(false);
Here is a Formatter class:
import java.util.logging.*;
public class MyFormatter extends Formatter
  public String format(LogRecord r)
    return "[" + "My Formatted Message: " + r.getMessage() + "]" +
        System.getProperty("line.separator");
}And here is some test code for the custom formatter:
import java.util.logging.*;
public class Main
  public static void main(String[] args)
    ConsoleHandler ch = new ConsoleHandler();
    ch.setFormatter(new MyFormatter());
    Logger l = Logger.getAnonymousLogger();
    // Keep in mind that your anonymouslogger will have initially
    // 0 handlers; it will by default send the LogRecords to the
    // ParentHandler
    l.addHandler(ch);
    // Uncomment this line so that parent handlers do not get called
    l.setUseParentHandlers(false);
    l.info("Hello World");
}I hope this is somewhat usefull.
- Chris

Similar Messages

  • Logging api hangs

    Im starting a java application from an applet calling Runtime.getRuntime().exec("java bla bla bla")
    Worked fine until I implemented Java 1.4 logging api. Now the application hangs after writing a few info lines to a FileHandler log. It's clearly the logger that hangs because if I set log level = OFF the the program runs just fine.
    Has anyone seen anything similar?
    * To make it harder to debug, the problem only occurs when starting the application from an applet.

    That might happen that spawn process generates lots of output.
    Runtime.getRuntime().exec() returns object of type java.lange.Process. That object provide access to the stdout and stderror of the newly created process. If those streams are not cleaned properly then process will hang as soon as OS buffers of those stdout and stderr streams get full.
    One way to work around it just read output from the process and throw it away. You can try using something like this:
    package com.xxx;
    import java.io.InputStream;
    public class ProcessOutputWaster {
        public ProcessOutputWaster(Process process)
            throws Exception {
            createWorker(process.getErrorStream()).start();
            createWorker(process.getInputStream()).start();
        protected Worker createWorker(InputStream is) {
            return new Worker(is);
        protected static class Worker
                  extends Thread {
            private InputStream inputStream_;
            public Worker(InputStream inputStream) {
                inputStream_ = inputStream;
            public void run() {
                if (getInputStream() != null) {
                    try {
                        byte[] buffer = new byte[1024];
                        int read;
                        while(true) {
                            read = inputStream_.read(buffer);
                            if (read < 0)
                               break;
                    catch(Exception ex) {
                        Handle the error some how. E.g. show the error box.
    Process process = Runtime.getRuntime().exec(strCommand);
    ProcessOutputWaster outputWaster = new ProcessOutputWaster(process);

  • Practical use of Java Logging API

    There was a recent technical tip about the Java Logging API, but after reading it I still don't understand how to use it in a real situation.
    Can anyone help me with this with a practical example?
    At the moment I have try-catch clauses that catch exceptions and print a message in a System.err log that I can consult if there's a specific problem.
    How should I be using the Logging API? I feel sure that it can help me, but can't see how.
    Thanks for any practical information.

    What if you don't want to write to system.err anymore? What if you need to write something to the windows event log? What if system.err is irrelevant (nt service), ...
    Btw, lots of examples on the JDK1.4 logging api:
    http://www.esus.com/docs/GetIndexPage.jsp?uid=265

  • Customize Java logging API

    Want to customize java.util.logging api, like write message to message queue, xml file, etc. Would you guys give me some useful suggestion or resource or link? Thanks.

    Just write a sub-class of Handler such as this:
    public class JMSHandler extends Handler {
    }Look into the JDK source code such as MemoryHandler and StreamHandler on how to implement it.

  • Problem with java logging API

    Hi there
    It`s the first time I`m using (I have to use) the standard java logging API.
    My need is to integrate it in an existing web-application based on struts.
    So my first step was to include the following code into an Struts Action-class:
    FileHandler file = new FileHandler("/pathToLogFile/myLogFile.log",true);
    file.setFormatter(new SimpleFormatter());
    logger.info("create info");
    By intention is to have exactly one log-file for the whole application, but indeed I'm getting multiple log-files, even for each request of one and the same Action/Servlet class, like
    myLogFile.log
    myLogFile.log.1
    myLogFile.log.2
    myLogFile.log.3
    Why does using append=true not work in the constructor of "FileHandler"
    Do I have to close the FileHandler each time I've used it?
    Is this a known issue?
    Thanks for any responds!

    @ Stone.li
    First, thanks for your answer.
    perhaps my question was quite confusing .... but my need is just
    to establish the logging API in an existing Web-Application and to have exactly one log-file for the whole application. This means I would have to provide in each servlet a FileHandler referencing to the log-file. I thought it would be part of the job of the logging API to synchronise this file access.

  • Logging API: Java 1.5 logs a lot in FINE, etc.

    I noticed that my application log contains a lot more entries since I use Java 1.5 when I log fine/finer/finest messages. I tried to workaround this by just change the log levels of my loggers (by inspecting the logger name prefixes). But the Java messages still log:
         * Set level for all registered loggers of the LogManager.
         * @param level New level to set.
         * @param prefix Optional prefix string for loggers to consider.
        static public void setGlobalLevel(Level level, String prefix) {
            if (level != null) {
                LogManager logManager = LogManager.getLogManager();
                if (logManager != null) {
                    Enumeration<String> enu = logManager.getLoggerNames();
                    boolean first = true;
                    while (enu.hasMoreElements()) {
                        String loggerName = enu.nextElement();
                        if (prefix == null || loggerName.startsWith(prefix)) {
                            Logger logger = logManager.getLogger(loggerName);
                            if (logger != null) {
                                logger.setLevel(level);
                            }//else: logger unavailable
                            if (first) {
                                logger.log(Level.CONFIG, "Global log level changed to "+level);
                                first = false;
                    }//next logger
                }//else: LogManager unavailable
            }//else: level unavailable
        }//setGlobalLevel()

    Okay, I try to explain it differently. SInce Java 1.5, why I log messages with level FINE, FINER, or FINEST, I get lots of additional entries like:
    2005-04-19 13:13:22.076 FINER focus owner is javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.076 FINER >>> java.awt.event.KeyEvent[KEY_PRESSED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_LEFT] on frame0 [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.404 FINER focus owner is javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.404 FINER >>> java.awt.event.KeyEvent[KEY_RELEASED,keyCode=9,keyText=Tabulator,keyChar=Tabulator,modifiers=Alt,extModifiers=Alt,keyLocation=KEY_LOCATION_STANDARD] on frame0 [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.716 FINER focus owner is javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.716 FINER >>> java.awt.event.KeyEvent[KEY_RELEASED,keyCode=18,keyText=Alt,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_LEFT] on frame0 [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE >>> java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite=null,oldState=0,newState=0] on frame0 [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite=null,oldState=0,newState=0] on frame0 [java.awt.focus.DefaultKeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE Active de.icomps.prt.gui.ClientReportPrinterConsole[frame0,110,46,1140x794,invalid,layout=java.awt.BorderLayout,title=iComps Client Report Printer 1.1.6,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,4,23,1132x767,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true], Current focused de.icomps.prt.gui.ClientReportPrinterConsole[frame0,110,46,1140x794,invalid,layout=java.awt.BorderLayout,title=iComps Client Report Printer 1.1.6,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,4,23,1132x767,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true], losing focus de.icomps.prt.gui.ClientReportPrinterConsole[frame0,110,46,1140x794,invalid,layout=java.awt.BorderLayout,title=iComps Client Report Printer 1.1.6,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,4,23,1132x767,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true] opposite null [java.awt.focus.DefaultKeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE >>> java.awt.event.FocusEvent[FOCUS_LOST,temporary,opposite=null] on javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE java.awt.event.FocusEvent[FOCUS_LOST,temporary,opposite=null] on javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.DefaultKeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE java.awt.event.FocusEvent[FOCUS_LOST,temporary,opposite=null] on javax.swing.JButton[,12,97,161x33,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@19d3b3a,flags=424,maximumSize=,minimumSize=,preferredSize=,defaultIcon=javax.swing.ImageIcon@19050a0,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Log-Datei,defaultCapable=true] [java.awt.focus.Component]
    2005-04-19 13:13:22.732 FINE >>> java.awt.event.WindowEvent[WINDOW_DEACTIVATED,opposite=null,oldState=0,newState=0] on frame0 [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.732 FINE java.awt.event.WindowEvent[WINDOW_DEACTIVATED,opposite=null,oldState=0,newState=0] on frame0 [java.awt.focus.DefaultKeyboardFocusManager]
    2005-04-19 13:13:22.748 FINER Setting global active window to null, old active de.icomps.prt.gui.ClientReportPrinterConsole[frame0,110,46,1140x794,invalid,layout=java.awt.BorderLayout,title=iComps Client Report Printer 1.1.6,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,4,23,1132x767,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true] [java.awt.focus.KeyboardFocusManager]
    2005-04-19 13:13:22.748 FINE >>> java.awt.event.FocusEvent[FOCUS_LOST,permanent,opposite=null] on frame0 [java.awt.focus.KeyboardFocusManager]
    So, I try just to set the levels FINE, FINER, FINEST for my applications loggers that all have logger names being the Java package name and class name (e.g. "one.two.three.MyClass"). So, I change the levels of all logers who's lagger name starts with "one.two.three". That should lead to log messages of FINE/FINER/FINEST from my loggers. But I still get the log messages of Java internal loggings like
    >>> java.awt.event.FocusEvent[FOCUS_LOST,permanent,opposite=null] on frame0
    from java.awt.focus.KeyboardFocusManager.

  • 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);

  • How to set NC Log API

    Hi all,
    I want to use the following NC log API,but I don't know how to initialize the interface's java object and set the parameter "ApplicationVO".
    Interface LogNCApplicationInterface
    Method ApplicationVO addNDone(ApplicationVO applicationvo)
    Please help me.Thank you!
    Qiang Liu

    if you just need to log an NC the minimum fields you need to set are the following:
    CreateNCRequest ncRequest = new CreateNCRequest();
    ncRequest.setActivity("NC500"); // activity where NC is logged - can be any name
    ncRequest.setSfcRef(new SFCBOHandle(site, sfcParent).toString());// the SFC for which you are reporting an NC
    // ncRequest.setValidateNCCodeOperation(true); // no need to set it, it's true by default
    // nc code reference for nc code that is reported
    // nc code must exist in the system
    ncRequest.setNcCodeRef(new NCCodeBOHandle(site,"NCCODE").toString());
    // required custom fields must be set
    CreateNCResponse ncResponse = ncPSI.createNC(ncRequest);

  • Setting Logging API config file

    Hi,
    Is there a way I can set the Logging API's config file (java.util.logging.config.file) from within my program? I have tried using System.setProperty but it doesn't seem to work. The only way I seem to be able to set the property is with -D on the command line.
    Thanks
    Rob

    Is there a way I can set the Logging API's config file (java.util.logging.config.file) from within my program? I have tried using System.setProperty but it doesn't seem to work. The only way I seem to be able to set the property is with -D on the command line.Read the Logging Overview Dokumentation
    anyway
    InputStream inputStream = new FileInputStream("logging.properties");
    LogManager.getLogManager().readConfiguration(inputStream);
    ...

  • Is this logging code faster than using a standard logging API like log4J

    is this logging code faster than using a standard logging API like log4J or the logging API in java 1.4
    As you can see my needs are extremely simple. write some stuff to text file and write some stuff to dos window.
    I am thinking about using this with a multi threaded app. So all the threads ~ 200 will be using this simultaneously.
    * Tracer.class logs items according to the following criteria:
    * 2 = goes to text file Crawler_log.txt
    * 1 = goes to console window because it is higher priority.
    * @author Stephen
    * @version 1.0
    * @since June 2002
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    class Tracer{
    public static void log(int traceLevel, String message, Object value)
    if(traceLevel == 1){
    System.out.println(getLogFileDate(new Date()) +" >" + message+ " value = " + value.toString()););
    }else{
    pout.write(getLogFileDate(new Date()) +" >" + message + " value = " + value.toString());
    pout.flush();
    public static void log(int traceLevel, String message )
    if(traceLevel == 1){System.out.println(message);
    }else{
    pout.write(message ) ;
    pout.flush();
    //public static accessor method
    public static Tracer getTracerInstance()
    return tracerInstance;
    private static String getLogFileDate(Date d )
    String s = df.format(d);
    String s1= s.replace(',','-');
    String s2= s1.replace(' ','-');
    String s3= s2.replace(':','.');
    System.out.println("getLogFileDate() = " + s3 ) ;
    return s3;
    //private instance
    private Tracer(){
    System.out.println("Tracer constructor works");
    df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    date = new java.util.Date();
    try{
    pout = new PrintWriter(new BufferedWriter(new FileWriter("Crawler_log"+getLogFileDate(new Date())+".txt", true)));
    pout.write("**************** New Log File Created "+ getLogFileDate(new Date()) +"****************");
    pout.flush();
    }catch (IOException e){
    System.out.println("**********THERE WAS A CRITICAL ERROR GETTING TRACER SINGLETON INITIALIZED. APPLICATION WILL STOP EXECUTION. ******* ");
    public static void main(String[] argz){
    System.out.println("main method starts ");
    Tracer tt = Tracer.getTracerInstance();
    System.out.println("main method successfully gets Tracer instance tt. "+ tt.toString());
    //the next method is where it fails - on pout.write() of log method. Why ?
    tt.log(1, "HIGH PRIORITY");
    System.out.println("main method ends ");
    //private static reference
    private static Tracer tracerInstance = new Tracer();
    private static Date date = null;
    private static PrintWriter pout = null;
    public static DateFormat df = null;
    }

    In general I'd guess that a small, custom thing will be faster than a large, generic thing with a lot of options. That is, unless the writer of the small program have done something stupid, og the writer of the large program have done something very smart.
    One problem with java in this respect is that it is next to impossible to judge exactly how much machine-level processing a single java statement takes. Things like JIT compilers makes it even harder.
    In the end, there is really only one way to find out: Test it.

  • How come logging is so hard? - JDK1.4 Logging API

    Have a small project on hand. A standalone java program trigged by unix cron job and do some data cleaning. Need to implement a very simple logger. Tried to use JDK1.4 Logging API, here's my code:
    public class MyLogManager {
         public final static String NAME = "mylog";
         public final static String LOG_FILE_NAME = "C:/my.log";
         private static Logger logger;
         static {
              try {
                   logger = Logger.getLogger(NAME);
                   Handler fh = new FileHandler(LOG_FILE_NAME);
                   fh.setFormatter(new SimpleFormatter());
                   logger.addHandler(fh);
                   logger.setLevel(Level.ALL);
              } catch (Exception e) {
                   System.out.println("Unable to initialize logger: " + e.toString());
                   System.exit(1);
         public static Logger getLogger() {
              return logger;
    and use MyLogManager.getLogger().info("message") to log message.
    It works and my.log was generated with log message. However, the problem is everytime a new job (java myprogam ...) runs, it deletes the old log file and create a new one.
    I want the message to be appended by the end of old log file. What should I do? Any help?

    Use log4j (google for it - it's on http://jakarta.apache.org).
    If log4j.jar is in your classpath, the JDK 1.4 logging framework will use it automatically. Then all you have to do is to configure a log4j.properties file in your classpath to log wherever you want it to.
    And log4j is sorta-smart about multiple programs logging to the same file.

  • Log4j VS other logging APIs

    I need a logging API for my current application, and I was going to go with log4j. I just wanted to check first to make sure that there were no other more popular loggers, or logging APIs build directly into Java 1.5.
    Thanks for any info,
    John

    Log4j has extensive use within the J2EE community, while java.util.logging is (relatively) new. If you're not sure you'll stick to one or the other, you could use a higher-level API like Apache's commons logging :
    http://jakarta.apache.org/commons/logging/Then you could use whatever logging solution you choose and switch at a later time without impacting your program in a significant way.

  • Logging API

    I am trying to use the logging APIs within a channel's java application code. The code will successfully create the log file, but I can not get it to log any information into that file. Can anyone point me to what I might be missing?
    I am running Portal 6.0 on Solaris 2.9 with JVM version 1.3.1_04.
    Here is the code I am working with, which is more or less right out of the developers guide. When I execute it i get no errors, no exceptions, no data in log file.
    Any help would be appreciated.
    Bill
          try {
                SSOTokenManager manager = SSOTokenManager.getInstance();
                token = manager.createSSOToken(req);
                if (!manager.isValidToken(token)) {
                        message = "*** InValid Token. ***";
          } catch(Exception e){
                        message = "*** SSOToken Exception. ***" + e.toString();
           try {
                      LogManager logger = new LogManager(token);
                      logger.create("SampleLog.log");
                      LogRecord lr = new LogRecord("Session", "Sample Data");
                      logger.write(lr, "SampleLog.log");
            } catch (Exception e) {
                          content.append( "Logging Error: " + e.toString() + "\n");             
            }

    Thanks for your feedback.
    BEA is on the expert group of this JSR and we are tracking this standard.
    We will consider implementing this API in the next release.
    Wong Kok Wai <[email protected]> wrote in message
    news:[email protected]..
    Sun has released the public draft of the Logging API
    (http://java.sun.com/aboutJava/communityprocess/review/jsr047/). Suggest
    for WLS to implement this API, except the package name, to minimise
    porting in future.

  • Does the logging API provide  "Asynchronous File Handler", like log4j ?

    Hi,
    One more question about java.util.logging:
    Does sun provide a standard "Asynchronous File Handler", equivalent to log4j AsyncFileAppender ?
    The idea is, logging requests are placed into a queue, which is being consumed by a dedicated logging-IO thread.
    Thanks.

    it's a shame, really. the Logging API was blatantly inspired by Log4J, but it's just such a poor cousin in so many ways...

  • Not able to create log files using logging API's

    Hi All,
    I am trying to make use of logging API's of SAP in my standalone java project.
    Below is the following line of code.
    public class TestLog {
    private static final com.sap.tc.logging.Location logger = com.sap.tc.logging.Location.getLocation(testLog.class);
    static
    logger.setEffectiveSeverity(Severity.INFO);
    // logger.addLog(new ConsoleLog());
    logger.addLog(new FileLog("C://temp//testOutput.log", new ListFormatter()));
    public static void main(String[] args) {
    writeLog();
    public static void writeLog()
    logger.entering("entering");
    logger.debugT("In Write Log");
    logger.exiting("exiting");
    But the above codes does not create the testOutput.log file in the dir which i have mentioned . I have added sap.comtcloggingjavaimpl.jar from eclipse plugin folder to make use of these API's .
    Could you please help me on this .
    Thanks & Regards,
    Mitul Adhia.

    Hi,
    Also try adjusting the severity level in nwa(Netweaver Administrator).
    1. Go to http://<host-name>:<port-number>/nwa
    2. Select Problem Management from tabs.
    3. In that select Logs and Traces tab.
    4. Select Log configuration
    5. in Show select Tracing Locations
    6. Select your application and set the severity to be the one lower than that you specify in your code.
    Hope it helps.
    Regards,
    Srinivasan Subbiah

Maybe you are looking for