Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:TestSign.java

/**
 * Method main/* w  ww. j  a  v  a2 s  .com*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    doc.appendChild(sig.getElement());

    {
        ObjectContainer obj = new ObjectContainer(doc);
        Element anElement = doc.createElementNS(null, "InsideObject");

        anElement.appendChild(doc.createTextNode("A text in a box"));
        obj.appendChild(anElement);

        String Id = "TheFirstObject";

        obj.setId(Id);
        sig.appendObject(obj);

        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#" + Id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    for (int i = 0; i < sig.getSignedInfo().getSignedContentLength(); i++) {
        System.out.println("--- Signed Content follows ---");
        System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
    }
}

From source file:org.apache.xml.security.samples.signature.HereSigner.java

/**
 * Method main//from ww w  .j a va  2  s.  c o m
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("hereSignature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    String BaseURI = signatureFile.toURL().toString();
    Constants.setSignatureSpecNSprefix("prof");
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    doc.appendChild(sig.getElement());
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    {
        ObjectContainer ob1 = new ObjectContainer(doc);
        ob1.setId("object-1");
        ob1.appendChild(doc.createTextNode("\nSigned Text\n"));
        Element c = doc.createElementNS(null, "element");
        c.setAttributeNS(null, "name", "val");
        ob1.appendChild(c);
        sig.appendObject(ob1);

        Transforms transforms = new Transforms(doc);
        XPathContainer xc = new XPathContainer(doc);
        xc.setXPathNamespaceContext("prof", Constants.SignatureSpecNS);

        //J-
        String xpath = "\n" + "count(" + "\n" + " ancestor-or-self::prof:Object " + "\n" + " | " + "\n"
                + " here()/ancestor::prof:Signature[1]/child::prof:Object[@Id='object-1']" + "\n"
                + ") <= count(" + "\n" + " ancestor-or-self::prof:Object" + "\n" + ") " + "\n";
        //J+

        xc.setXPath(xpath);
        HelperNodeList nl = new HelperNodeList();
        nl.appendChild(doc.createTextNode("\n"));
        nl.appendChild(xc.getElement());
        nl.appendChild(doc.createTextNode("\n"));

        transforms.addTransform(Transforms.TRANSFORM_XPATH, nl);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getSignedContentLength(); i++) {
        System.out.println(new String(s.getSignedContentItem(i)));
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);

    f.close();
    System.out.println("Wrote signature to " + BaseURI);
}

From source file:org.apache.xml.security.samples.signature.CreateSignature.java

/**
 * Method main/*w w  w  . j a  va  2s . c  o m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");

    //J-
    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //Build a sample document. It will look something like:
    //<!-- Comment before -->
    //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1">Some simple text
    //</apache:RootElement>
    //<!-- Comment after -->
    doc.appendChild(doc.createComment(" Comment before "));

    Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement");

    root.setAttributeNS(null, "attr1", "test1");
    root.setAttributeNS(null, "attr2", "test2");
    root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo");
    root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test");

    root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    //The BaseURI is the URI that's used to prepend to relative URIs
    String BaseURI = signatureFile.toURL().toString();
    //Create an XML Signature object from the document, BaseURI and
    //signature algorithm (in this case DSA)
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    //Append the signature element to the root element before signing because
    //this is going to be an enveloped signature.
    //This means the signature is going to be enveloped by the document.
    //Two other possible forms are enveloping where the document is inside the
    //signature and detached where they are seperate.
    //Note that they can be mixed in 1 signature with seperate references as
    //shown below.
    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    {
        //create the transforms object for the Document/Reference
        Transforms transforms = new Transforms(doc);

        //First we have to strip away the signature element (it's not part of the
        //signature calculations). The enveloped transform can be used for this.
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        //Part of the signature element needs to be canonicalized. It is a kind
        //of normalizing algorithm for XML. For more information please take a
        //look at the W3C XML Digital Signature webpage.
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        //Add the above Document/Reference
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        //Add in 2 external URIs. This is a detached Reference.
        //
        // When sign() is called, two network connections are made. -- well,
        // not really, as we use the OfflineResolver which acts as a proxy for
        // these two resouces ;-))
        //
        sig.addDocument("http://www.w3.org/TR/xml-stylesheet");
        sig.addDocument("http://www.nue.et-inf.uni-siegen.de/index.html");
    }

    {
        //Add in the KeyInfo for the certificate that we used the private key of
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);

    f.close();
    System.out.println("Wrote signature to " + BaseURI);
}

From source file:fr.jayasoft.ivy.Main.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();//w w  w.j ava  2  s .  com

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("?")) {
            usage(options);
            return;
        }

        if (line.hasOption("debug")) {
            Message.init(new DefaultMessageImpl(Message.MSG_DEBUG));
        } else if (line.hasOption("verbose")) {
            Message.init(new DefaultMessageImpl(Message.MSG_VERBOSE));
        } else if (line.hasOption("warn")) {
            Message.init(new DefaultMessageImpl(Message.MSG_WARN));
        } else if (line.hasOption("error")) {
            Message.init(new DefaultMessageImpl(Message.MSG_ERR));
        } else {
            Message.init(new DefaultMessageImpl(Message.MSG_INFO));
        }

        boolean validate = line.hasOption("novalidate") ? false : true;

        Ivy ivy = new Ivy();
        ivy.addAllVariables(System.getProperties());
        if (line.hasOption("m2compatible")) {
            ivy.setVariable("ivy.default.configuration.m2compatible", "true");
        }

        configureURLHandler(line.getOptionValue("realm", null), line.getOptionValue("host", null),
                line.getOptionValue("username", null), line.getOptionValue("passwd", null));

        String confPath = line.getOptionValue("conf", "");
        if ("".equals(confPath)) {
            ivy.configureDefault();
        } else {
            File conffile = new File(confPath);
            if (!conffile.exists()) {
                error(options, "ivy configuration file not found: " + conffile);
            } else if (conffile.isDirectory()) {
                error(options, "ivy configuration file is not a file: " + conffile);
            }
            ivy.configure(conffile);
        }

        File cache = new File(
                ivy.substitute(line.getOptionValue("cache", ivy.getDefaultCache().getAbsolutePath())));
        if (!cache.exists()) {
            cache.mkdirs();
        } else if (!cache.isDirectory()) {
            error(options, cache + " is not a directory");
        }

        String[] confs;
        if (line.hasOption("confs")) {
            confs = line.getOptionValues("confs");
        } else {
            confs = new String[] { "*" };
        }

        File ivyfile;
        if (line.hasOption("dependency")) {
            String[] dep = line.getOptionValues("dependency");
            if (dep.length != 3) {
                error(options,
                        "dependency should be expressed with exactly 3 arguments: organisation module revision");
            }
            ivyfile = File.createTempFile("ivy", ".xml");
            ivyfile.deleteOnExit();
            DefaultModuleDescriptor md = DefaultModuleDescriptor
                    .newDefaultInstance(ModuleRevisionId.newInstance(dep[0], dep[1] + "-caller", "working"));
            DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md,
                    ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true);
            for (int i = 0; i < confs.length; i++) {
                dd.addDependencyConfiguration("default", confs[i]);
            }
            md.addDependency(dd);
            XmlModuleDescriptorWriter.write(md, ivyfile);
            confs = new String[] { "default" };
        } else {
            ivyfile = new File(ivy.substitute(line.getOptionValue("ivy", "ivy.xml")));
            if (!ivyfile.exists()) {
                error(options, "ivy file not found: " + ivyfile);
            } else if (ivyfile.isDirectory()) {
                error(options, "ivy file is not a file: " + ivyfile);
            }
        }

        ResolveReport report = ivy.resolve(ivyfile.toURL(), null, confs, cache, null, validate, false, true,
                line.hasOption("useOrigin"), null);
        if (report.hasError()) {
            System.exit(1);
        }
        ModuleDescriptor md = report.getModuleDescriptor();

        if (confs.length == 1 && "*".equals(confs[0])) {
            confs = md.getConfigurationsNames();
        }
        if (line.hasOption("retrieve")) {
            String retrievePattern = ivy.substitute(line.getOptionValue("retrieve"));
            if (retrievePattern.indexOf("[") == -1) {
                retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]";
            }
            ivy.retrieve(md.getModuleRevisionId().getModuleId(), confs, cache, retrievePattern, null, null,
                    line.hasOption("sync"), line.hasOption("useOrigin"));
        }
        if (line.hasOption("cachepath")) {
            outputCachePath(ivy, cache, md, confs, line.getOptionValue("cachepath", "ivycachepath.txt"));
        }

        if (line.hasOption("revision")) {
            ivy.deliver(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                    cache, ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")),
                    ivy.substitute(line.getOptionValue("status", "release")), null,
                    new DefaultPublishingDRResolver(), validate);
            if (line.hasOption("publish")) {
                ivy.publish(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                        cache,
                        ivy.substitute(line.getOptionValue("publishpattern",
                                "distrib/[type]s/[artifact]-[revision].[ext]")),
                        line.getOptionValue("publish"),
                        ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")), validate);

            }
        }
        if (line.hasOption("main")) {
            invoke(ivy, cache, md, confs, line.getOptionValue("main"), line.getOptionValues("args"));
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        usage(options);
    }
}

From source file:org.apache.hadoop.hbase.util.RunTrigger.java

/**
 * @param args//  w  w w. ja v  a 2  s .c  om
 * @throws Throwable 
 */
public static void main(String[] args) throws Throwable {
    String usage = "RunTrigger jarFile [mainClass] args...";

    if (args.length < 1) {
        System.err.println(usage);
        System.exit(-1);
    }
    int firstArg = 0;
    String fileName = args[firstArg++];
    File file = new File(fileName);
    File tmpJarFile = new File("/tmp/hbase/triggerJar/trigger.jar");
    if (tmpJarFile.exists()) {
        tmpJarFile.delete();
    }
    FileUtils.copyFile(file, tmpJarFile);

    String mainClassName = null;
    JarFile jarFile;
    try {
        jarFile = new JarFile(fileName);
    } catch (IOException e) {
        throw new IOException("Error opening trigger jar: " + fileName).initCause(e);
    }

    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        mainClassName = manifest.getMainAttributes().getValue("Main-Class");
    }
    jarFile.close();
    System.out.println("Manifest From Jar: " + mainClassName);

    if (mainClassName == null) {
        if (args.length < 2) {
            System.err.println(usage);
            System.exit(-1);
        }
        mainClassName = args[firstArg++];
    }
    System.out.println("Manifest class from argument: " + mainClassName);

    mainClassName = mainClassName.replace("/", ".");

    //'hbase.tmp.dir'
    File tmpDir = new File("/tmp/hbase/trigger/");

    tmpDir.mkdirs();
    if (!tmpDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + tmpDir);
        System.exit(-1);
    }
    final File workDir = File.createTempFile("trigger-unjar", "", tmpDir);
    workDir.delete();
    workDir.mkdirs();
    if (!workDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + workDir);
        System.exit(-1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                FileUtil.fullyDelete(workDir);
            } catch (IOException e) {
            }
        }
    });

    unJar(file, workDir);

    ArrayList<URL> classPath = new ArrayList<URL>();
    classPath.add(new File(workDir + "/").toURL());
    classPath.add(file.toURL());
    classPath.add(new File(workDir, "classes/").toURL());
    File[] libs = new File(workDir, "lib").listFiles();
    if (libs != null) {
        for (int i = 0; i < libs.length; i++) {
            classPath.add(libs[i].toURL());
        }
    }

    ClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0]));
    Thread.currentThread().setContextClassLoader(loader);
    Class<?> mainClass = Class.forName(mainClassName, true, loader);
    Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() });
    String[] newArgs = Arrays.asList(args).subList(firstArg, args.length).toArray(new String[0]);
    try {
        main.invoke(null, new Object[] { newArgs });
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}

From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleSixteen.java

/**
 * Method main//  ww w . jav  a2  s.com
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("merlinsSixteenRecreatedNoRetrievalMethod.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    if (privateKey == null) {
        throw new RuntimeException("Private key is null");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //////////////////////////////////////////////////
    Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope");

    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://www.usps.gov/");
    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://www.usps.gov/foo");
    envelope.appendChild(doc.createTextNode("\n"));
    doc.appendChild(doc.createComment(" Preamble "));
    doc.appendChild(envelope);
    doc.appendChild(doc.createComment(" Postamble "));

    Element dearSir = doc.createElementNS("http://www.usps.gov/", "DearSir");

    dearSir.appendChild(doc.createTextNode("foo"));
    envelope.appendChild(dearSir);
    envelope.appendChild(doc.createTextNode("\n"));

    Element body = doc.createElementNS("http://www.usps.gov/", "Body");

    body.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(body);
    envelope.appendChild(doc.createTextNode("\n"));

    Element YoursSincerely = doc.createElementNS("http://www.usps.gov/", "YoursSincerely");
    YoursSincerely.appendChild(doc.createTextNode("\n"));

    envelope.appendChild(YoursSincerely);

    Element PostScript = doc.createElementNS("http://www.usps.gov/", "PostScript");

    PostScript.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(PostScript);

    Element Notaries = doc.createElementNS(null, "Notaries");

    Notaries.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    Notaries.setAttributeNS(null, "Id", "notaries");
    IdResolver.registerElementById(Notaries, "Id");

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Great, A. T.");
        Notaries.appendChild(Notary);
    }

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Hun, A. T.");
        Notaries.appendChild(Notary);
    }

    envelope.appendChild(Notaries);
    envelope.appendChild(doc.createComment(" Commentary "));

    //////////////////////////////////////////////////
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    YoursSincerely.appendChild(sig.getElement());
    sig.setId("signature");

    /*
     * Add the Objects
     */

    // object-1
    {
        ObjectContainer object1 = new ObjectContainer(doc);

        object1.setId("object-1");
        object1.setMimeType("text/plain");
        object1.appendChild(doc.createTextNode("I am the text."));
        sig.appendObject(object1);
    }

    // object-2
    {
        ObjectContainer object2 = new ObjectContainer(doc);

        object2.setId("object-2");
        object2.setMimeType("text/plain");
        object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64");
        object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="));
        sig.appendObject(object2);
    }

    // object-3
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-3");

        Element nonc = doc.createElementNS(null, "NonCommentandus");

        nonc.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
        nonc.appendChild(doc.createComment(" Commentandum "));
        object.appendChild(doc.createTextNode("\n        "));
        object.appendChild(nonc);
        object.appendChild(doc.createTextNode("\n      "));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.appendChild(createObject4(sig));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);
        SignatureProperties sps = new SignatureProperties(doc);

        sps.setId("signature-properties-1");

        SignatureProperty sp = new SignatureProperty(doc, "#signature");
        Element signedAdress = doc.createElementNS("urn:demo", "SignedAddress");

        signedAdress.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "urn:demo");

        Element IP = doc.createElementNS("urn:demo", "IP");

        IP.appendChild(doc.createTextNode("192.168.21.138"));
        signedAdress.appendChild(IP);
        sp.appendChild(signedAdress);
        sps.addSignatureProperty(sp);
        object.appendChild(sps.getElement());
        sig.appendObject(object);
    }

    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-4");

        X509Data x509data = new X509Data(doc);

        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        object.appendChild(x509data.getElement());
        sig.appendObject(object);
    }

    /*
     * Add References
     */
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());
    sig.addDocument("http://www.w3.org/TR/xml-stylesheet");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("http://xmldsig.pothole.com/xml-stylesheet.txt", transforms,
                Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPath("self::text()");
        transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns());
        sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }
    /*
    {
       Transforms transforms = new Transforms(doc);
       XPathContainer xpathC = new XPathContainer(doc);
            
       //J-
       xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
       xpathC.setXPath("\n"
        + " ancestor-or-self::ds:SignedInfo                    " + "\n"
        + "  and                                               " + "\n"
        + " count(ancestor-or-self::ds:Reference |             " + "\n"
        + "      here()/ancestor::ds:Reference[1]) >           " + "\n"
        + " count(ancestor-or-self::ds:Reference)              " + "\n"
        + "  or                                                " + "\n"
        + " count(ancestor-or-self::node() |                   " + "\n"
        + "      id('notaries')) =                             " + "\n"
        + " count(ancestor-or-self::node())                    " + "\n");
       //J+
       transforms.addTransform(Transforms.TRANSFORM_XPATH,
                         xpathC.getElementPlusReturns());
       sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                 "http://www.w3.org/2000/09/xmldsig#Object");
    }
    */

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("#object-2", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    sig.addDocument("#manifest-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Manifest");
    sig.addDocument("#signature-properties-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#SignatureProperties");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        sig.addDocument("#object-3", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#object-3", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#xpointer(id('object-3'))", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(id('object-3'))", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#manifest-reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-1",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-2",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-2", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    /*
     * Add KeyInfo and sign()
     */
    {
        Transforms retrievalTransforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        xpathC.setXPath("ancestor-or-self::ds:X509Data");
        retrievalTransforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElement());
        sig.getKeyInfo().add(new RetrievalMethod(doc, "#object-4", retrievalTransforms,
                "http://www.w3.org/2000/09/xmldsig#X509Data"));

        /*
        X509Data x509data = new X509Data(doc);
                
        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        sig.getKeyInfo().add(x509data);
        */

        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getLength(); i++) {
        Reference r = s.item(i);
        String fn = "merlin16_" + i + ".html";
        System.out.println("Wrote Reference " + i + " to file " + fn);
        JavaUtils.writeBytesToFilename(fn, r.getHTMLRepresentation().getBytes());
    }

    /*
    for (int i=0; i<s.getSignedContentLength(); i++) {
       if (s.item(i).getType().equals(Reference.MANIFEST_URI)) {
    System.out.println("################ Signed Manifest " + i + " ################");
       } else {
    System.out.println("################ Signed Resource " + i + " ################");
       }
       System.out.println(new String(s.getSignedContentItem(i)));
       System.out.println();
    }
    */
}

From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleTwentyThree.java

/**
 * Method main// ww  w. j av a2s  .  co m
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    Constants.setSignatureSpecNSprefix("ds");
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("merlinsTwentyThreeRecreatedNoRetrievalMethod.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    if (privateKey == null) {
        throw new RuntimeException("Private key is null");
    }

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    //////////////////////////////////////////////////
    Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope");

    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://www.usps.gov/");
    envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://www.usps.gov/foo");
    envelope.appendChild(doc.createTextNode("\n"));
    doc.appendChild(doc.createComment(" Preamble "));
    doc.appendChild(envelope);
    doc.appendChild(doc.createComment(" Postamble "));

    Element dearSir = doc.createElementNS("http://www.usps.gov/", "DearSir");

    dearSir.appendChild(doc.createTextNode("foo"));
    envelope.appendChild(dearSir);
    envelope.appendChild(doc.createTextNode("\n"));

    Element body = doc.createElementNS("http://www.usps.gov/", "Body");

    body.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(body);
    envelope.appendChild(doc.createTextNode("\n"));

    Element YoursSincerely = doc.createElementNS("http://www.usps.gov/", "YoursSincerely");
    YoursSincerely.appendChild(doc.createTextNode("\n"));

    envelope.appendChild(YoursSincerely);

    Element PostScript = doc.createElementNS("http://www.usps.gov/", "PostScript");

    PostScript.appendChild(doc.createTextNode("bar"));
    envelope.appendChild(PostScript);

    Element Notaries = doc.createElementNS(null, "Notaries");

    Notaries.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
    Notaries.setAttributeNS(null, "Id", "notaries");
    IdResolver.registerElementById(Notaries, "Id");

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Great, A. T.");
        Notaries.appendChild(Notary);
    }

    {
        Element Notary = doc.createElementNS(null, "Notary");

        Notary.setAttributeNS(null, "name", "Hun, A. T.");
        Notaries.appendChild(Notary);
    }

    envelope.appendChild(Notaries);
    envelope.appendChild(doc.createComment(" Commentary "));

    //////////////////////////////////////////////////
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    YoursSincerely.appendChild(sig.getElement());
    sig.setId("signature");

    /*
     * Add the Objects
     */

    // object-1
    {
        ObjectContainer object1 = new ObjectContainer(doc);

        object1.setId("object-1");
        object1.setMimeType("text/plain");
        object1.appendChild(doc.createTextNode("I am the text."));
        sig.appendObject(object1);
    }

    // object-2
    {
        ObjectContainer object2 = new ObjectContainer(doc);

        object2.setId("object-2");
        object2.setMimeType("text/plain");
        object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64");
        object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="));
        sig.appendObject(object2);
    }

    // object-3
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-3");

        Element nonc = doc.createElementNS(null, "NonCommentandus");

        nonc.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
        nonc.appendChild(doc.createComment(" Commentandum "));
        object.appendChild(doc.createTextNode("\n        "));
        object.appendChild(nonc);
        object.appendChild(doc.createTextNode("\n      "));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);

        object.appendChild(createObject4(sig));
        sig.appendObject(object);
    }

    // object number 4
    {
        ObjectContainer object = new ObjectContainer(doc);
        SignatureProperties sps = new SignatureProperties(doc);

        sps.setId("signature-properties-1");

        SignatureProperty sp = new SignatureProperty(doc, "#signature");
        Element signedAdress = doc.createElementNS("urn:demo", "SignedAddress");

        signedAdress.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "urn:demo");

        Element IP = doc.createElementNS("urn:demo", "IP");

        IP.appendChild(doc.createTextNode("192.168.21.138"));
        signedAdress.appendChild(IP);
        sp.appendChild(signedAdress);
        sps.addSignatureProperty(sp);
        object.appendChild(sps.getElement());
        sig.appendObject(object);
    }

    {
        ObjectContainer object = new ObjectContainer(doc);

        object.setId("object-4");

        X509Data x509data = new X509Data(doc);

        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        object.appendChild(x509data.getElement());
        sig.appendObject(object);
    }

    /*
     * Add References
     */
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());
    sig.addDocument("http://www.w3.org/TR/xml-stylesheet");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("http://xmldsig.pothole.com/xml-stylesheet.txt", transforms,
                Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPath("self::text()");
        transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns());
        sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }
    /*
    {
       Transforms transforms = new Transforms(doc);
       XPathContainer xpathC = new XPathContainer(doc);
            
       //J-
       xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
       xpathC.setXPath("\n"
        + " ancestor-or-self::ds:SignedInfo                    " + "\n"
        + "  and                                               " + "\n"
        + " count(ancestor-or-self::ds:Reference |             " + "\n"
        + "      here()/ancestor::ds:Reference[1]) >           " + "\n"
        + " count(ancestor-or-self::ds:Reference)              " + "\n"
        + "  or                                                " + "\n"
        + " count(ancestor-or-self::node() |                   " + "\n"
        + "      id('notaries')) =                             " + "\n"
        + " count(ancestor-or-self::node())                    " + "\n");
       //J+
       transforms.addTransform(Transforms.TRANSFORM_XPATH,
                         xpathC.getElementPlusReturns());
       sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                 "http://www.w3.org/2000/09/xmldsig#Object");
    }
    */

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
        sig.addDocument("#object-2", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    sig.addDocument("#manifest-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Manifest");
    sig.addDocument("#signature-properties-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#SignatureProperties");

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        sig.addDocument("#object-3", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#object-3", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#xpointer(id('object-3'))", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#xpointer(id('object-3'))", transforms, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Object");
    }

    {
        sig.addDocument("#manifest-reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-1",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-2",
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    {
        sig.addDocument("#reference-2", null, Constants.ALGO_ID_DIGEST_SHA1, null,
                "http://www.w3.org/2000/09/xmldsig#Reference");
    }

    /*
     * Add KeyInfo and sign()
     */
    {
        Transforms retrievalTransforms = new Transforms(doc);
        XPathContainer xpathC = new XPathContainer(doc);

        xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS);
        xpathC.setXPath("ancestor-or-self::ds:X509Data");
        retrievalTransforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElement());
        sig.getKeyInfo().add(new RetrievalMethod(doc, "#object-4", retrievalTransforms,
                "http://www.w3.org/2000/09/xmldsig#X509Data"));

        /*
        X509Data x509data = new X509Data(doc);
                
        x509data.add(new XMLX509SubjectName(doc, cert));
        x509data.add(new XMLX509IssuerSerial(doc, cert));
        x509data.add(new XMLX509Certificate(doc, cert));
        sig.getKeyInfo().add(x509data);
        */

        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getLength(); i++) {
        Reference r = s.item(i);
        String fn = "merlin16_" + i + ".html";
        System.out.println("Wrote Reference " + i + " to file " + fn);
        JavaUtils.writeBytesToFilename(fn, r.getHTMLRepresentation().getBytes());
    }

    /*
    for (int i=0; i<s.getSignedContentLength(); i++) {
       if (s.item(i).getType().equals(Reference.MANIFEST_URI)) {
    System.out.println("################ Signed Manifest " + i + " ################");
       } else {
    System.out.println("################ Signed Resource " + i + " ################");
       }
       System.out.println(new String(s.getSignedContentItem(i)));
       System.out.println();
    }
    */
}

From source file:org.lilyproject.runtime.classloading.ClassLoaderBuilder.java

private static ClassLoader create(List<ClasspathEntry> classpathEntries, ClassLoader parentClassLoader,
        ArtifactRepository repository) throws ArtifactNotFoundException, MalformedURLException {
    List<URL> classpath = new ArrayList<URL>();

    for (ClasspathEntry cpEntry : classpathEntries) {
        File resolvedFile = cpEntry.getArtifactRef().resolve(repository);
        classpath.add(resolvedFile.toURL());
    }/*from  www. j  av  a 2s  . c  om*/

    return new URLClassLoader(classpath.toArray(new URL[classpath.size()]), parentClassLoader);
}

From source file:com.ms.commons.test.classloader.util.AntxconfigUtil.java

@SuppressWarnings("deprecation")
public static void changeClassLoader() throws Exception {
    File tmp = new File(TEMP_DIR);
    URLClassLoader cl = new URLClassLoader(new URL[] { tmp.toURL() },
            Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(cl);
}

From source file:org.apache.xml.security.samples.signature.VerifyMerlinsExamplesFifteen.java

/**
 * Method verify//from   w  w  w.  j a va 2s . c  o m
 *
 * @param dbf
 * @param filename
 * @throws Exception
 */
public static void verifyHMAC(DocumentBuilderFactory dbf, String filename) throws Exception {

    File f = new File(filename);

    System.out.println("Try to verify " + f.toURL().toString());

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    if (VerifyMerlinsExamplesSixteen.schemaValidate) {
        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
        db.setEntityResolver(new org.xml.sax.EntityResolver() {

            public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
                    throws org.xml.sax.SAXException {

                if (systemId.endsWith("xmldsig-core-schema.xsd")) {
                    try {
                        return new org.xml.sax.InputSource(new FileInputStream(signatureSchemaFile));
                    } catch (FileNotFoundException ex) {
                        throw new org.xml.sax.SAXException(ex);
                    }
                } else {
                    return null;
                }
            }
        });
    }

    org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f));

    Element nscontext = SampleUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    XMLSignature signature = new XMLSignature(sigElement, f.toURL().toString());

    // signature.addResourceResolver(new OfflineResolver());

    byte keybytes[] = "secret".getBytes("ASCII");
    javax.crypto.SecretKey sk = signature.createSecretKey(keybytes);

    System.out.println("The XML signature in file " + f.toURL().toString() + " is "
            + (signature.checkSignatureValue(sk) ? "valid (good)" : "invalid !!!!! (bad)"));
}