List of usage examples for org.w3c.dom Document createElementNS
public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);/*from w w w . j a va 2s . c om*/ DocumentBuilder db = dbf.newDocumentBuilder(); // Create original document Document document = db.newDocument(); Element root = document.createElementNS("urn:FOO", "ns0:Root"); document.appendChild(root); Element request = document.createElementNS("urn:FOO", "ns0:Request"); root.appendChild(request); // Create new Request element. Element newRequest = document.createElementNS("urn:BAR", "ns1:Request"); // Replace Request element root.replaceChild(newRequest, request); // Output the new document TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); t.transform(source, result); }
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);//from w w w. j a v a 2s. c om DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElementNS(null, "person"); // Create Root Element Element item = doc.createElementNS(null, "name"); // Create element item.appendChild(doc.createTextNode("Jeff")); root.appendChild(item); // Attach element to Root element item = doc.createElementNS(null, "age"); // Create another Element item.appendChild(doc.createTextNode("28")); root.appendChild(item); // Attach Element to previous element down tree item = doc.createElementNS(null, "height"); item.appendChild(doc.createTextNode("1.80")); root.appendChild(item); // Attach another Element - grandaugther doc.appendChild(root); // Add Root to Document DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer // for the DOM LSOutput out = domImplLS.createLSOutput(); StringWriter stringOut = new StringWriter(); // Writer will be a String out.setCharacterStream(stringOut); ser.write(doc, out); // Serialize the DOM System.out.println("STRXML = " + stringOut.toString()); // DOM as a String }
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*w w w. j av a 2s. c o m*/ DocumentBuilder loader = factory.newDocumentBuilder(); Document document = loader.newDocument(); String docNS = "http://www.my-company.com"; Element order = document.createElementNS(docNS, "order"); document.appendChild(order); order.setAttribute("xmlns", docNS); }
From source file:DOMGenerate.java
public static void main(String[] argv) { try {/*w w w . j a v a 2 s.c o m*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElementNS(null, "person"); // Create Root Element Element item = doc.createElementNS(null, "name"); // Create element item.appendChild(doc.createTextNode("Jeff")); root.appendChild(item); // Attach element to Root element item = doc.createElementNS(null, "age"); // Create another Element item.appendChild(doc.createTextNode("28")); root.appendChild(item); // Attach Element to previous element down tree item = doc.createElementNS(null, "height"); item.appendChild(doc.createTextNode("1.80")); root.appendChild(item); // Attach another Element - grandaugther doc.appendChild(root); // Add Root to Document DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer // for the DOM LSOutput out = domImplLS.createLSOutput(); StringWriter stringOut = new StringWriter(); // Writer will be a String out.setCharacterStream(stringOut); ser.write(doc, out); // Serialize the DOM System.out.println("STRXML = " + stringOut.toString()); // Spit out the // DOM as a String } catch (Exception ex) { ex.printStackTrace(); } }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java
/** * Main (starting) method of the command line application. * * @param argv Array of command line arguments that are expected to be * filesystem paths to input XML documents with MathML to be unified. * @throws ParserConfigurationException If a XML DOM builder cannot be * created with the configuration requested. */// w w w.jav a2 s . c o m public static void main(String argv[]) throws ParserConfigurationException { final Options options = new Options(); options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes"); options.addOption("h", "help", false, "print help"); final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argv); } catch (ParseException ex) { printHelp(options); System.exit(1); } if (line != null) { if (line.hasOption('h')) { printHelp(options); System.exit(0); } operatorUnification = line.hasOption('p'); final List<String> arguments = Arrays.asList(line.getArgs()); if (arguments.size() > 0) { Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument(); Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM); outerDocument.appendChild(rootNode); for (String filepath : arguments) { try { Document doc = DOMBuilder.buildDocFromFilepath(filepath); MathMLUnificator.unifyMathML(doc, operatorUnification); if (arguments.size() == 1) { xmlStdoutSerializer(doc); } else { Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM); Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR); filenameAttr.setTextContent(String.valueOf(filepath)); ((Element) itemNode).setAttributeNodeNS(filenameAttr); itemNode.appendChild( rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true)); rootNode.appendChild(itemNode); } } catch (SAXException | IOException ex) { Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE, "Failed processing of file: " + filepath, ex); } } if (rootNode.getChildNodes().getLength() > 0) { xmlStdoutSerializer(rootNode.getOwnerDocument()); } } else { printHelp(options); System.exit(0); } } }
From source file:TestSign.java
/** * Method main/* w w w .j a va2s.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("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:com.cladonia.security.signature.SignatureGenerator.java
public static void main(String args[]) throws Exception { // use this if you want to configure logging, normally would put this in a static block, // but this is just for testing (see jre\lib\logging.properties) org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory .getLog(SignatureGenerator.class.getName()); //System.out.println("Using the logger: "+log.getClass().getName()); //log.debug("Debug is on"); //log.warn("Warning is on"); //log.error("Error is on"); log.info("**** Testing Signature Generator *****"); //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "data/keystore.jks"; String keystorePass = "xmlexchanger"; String privateKeyAlias = "exchanger"; String privateKeyPass = "xmlexchanger"; String certificateAlias = "exchanger"; // set the keystore and private key properties KeyBuilder.setParams(keystoreType, keystoreFile, keystorePass, privateKeyAlias, privateKeyPass, certificateAlias);// w w w. j ava2 s .c o m // get the private key for signing. PrivateKey privateKey = KeyBuilder.getPrivateKey(); // get the cert X509Certificate cert = KeyBuilder.getCertificate(); // ************* create a sample to be signed ****************** 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 document = db.newDocument(); //Build a sample document. It will look something like: //<!-- Comment before --> //<cladonia:Exchanger xmlns:cladonia="http://www.exchangerxml.com"> //</cladonia:Exchanger> document.appendChild(document.createComment(" Comment before ")); Element root = document.createElementNS("http://www.exchangerxml.com", "cladonia:Exchanger"); root.setAttributeNS(null, "attr1", "test1"); root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:foo", "http://www.exchangerxml.com/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cladonia", "http://www.exchangerxml.com"); document.appendChild(root); Element firstchild = document.createElementNS("http://www.exchangerxml.com", "cladonia:Editor"); firstchild.appendChild(document.createTextNode("simple text\n")); firstchild.setAttributeNS(null, "Id", "CladoniaId"); root.appendChild(firstchild); //******************** End of sample to be signed************************* // *************** Signature 1 // create SignatureGenerator using private key, cert and the dom (i.e an enveloped signature) SignatureGenerator gen = new SignatureGenerator(privateKey, cert, document); // set the c14n algorithm (Exclusive) gen.setC14nAlgorithm(SignatureGenerator.TRANSFORM_C14N_EXCL_WITH_COMMENTS); // set the xpath transform gen.setXpath("//cladonia:Editor"); // set the id gen.setId("CladoniaId"); // sign the document document = gen.sign(null); // output the enveloped signature FileOutputStream fos = new FileOutputStream("c:\\temp\\sigout.xml"); XMLUtils.outputDOMc14nWithComments(document, fos); fos.close(); System.out.println("Created Signature 1 - an enveloped signature"); // ************** Signature 2 // now sign the previous output as an example of a detached signature SignatureGenerator gen2 = new SignatureGenerator(privateKey, cert, "file:///c:/temp/sigout.xml"); // set the c14n algorithm gen2.setC14nAlgorithm(SignatureGenerator.TRANSFORM_C14N_WITH_COMMENTS); // sign the document Document document2 = gen2.sign(null); // output the detached signature FileOutputStream fos2 = new FileOutputStream("c:\\temp\\sigout2.xml"); XMLUtils.outputDOMc14nWithComments(document2, fos2); fos2.close(); System.out.println("Created Signature 2 - a detached signature"); System.out.println(""); }
From source file:edu.kit.dama.util.test.LocalAccessTest.java
public static void main(String[] args) throws Exception { IFileTree tree = DataOrganizationUtils.createTreeFromFile("1q2345", new AbstractFile(new File( "/Users/jejkal/NetBeansProjects/KITDM/trunk/Docker/KITDM/share/log/cd37731e22d7df46722fa41efe2c5511ee83d3ee")), true);// w w w . j a va2 s .co m IDataOrganizationNode generatedNode = Util.getNodeByName(tree.getRootNode(), Constants.STAGING_GENERATED_FOLDER_NAME); //DataOrganizationUtils.printTree(tree.getRootNode(), true); DataOrganizationUtils.printTree((ICollectionNode) generatedNode, true); if (generatedNode == null || !(generatedNode instanceof ICollectionNode) || ((ICollectionNode) generatedNode).getChildren().isEmpty()) { System.out.println( "Node for 'generated' content not found or is empty. Skip registering view 'generated'."); } else { System.out.println("OK!"); } if (true) { return; } // DigitalObject c = DigitalObject.factoryNewDigitalObject(); //System.out.println(c.getDigitalObjectIdentifier()); /* CustomDigitalObject c = new CustomDigitalObject(); c.setDigitalObjectId(new DigitalObjectId(UUID.randomUUID().toString())); c.setLabel("TEst"); c.setNote("ee123"); System.out.println("EDS"); mdm.save(c); System.out.println("ODN");*/ // mdm.close(); String accessKey = "admin"; String accessSecret = "dama14"; String restBaseUrl = "http://localhost:8080/KITDM"; SimpleRESTContext context = new SimpleRESTContext(accessKey, accessSecret); /* DigitalObject newDigitalObject= DigitalObject.factoryNewDigitalObject(); newDigitalObject.setLabel("Sample DigitalObject"); newDigitalObject.setNote("This is a sample"); newDigitalObject.setStartDate(new Date());*/ long s = System.currentTimeMillis(); BaseMetaDataRestClient client; client = new BaseMetaDataRestClient(restBaseUrl + "/rest/basemetadata/", context); long t = 0; for (int i = 0; i < 100; i++) { DigitalObjectWrapper o = client.getDigitalObjectById(57l); t += (System.currentTimeMillis() - s); s = System.currentTimeMillis(); } System.out.println("T " + (t / 100l)); /*DigitalObject ob = o.getEntities().get(0); System.out.println(ob.getDigitalObjectIdentifier()); System.out.println(ob.getDigitalObjectId().getStringRepresentation());*/ /*Study newStudy = Study.factoryNewStudy(); newStudy.setTopic("Sample Study"); newStudy.setNote("This is a sample"); newStudy.setStartDate(new Date()); Investigation newInvestigation= Investigation.factoryNewInvestigation(); newInvestigation.setTopic("Sample Investigation"); newInvestigation.setNote("This is a sample"); newInvestigation.setStartDate(new Date()); client = new BaseMetaDataRestClient(restBaseUrl + "/rest/basemetadata/", context); //Create a new study. The study will be assigned to the default group whose ID we've obtained above. StudyWrapper studyWrapper = client.addStudy(newStudy, Constants.USERS_GROUP_ID); //Assign returned study to 'newStudy' as the created entity now contains a valid studyId. newStudy = studyWrapper.getEntities().get(0); //Use the studyId to add a new investigation to the study we've just created. InvestigationWrapper investigationWrapper = client.addInvestigationToStudy(newStudy.getStudyId(), newInvestigation, Constants.USERS_GROUP_ID); //Assign returned investigation to 'newInvestigation' as the created entity now contains a valid investigationId. newInvestigation = investigationWrapper.getEntities().get(0); //Use the investigationId to add a new digital object to the investigation just created. DigitalObjectWrapper digitalObjectWrapper = client.addDigitalObjectToInvestigation(newInvestigation.getInvestigationId(), newDigitalObject, Constants.USERS_GROUP_ID); //Assign returned digitalObject to 'newDigitalObject' as the created entity now contains a valid objectId. newDigitalObject = digitalObjectWrapper.getEntities().get(0); System.out.println("OK"); */ /*StagingServiceRESTClient client = new StagingServiceRESTClient("http://localhost:8080/KITDM/rest/staging/", new SimpleRESTContext("admin", "dama14")); FileTreeImpl f = new FileTreeImpl(); f.setDigitalObjectId(new DigitalObjectId("f735e33e-8821-460e-9d86-90281e6f91e1")); f.setViewName("default"); CollectionNodeImpl col = new CollectionNodeImpl(); col.setName("myImage"); FileNodeImpl fi = new FileNodeImpl(new LFNImpl("file:/Users/jejkal/tmp/2016/5/16/admin/d83bdb349f073714cec972958ab5737e7fe28f27/data/images/StructureAdminMetadata.png")); fi.setNodeId(500l); col.addChild(fi); f.getRootNode().addChild(col); System.out.println(client.createDownload("f735e33e-8821-460e-9d86-90281e6f91e1", "273f477a-546c-41d7-9037-61723de4dd36", f, "USERS")); */ /*String token = new String(Base64.getDecoder().decode("YWRtaW46ZGFtYTE0")); int splitIndex = token.indexOf(":"); if (splitIndex < 1) { throw new UnauthorizedAccessAttemptException("Invalid basic authentication header."); } String user = token.substring(0, splitIndex); String secret = token.substring(splitIndex+1); System.out.println(user); System.out.println(secret);*/ /* System.out.println(DigestUtils.md5Hex("admin:kitdm:dama14")); String md5a1 = DigestUtils.md5Hex("admin:kitdm:dama14"); String md5a2 = DigestUtils.md5Hex("GET:/KITDM/rest/basemetadata/investigations?groupId=USERS"); Map<String, Object> custom = new HashMap<>(); custom.put("repository.context", "empty"); AdalapiProtocolConfiguration config = AdalapiProtocolConfiguration.factoryConfiguration(new URL("http://dreamatico.com/data_images/kitten/kitten-2.jpg"),SimpleHttp.class.getCanonicalName(), KITDMAuthenticator.class.getCanonicalName(), custom); String clientHash = "602ce28e72c44bf003556f4b0e5b678d"; String serverDigest = DigestUtils.md5Hex(md5a1 + ":12345:" + md5a2); System.out.println(md5a1); System.out.println(md5a2); System.out.println(serverDigest); System.out.println(clientHash); */ /* String tokenKey = CryptUtil.stringToSHA1("test12345"); System.out.println(tokenKey); IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext()); ServiceAccessToken accessToken = ServiceAccessUtil.getAccessToken(mdm, tokenKey, "simpleRestToken"); System.out.println(accessToken);*/ // AbstractFile fi = new AbstractFile(new URL("http://ipelsdf1.lsdf.kit.edu:8889/webdav/admin/1/data/screen.jpg")); //SimpleRESTContext context = new SimpleRESTContext("admin", "dama14"); /* UserGroupWrapper groupWrapper = client1.getAllGroups(0, Integer.MAX_VALUE); System.out.println("The following groups were found:"); for (UserGroup group : groupWrapper.getEntities()) { System.out.println(" Name: " + group.getGroupName()); UserDataWrapper members = client1.getUsersOfGroup(group.getId(), 0, Integer.MAX_VALUE); System.out.println(" The group has the following members:"); for (UserData user : members.getEntities()) { System.out.println(" - " + user.getFullname() + " (" + user.getDistinguishedName() + ")" + user.getUserId()); } } // client1.addGroup("uniqueId", "Another Custom Group", "A custom group created for testing purposes."); UserDataWrapper userWrapper = client1.getAllUsers(Constants.USERS_GROUP_ID, 0, Integer.MAX_VALUE); for (UserData user : userWrapper.getEntities()) { System.out.println(" - " + user.getFullname() + " (" + user.getDistinguishedName() + ")"); } //distinguished name or id int modified = client1.addUserToGroup(3l, "tester").getCount(); System.out.println(client1.removeUserFromGroup(3l, 421l).getCount()); */ /* UserDataWrapper newUser = client1.addUser(Constants.USERS_GROUP_ID, "Test", "User", "test@mail.org", newUserIdentifier); System.out.println(newUser.getEntities().get(0).getDistinguishedName()); //distinguished name or id int modified = client1.addUserToGroup(3l, newUserIdentifier).getCount(); */ /* UserGroupWrapper groupWrapper = client.getAllGroups(0, Integer.MAX_VALUE); for (UserGroup group : groupWrapper.getEntities()) { System.out.println("GName: " + group.getGroupName()); } UserDataWrapper userWrapper = client.getAllUsers("eCod", 0, Integer.MAX_VALUE); for (UserData user : userWrapper.getEntities()) { System.out.println("UName: " + user.getDistinguishedName()); }*/ // AbstractRandomDataProviderStrategy stra = new AbstractRandomDataProviderStrategy() { // @Override // public Long getLong(AttributeMetadata attributeMetadata) { // if (attributeMetadata.getAttributeName().toLowerCase().contains("id")) { // return 0l; // } // return super.getLong(attributeMetadata); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public Object getMemoizedObject(AttributeMetadata attributeMetadata) { // if (attributeMetadata != null && attributeMetadata.getAttributeName() != null) { // switch (attributeMetadata.getAttributeName()) { // case "validFrom": // return new Date(0); // case "startDate": // return new Date(0); // case "validUntil": // return new Date(System.currentTimeMillis()); // case "endDate": // return new Date(System.currentTimeMillis()); // case "uploadDate": // return new Date(System.currentTimeMillis()); // } // } // return super.getMemoizedObject(attributeMetadata); // } // // }; // stra.setDefaultNumberOfCollectionElements(1); // PodamFactory factory = new PodamFactoryImpl(stra); // // DigitalObject a2 = factory.manufacturePojo(DigitalObject.class); // // IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); // mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext()); // a2 = mdm.save(a2); // // System.out.println(a2); if (true) { return; } /*String content = org.apache.commons.io.FileUtils.readFileToString(new File("/Users/jejkal/Software/GenericRestClient-1.2/bin/data/default_view.json")); JSONObject viewObject = new JSONObject(content); IFileTree tree1 = Util.jsonViewToFileTree(viewObject, true, false); DataOrganizationUtils.printTree(tree1.getRootNode(), true);*/ /*AdalapiProtocolConfiguration config = AdalapiProtocolConfiguration.factoryConfiguration(new URL("http://localhost:8080"), "edu.kit.lsdf.adalapi.protocols.WebDav", "edu.kit.dama.staging.adalapi.authenticator.KITDMAuthenticator", null); IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext()); System.out.println("RESULT " + mdm.save(config)); DatabaseProtocolConfigurator config1 = new DatabaseProtocolConfigurator(); ProtocolSettings.getSingleton().setExternalProtocolConfigurator(config1); Configuration configuration = config1.getConfiguration(new URL("http://localhost:8080")); Iterator keys = configuration.getKeys(); while (keys.hasNext()) { String key = (String) keys.next(); System.out.println(key + " - " + configuration.getString(key)); }*/ //SardineImpl impl = new SardineImpl("webdav", "webdav"); //impl.enablePreemptiveAuthentication(new URL("http://127.0.0.1:8080/webdav/admin/1/data/index.html")); //impl.setCredentials("webdav", "webdav"); //System.out.println(impl.get("http://webdav@127.0.0.1:8080/webdav/admin/1/data/index.html")); //System.out.println(impl.exists("http://webdav@ipesuco1.ipe.kit.edu:10000/")); /*Configuration config = new DatabaseProtocolConfigurator().getConfiguration(new URL("http://localhost:8080/webdav/admin/1/data/index.html")); config.addProperty("username", "webdav"); config.addProperty("password", "webdav"); AbstractFile file = new AbstractFile(new URL("http://localhost:8080/webdav/admin/1/data/index.html")); System.out.println(file.exists()); /* Configuration config1 = new DatabaseProtocolConfigurator().getConfiguration(new URL("http://localhost:8080/webdav/admin/1/data/index.html")); config1.addProperty("username", "webdav1"); config1.addProperty("password", "webdav1"); */ /* AbstractFile file2 = new AbstractFile(new URL("http://localhost:8080/webdav/admin/1/data/index.html")); System.out.println(file2.exists());*/ // createDestination("1", new AuthorizationContext(new UserId("admin"), new GroupId("USERS"), Role.ADMINISTRATOR)); // System.out.println(file.exists()); /////////// // long investigationId = -1l; // int first = 0; // int results = 10; // List<DigitalObject> objects; // if (investigationId <= 0) { // //no investigationId provided...get all objects // mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple"); // objects = mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class, first, results); // } else { // //first, obtain investigation for id // mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "Investigation.simple"); // Investigation investigation = mdm.find(Investigation.class, investigationId); // if (investigation == null) { // LOGGER.error("Investigation for id {} not found.", investigationId); // throw new WebApplicationException(Response.Status.NOT_FOUND); // } // //try to get objects in investigation // mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple"); // objects = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.investigation.investigationId=" + investigationId, DigitalObject.class, first, results); // } //////// /* BaseMetaDataRestClient cl = new BaseMetaDataRestClient("http://ipesuco1.ipe.kit.edu:8080/KITDM/rest/basemetadata/", new SimpleRESTContext("admin", "dama14")); DigitalObjectWrapper w = cl.getAllDigitalObjects(63l, 0, 100, "eCod"); System.out.println("Time2: " + (System.currentTimeMillis() - s)); */ //DataOrganizationRestClient doClient = new DataOrganizationRestClient("http://localhost:8080/KITDM/rest/dataorganization/", new SimpleRESTContext("admin", "dama14")); /* DataOrganizer org = DataOrganizerFactory.getInstance().getDataOrganizer(); IFileTree tree1 = org.loadFileTree(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), "default"); IFileTree sub = org.loadSubTree(new NodeId(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), 400l,1), 0); DataOrganizationUtils.printTree(sub.getRootNode(), true);*/ /* FileTreeImpl newTree = new FileTreeImpl(); newTree.setDigitalObjectId(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c")); newTree.setViewName("custom"); CollectionNodeImpl images = new CollectionNodeImpl(); images.setNodeId(400l); CollectionNodeImpl documents = new CollectionNodeImpl(); documents.setName("documents"); FileNodeImpl fDocumentation = new FileNodeImpl(null); fDocumentation.setNodeId(200l); documents.addChild(fDocumentation); newTree.getRootNode().addChild(images); newTree.getRootNode().addChild(documents); doClient.postView("USERS", 31l, newTree, Boolean.TRUE, new SimpleRESTContext("admin", "dama14")); */ /* DataOrganizer org = DataOrganizerFactory.getInstance().getDataOrganizer(); IFileTree tree1 = org.loadFileTree(new DigitalObjectId("ef16c1e5-d9b3-44b5-ba77-b9877082d02c"), "custom"); DataOrganizationUtils.printTree(tree1.getRootNode(), true);*/ DataOrganizer dor = DataOrganizerFactory.getInstance().getDataOrganizer(); //dor.configure("http://localhost:7474", "neo4j", "test"); // edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl dor = new edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl(); // IFileTree tree = DataOrganizationUtils.createTreeFromFile("Large4", new AbstractFile(new File("/Users/jejkal/NetBeansProjects/KITDM/trunk")), true); //edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl dor = new edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl(); // System.out.println("Create tree"); // dor.createFileTree(tree); System.out.println("DONE"); s = System.currentTimeMillis(); System.out.println(dor.getViews(new DigitalObjectId("Large4"))); //dor.createFileTree(tree); System.out.println("R " + (System.currentTimeMillis() - s)); if (true) { return; } // IMetaDataManager mdm1 = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); // mdm1.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.simple"); // AuthorizationContext ctx1 = new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.ADMINISTRATOR); // mdm1.setAuthorizationContext(ctx1);*/ /* StringBuilder query = new StringBuilder(); IMetaDataManager mdm1 = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); mdm1.setAuthorizationContext(ctx1); String domain = SecurableEntityHelper.getSecurableResourceDomain(DigitalObject.class); String uniqueField = SecurableEntityHelper.getDomainUniqueFieldName(DigitalObject.class); query.append("SELECT o FROM FilterHelper f, "). append("DigitalObject").append(" o WHERE "); query.append("f.userId='").append(ctx1.getUserId().getStringRepresentation()); query.append("' AND "); query.append("f.groupId='").append(ctx1.getGroupId().getStringRepresentation()).append("' AND ") .append("f.domainId='").append(domain). append("' AND f.roleAllowed>=").append(Role.GUEST.ordinal()). append(" AND f.domainUniqueId=o.").append(uniqueField); long s1 = System.currentTimeMillis(); List<DigitalObject> result2 = mdm1.findResultList(query.toString(), DigitalObject.class, 0, 100); System.out.println("D: " + (System.currentTimeMillis() - s1));*/ /*for(int i=0;i<100;i++){ if(result1.get(i).getDigitalObjectId().equals(result2.get(i).getDigitalObjectId())){ System.out.println("ERROR "); System.out.println(result1.get(i)); System.out.println("====================="); System.out.println(result2.get(i)); System.out.println("==================="); System.out.println(i); } }*/ if (true) { return; } // IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); // AuthorizationContext ctx = new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.ADMINISTRATOR); // mdm.setAuthorizationContext(ctx); // long s = System.currentTimeMillis(); // //System.out.println(new DigitalObjectSecureQueryHelper().getReadableResources(mdm, 0, 100, ctx).size()); // System.out.println("Time: " + (System.currentTimeMillis() - s)); // s = System.currentTimeMillis(); // mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default"); // System.out.println(mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class, 0, 100).size()); // System.out.println("Time2: " + (System.currentTimeMillis() - s)); // if (true) { // return; // } // IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); // //mdm.setAuthorizationContext(new AuthorizationContext(new UserId("admin"), new GroupId("eCod"), Role.MANAGER)); // mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext()); // mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default"); // long s = System.currentTimeMillis(); // DigitalObject result = mdm.find(DigitalObject.class, 1000l); // System.out.println(result.getBaseId()); // System.out.println(result.getLabel()); // System.out.println(result.getInvestigation().getInvestigationId()); // System.out.println(result.getInvestigation().getTopic()); // /* System.out.println(result.getStudyId()); // System.out.println(result.getTopic());*/ // System.out.println("TIME: " + (System.currentTimeMillis() - s)); // // System.out.println(result.getInvestigations().size()); /* System.out.println(result.getBaseId()); System.out.println(result.getLabel()); System.out.println(result.getNote()); System.out.println("--------"); mdm.addProperty(MetaDataManagerJpa.JAVAX_PERSISTENCE_FETCHGRAPH, "DigitalObject.default"); result = mdm.save(result); System.out.println(result.getBaseId()); System.out.println(result.getLabel()); System.out.println(result.getNote()); System.out.println("--------"); result = mdm.find(DigitalObject.class).get(0); System.out.println(result.getBaseId()); System.out.println(result.getLabel()); System.out.println(result.getNote());*/ /* System.out.println("TOPIC " + result.get(0).getTopic()); System.out.println("NOT " + result.get(0).getNote()); System.out.println("INV " + result.get(0).getInvestigations()); System.out.println("DO " + ((Investigation) result.get(0).getInvestigations().toArray()[0]).getDataSets());*/ if (true) { return; } // long t = System.currentTimeMillis(); // // AbstractRandomDataProviderStrategy stra = new AbstractRandomDataProviderStrategy() { // }; // stra.setDefaultNumberOfCollectionElements(1); // PodamFactory factory = new PodamFactoryImpl(stra); // DigitalObject a = factory.manufacturePojo(DigitalObject.class); // DigitalObject a2 = factory.manufacturePojoWithFullData(DigitalObject.class); // // //for (int i = 0; i < 10; i++) { // // long s = System.currentTimeMillis(); // Marshaller marshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(DigitalObject.class).createMarshaller(); // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // marshaller.setProperty("eclipselink.media-type", "application/json"); // marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "default"); // marshaller.marshal(a, System.out); // marshaller.marshal(a2, System.out); // // t += System.currentTimeMillis() - s; // // } // System.out.println("D " + (System.currentTimeMillis() - t)); // if (true) { // return; // } Document docDigitalObject = null; String completeXml = null; String baseXML = DigitalObject2Xml.getXmlString(DigitalObject.factoryNewDigitalObject()); try { ByteArrayInputStream bin = new ByteArrayInputStream(baseXML.getBytes()); docDigitalObject = JaxenUtil.getW3CDocument(bin);//XMLTools.parseDOM(baseXML); } catch (Exception exc) { throw new MetaDataExtractionException("Failed to transform DigitalObject XML.", exc); } Element digitalObjectElement = docDigitalObject.getDocumentElement(); Document completeDocument = null; try { completeDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException ex) { throw new MetaDataExtractionException("Failed to generate target document.", ex); } Element rootElement = completeDocument.createElement("test"); Element root = completeDocument.createElementNS(BaseMetaDataHelper.DAMA_NAMESPACE_BASEMETADATA, BaseMetaDataHelper.DAMA_NAMESPACE_PREFIX); root.appendChild(completeDocument.importNode(digitalObjectElement, true)); Node csmdRoot = root.appendChild(completeDocument.createElementNS( BaseMetaDataHelper.DAMA_NAMESPACE_METADATA, BaseMetaDataHelper.CSMD_NAMESPACE_PREFIX)); csmdRoot.appendChild(completeDocument.importNode(rootElement, true)); completeDocument.appendChild(root); root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation", BaseMetaDataHelper.DAMA_NAMESPACE_METADATA + " " + BaseMetaDataHelper.DAMA_NAMESPACE_BASEMETADATA + "/MetaData.xsd"); // convert tweaked DOM back to XML string try { completeXml = getStringFromDocument(completeDocument);//XMLTools.getXML(completeDocument); } catch (Exception exc) { throw new MetaDataExtractionException("Internal XML conversion error.", exc); } System.out.println(completeXml); // IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); // IAuthorizationContext context = new AuthorizationContext(new UserId("admin"), new GroupId(Constants.USERS_GROUP_ID), Role.ADMINISTRATOR);//AuthorizationContext.factorySystemContext(); // mdm.setAuthorizationContext(context); // try { // //TransferClientProperties props = new TransferClientProperties(); // //props.setStagingAccessPointId("0000-0000-0000-0000"); // //IngestInformationServiceLocal.getSingleton().prepareIngest(new DigitalObjectId("c98408fc-36d0-4cc0-8197-340873d6698e"), props, context); // // //System.out.println(StagingService.getSingleton().finalizeIngest(new DigitalObjectId("c98408fc-36d0-4cc0-8197-340873d6698e"), context)); // System.out.println(MetadataIndexingHelper.getSingleton().performIndexing("KITDataManager", "dc", new GroupId("USERS"), 10, context)); // } finally { // mdm.close(); // } }
From source file:Main.java
public static void edit(Document doc) { Element root = doc.createElementNS(null, "person"); // Create Root Element Element item = doc.createElementNS(null, "name"); // Create element item.appendChild(doc.createTextNode("Jeff")); root.appendChild(item); // Attach element to Root element item = doc.createElementNS(null, "age"); // Create another Element item.appendChild(doc.createTextNode("28")); root.appendChild(item); // Attach Element to previous element down tree item = doc.createElementNS(null, "height"); item.appendChild(doc.createTextNode("1.80")); root.appendChild(item); // Attach another Element - grandaugther doc.appendChild(root); // Add Root to Document }
From source file:Main.java
public static Element addElement(Element parent, String childName, Document doc) { Element childElement = doc.createElementNS(DEFAULT_NAMESPACE, childName); parent.appendChild(childElement);//from w ww .ja v a 2s. c o m return childElement; }