List of usage examples for org.w3c.dom Document importNode
public Node importNode(Node importedNode, boolean deep) throws DOMException;
From source file:org.openengsb.openengsbplugin.tools.ToolsTest.java
@Test public void testInsertDomNode() throws Exception { Document thePom = Tools.parseXMLFromString( IOUtils.toString(ClassLoader.getSystemResourceAsStream("licenseCheck/pass/pom.xml"))); Document d = Tools.newDOM();/*from w ww.ja v a 2 s .co m*/ Node nodeB = d.createElementNS(POM_NS_URI, "b"); Node importedNode = thePom.importNode(nodeB, true); Tools.insertDomNode(thePom, importedNode, "/pom:project/pom:a", NS_CONTEXT); String serializedXml = Tools.serializeXML(thePom); File generatedFile = Tools.generateTmpFile(serializedXml, ".xml"); Document generatedPom = Tools.parseXMLFromString(FileUtils.readFileToString(generatedFile)); Node foundNode = Tools.evaluateXPath("/pom:project/pom:a/pom:b", generatedPom, NS_CONTEXT, XPathConstants.NODE, Node.class); assertNotNull(foundNode); assertTrue(generatedFile.delete()); }
From source file:org.openmrs.module.metadatasharing.converter.BaseConverter.java
protected Element newElement(Document doc, String name, Object object, ConverterContext context) throws SerializationException { String serializedObject = MetadataSharing.getInstance().getMetadataSerializer().serialize(object); Document tmpDoc;//w w w . j a v a2 s. c o m try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); tmpDoc = db.parse(new InputSource(new StringReader(serializedObject))); } catch (Exception e) { throw new SerializationException(e); } Element element = tmpDoc.getDocumentElement(); element = (Element) tmpDoc.renameNode(element, "", name); element = (Element) newReference(element, context); newChildReferences(element, context); Element importedElement = (Element) doc.importNode(element, true); return importedElement; }
From source file:org.openmrs.module.web.WebModuleUtil.java
/** * Performs the webapp specific startup needs for modules Normal startup is done in * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context * is not rerun. This will save a lot of time, but it also means that the calling method is * responsible for restarting the context if necessary (the calling method will also have to * call {@link #loadServlets(Module, ServletContext)} and * {@link #loadFilters(Module, ServletContext)}).<br> * <br>//from w w w. j av a 2 s.co m * If delayContextRefresh is true and this module should have caused a context refresh, a true * value is returned. Otherwise, false is returned * * @param mod Module to start * @param servletContext the current ServletContext * @param delayContextRefresh true/false whether or not to do the context refresh * @return boolean whether or not the spring context need to be refreshed */ public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) { if (log.isDebugEnabled()) { log.debug("trying to start module " + mod); } // only try and start this module if the api started it without a // problem. if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) { String realPath = getRealPath(servletContext); if (realPath == null) { realPath = System.getProperty("user.dir"); } File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator)); if (!webInf.exists()) { webInf.mkdir(); } copyModuleMessagesIntoWebapp(mod, realPath); log.debug("Done copying messages"); // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh // of the web application context boolean moduleNeedsContextRefresh = false; // copy the html files into the webapp (from /web/module/ in the module) // also looks for a spring context file. If found, schedules spring to be restarted JarFile jarFile = null; OutputStream outStream = null; InputStream inStream = null; try { File modFile = mod.getFile(); jarFile = new JarFile(modFile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); log.debug("Entry name: " + name); if (name.startsWith("web/module/")) { // trim out the starting path of "web/module/" String filepath = name.substring(11); StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF"); // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/... if (filepath.startsWith("tags/")) { filepath = filepath.substring(5); absPath.append("/tags/module/"); } // Otherwise, copy it into /WEB-INF/view/module/moduleId/... else { absPath.append("/view/module/"); } // if a module id has a . in it, we should treat that as a /, i.e. files in the module // ui.springmvc should go in folder names like .../ui/springmvc/... absPath.append(mod.getModuleIdAsPath() + "/" + filepath); if (log.isDebugEnabled()) { log.debug("Moving file from: " + name + " to " + absPath); } // get the output file File outFile = new File(absPath.toString().replace("/", File.separator)); if (entry.isDirectory()) { if (!outFile.exists()) { outFile.mkdirs(); } } else { // make the parent directories in case it doesn't exist File parentDir = outFile.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } //if (outFile.getName().endsWith(".jsp") == false) // outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION); // copy the contents over to the webapp for non directories outStream = new FileOutputStream(outFile, false); inStream = jarFile.getInputStream(entry); OpenmrsUtil.copyFile(inStream, outStream); } } else if (name.equals("moduleApplicationContext.xml") || name.equals("webModuleApplicationContext.xml")) { moduleNeedsContextRefresh = true; } else if (name.equals(mod.getModuleId() + "Context.xml")) { String msg = "DEPRECATED: '" + name + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. "; throw new ModuleException(msg, mod.getModuleId()); } } } catch (IOException io) { log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException io) { log.warn("Couldn't close jar file: " + jarFile.getName(), io); } } if (inStream != null) { try { inStream.close(); } catch (IOException io) { log.warn("Couldn't close InputStream: " + io); } } if (outStream != null) { try { outStream.close(); } catch (IOException io) { log.warn("Couldn't close OutputStream: " + io); } } } // find and add the dwr code to the dwr-modules.xml file (if defined) InputStream inputStream = null; try { Document config = mod.getConfig(); Element root = config.getDocumentElement(); if (root.getElementsByTagName("dwr").getLength() > 0) { // get the dwr-module.xml file that we're appending our code to File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator)); // testing if file exists if (!f.exists()) { // if it does not -> needs to be created createDwrModulesXml(realPath); } inputStream = new FileInputStream(f); Document dwrmodulexml = getDWRModuleXML(inputStream, realPath); Element outputRoot = dwrmodulexml.getDocumentElement(); // loop over all of the children of the "dwr" tag Node node = root.getElementsByTagName("dwr").item(0); Node current = node.getFirstChild(); while (current != null) { if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName()) || "init".equals(current.getNodeName())) { ((Element) current).setAttribute("moduleId", mod.getModuleId()); outputRoot.appendChild(dwrmodulexml.importNode(current, true)); } current = current.getNextSibling(); } moduleNeedsContextRefresh = true; // save the dwr-modules.xml file. OpenmrsUtil.saveDocument(dwrmodulexml, f); } } catch (FileNotFoundException e) { throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException io) { log.error("Error while closing input stream", io); } } } // mark to delete the entire module web directory on exit // this will usually only be used when an improper shutdown has occurred. String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath(); File outFile = new File(folderPath.replace("/", File.separator)); outFile.deleteOnExit(); // additional checks on module needing a context refresh if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null && mod.getAdvicePoints().size() > 0) { // AOP advice points are only loaded during the context refresh now. // if the context hasn't been marked to be refreshed yet, mark it // now if this module defines some advice moduleNeedsContextRefresh = true; } // refresh the spring web context to get the just-created xml // files into it (if we copied an xml file) if (moduleNeedsContextRefresh && delayContextRefresh == false) { if (log.isDebugEnabled()) { log.debug("Refreshing context for module" + mod); } try { refreshWAC(servletContext, false, mod); log.debug("Done Refreshing WAC"); } catch (Exception e) { String msg = "Unable to refresh the WebApplicationContext"; mod.setStartupErrorMessage(msg, e); if (log.isWarnEnabled()) { log.warn(msg + " for module: " + mod.getModuleId(), e); } try { stopModule(mod, servletContext, true); ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play } catch (Exception e2) { // exception expected with most modules here if (log.isWarnEnabled()) { log.warn("Error while stopping a module that had an error on refreshWAC", e2); } } // try starting the application context again refreshWAC(servletContext, false, mod); notifySuperUsersAboutModuleFailure(mod); } } if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) { // only loading the servlets/filters if spring is refreshed because one // might depend on files being available in spring // if the caller wanted to delay the refresh then they are responsible for // calling these two methods on the module // find and cache the module's servlets //(only if the module started successfully previously) log.debug("Loading servlets and filters for module: " + mod); loadServlets(mod, servletContext); loadFilters(mod, servletContext); } // return true if the module needs a context refresh and we didn't do it here return (moduleNeedsContextRefresh && delayContextRefresh == true); } // we aren't processing this module, so a context refresh is not necessary return false; }
From source file:org.openmrs.projectbuendia.webservices.rest.XformResource.java
/** * Converts a vanilla Xform into one that ODK Collect is happy to work with. * This requires://from w w w .j a v a 2 s . c om * <ul> * <li>Changing the namespace of the the root element to http://www.w3.org/1999/xhtml * <li>Wrapping the model element in an HTML head element, with a title child element * <li>Wrapping remaining elements in an HTML body element * </ul> */ static String convertToOdkCollect(String xml, String title) throws IOException, SAXException { // Change the namespace of the root element. I haven't figured out a way // to do // this within a document; removing the root element from the document // seems // to do odd things... so instead, we import it into a new document. Document oldDoc = XmlUtil.parse(xml); Document doc = XmlUtil.getDocumentBuilder().newDocument(); Element root = (Element) doc.importNode(oldDoc.getDocumentElement(), true); root = (Element) doc.renameNode(root, HTML_NAMESPACE, "h:form"); doc.appendChild(root); // Prepare the new wrapper elements Element head = doc.createElementNS(HTML_NAMESPACE, "h:head"); Element titleElement = XmlUtil.appendElementNS(head, HTML_NAMESPACE, "h:title"); titleElement.setTextContent(title); Element body = doc.createElementNS(HTML_NAMESPACE, "h:body"); // Find the model element to go in the head, and all its following // siblings to go in the body. // We do this before moving any elements, for the sake of sanity. Element model = getElementOrThrowNS(root, XFORMS_NAMESPACE, "model"); List<Node> nodesAfterModel = new ArrayList<>(); Node nextSibling = model.getNextSibling(); while (nextSibling != null) { nodesAfterModel.add(nextSibling); nextSibling = nextSibling.getNextSibling(); } // Now we're done with the preparation, we can move everything. head.appendChild(model); for (Node node : nodesAfterModel) { body.appendChild(node); } // Having removed the model and everything after it, we can now just // append the head and body to the document element... root.appendChild(head); root.appendChild(body); return XformsUtil.doc2String(doc); }
From source file:org.osaf.cosmo.dav.property.StandardDavProperty.java
/** * <p>/* w w w . ja v a2s . c o m*/ * If the property value is an <code>Element</code>, it is imported into * the provided <code>Document</code> and returned. * </p> * <p> * If the property value is an <code>XmlSerializable</code>, the element * returned by calling {@link XmlSerializable.toXml(Document)} on the * value is appended as a child of an element representing the property. * </p> * <p> * If the property value is otherwise not null, {@link Object.toString()} is * called upon it, and the result is set as text content of an element * representing the property. * </p> * <p> * In all cases, if the property has a language, it is used to set the * <code>xml:lang</code> attribute on the property element. * </p> */ public Element toXml(Document document) { Element e = null; if (value != null && value instanceof Element) e = (Element) document.importNode((Element) value, true); else { e = getName().toXml(document); Object v = getValue(); if (v != null) { if (v instanceof XmlSerializable) e.appendChild(((XmlSerializable) v).toXml(document)); else DomUtil.setText(e, v.toString()); } } if (lang != null) DomUtil.setAttribute(e, XML_LANG, NAMESPACE_XML, lang); return e; }
From source file:org.oscarehr.phr.service.PHRService.java
public void sendQueuedDocuments(PHRAuthentication auth, String providerNo) throws Exception { // package sharing // IndivoAPService apService = new IndivoAPService(this); // apService.packageAllAccessPolicies(auth); List<PHRAction> actions = phrActionDAO.getQueuedActions(providerNo); logger.debug("Processing " + actions.size() + " actions "); // TalkClient client = getTalkClient(); for (PHRAction action : actions) { boolean updated = false; Long resultId = null;/*from ww w . j ava 2 s . com*/ // handle messages differently logger.debug("ACTION classification " + action.getPhrClassification() + " action type " + action.getActionType() + ", phr_action.id=" + action.getId()); try { if (action.getPhrClassification().equalsIgnoreCase("MESSAGE") && (action.getActionType() == PHRAction.ACTION_ADD || action.getActionType() == PHRAction.ACTION_UPDATE)) { sendMessage(auth, action); updated = true; } else if (action.getPhrClassification().equalsIgnoreCase("RELATIONSHIP") && (action.getActionType() == PHRAction.ACTION_ADD || action.getActionType() == PHRAction.ACTION_UPDATE)) { sendRelationship(auth, action); updated = true; } else if (action.getActionType() == PHRAction.ACTION_ADD || action.getActionType() == PHRAction.ACTION_UPDATE) {// dealing with medication type document // if adding IndivoDocumentType doc = action.getIndivoDocument(); if (action.getPhrClassification().equals(MedicalDataType.BINARY_DOCUMENT.name())) { doc = PHRBinaryData.mountDocument(action.getOscarId(), doc); MedicalDataWs medicalDataWs = MyOscarServerWebServicesManager .getMedicalDataWs(auth.getMyOscarUserId(), auth.getMyOscarPassword()); logger.debug("sending medical data : " + action.getOscarId() + ", " + action.getDateSent() + ", " + action.getPhrClassification() + ", " + auth.getMyOscarUserId() + ", " + doc); GregorianCalendar dataTime = new GregorianCalendar(); EDoc edoc = EDocUtil.getDoc(action.getOscarId()); org.w3c.dom.Document xmlDocument = XmlUtils.newDocument("BinaryDocument"); XmlUtils.appendChildToRoot(xmlDocument, "Filename", edoc.getFileName()); XmlUtils.appendChildToRoot(xmlDocument, "FileDescription", edoc.getDescription()); XmlUtils.appendChildToRoot(xmlDocument, "MimeType", edoc.getContentType()); XmlUtils.appendChildToRoot(xmlDocument, "Data", edoc.getFileBytes()); String xmlString = XmlUtils.toString(xmlDocument, false); if (doc.getDocumentHeader().getCreationDateTime() != null) dataTime = doc.getDocumentHeader().getCreationDateTime().toGregorianCalendar(); MedicalDataTransfer3 medicalDataTransfer = new MedicalDataTransfer3(); medicalDataTransfer.setActive(true); medicalDataTransfer.setCompleted(true); medicalDataTransfer.setData(xmlString); medicalDataTransfer.setDateOfData(dataTime); medicalDataTransfer.setMedicalDataType(action.getPhrClassification()); medicalDataTransfer.setObserverOfDataPersonId(auth.getMyOscarUserId()); LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get(); medicalDataTransfer .setObserverOfDataPersonName(loggedInInfo.loggedInProvider.getFormattedName()); medicalDataTransfer.setOriginalSourceId( loggedInInfo.currentFacility.getName() + ":EDoc:" + edoc.getDocId()); medicalDataTransfer.setOwningPersonId(action.getReceiverMyOscarUserId()); resultId = medicalDataWs.addMedicalData3(medicalDataTransfer); } else if (action.getPhrClassification().equals("ANNOTATION")) { try { String referenceIndex = PHRIndivoAnnotation.getAnnotationReferenceIndex(doc);// temporarily stored PHRAction referencedDocumentAction = phrActionDAO.getActionById(referenceIndex); if (referencedDocumentAction == null) throw new Exception("Cannot find annotated document"); if (referencedDocumentAction.getPhrIndex() == null) continue; // referenced document must be sent first doc = PHRIndivoAnnotation.mountReferenceDocument( referencedDocumentAction.getPhrClassification(), referencedDocumentAction.getPhrIndex(), referencedDocumentAction.getIndivoDocument().getDocumentVersion().size() - 1, doc); action = PHRIndivoDocument.setDocContent(doc, action); phrActionDAO.save(action); } catch (Exception e) { logger.error("Could not send the annotation with ID: '" + action.getId() + "' to PHR; skipping it...", e); action.setStatus(PHRAction.STATUS_OTHER_ERROR); phrActionDAO.update(action); continue; // if there is an error sending annotation, screw it...move on } } else if (action.getPhrClassification().equals(MedicalDataType.MEDICATION.name())) { MedicalDataWs medicalDataWs = MyOscarServerWebServicesManager .getMedicalDataWs(auth.getMyOscarUserId(), auth.getMyOscarPassword()); GregorianCalendar dataTime = new GregorianCalendar(); Node medicationNode = doc.getDocumentVersion().get(0).getVersionBody().getAny(); org.w3c.dom.Document xmlDocument = XmlUtils.newDocument("Medication"); Node xmlDocumentRootNode = xmlDocument.getFirstChild(); NodeList nodeList = medicationNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); node = xmlDocument.importNode(node, true); xmlDocumentRootNode.appendChild(node); } String xmlString = XmlUtils.toString(xmlDocument, false); logger.debug("sending medical data : " + action.getOscarId() + ", " + action.getDateSent() + ", " + action.getPhrClassification() + ", " + auth.getMyOscarUserId() + ", " + xmlString); if (doc.getDocumentHeader().getCreationDateTime() != null) dataTime = doc.getDocumentHeader().getCreationDateTime().toGregorianCalendar(); MedicalDataTransfer3 medicalDataTransfer = new MedicalDataTransfer3(); medicalDataTransfer.setActive(true); medicalDataTransfer.setCompleted(true); medicalDataTransfer.setData(xmlString); medicalDataTransfer.setDateOfData(dataTime); medicalDataTransfer.setMedicalDataType(action.getPhrClassification()); medicalDataTransfer.setObserverOfDataPersonId(auth.getMyOscarUserId()); LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get(); medicalDataTransfer .setObserverOfDataPersonName(loggedInInfo.loggedInProvider.getFormattedName()); medicalDataTransfer.setOriginalSourceId( loggedInInfo.currentFacility.getName() + ":medication:" + action.getOscarId()); medicalDataTransfer.setOwningPersonId(action.getReceiverMyOscarUserId()); resultId = medicalDataWs.addMedicalData3(medicalDataTransfer); } // AddDocumentResultType result = client.addDocument(auth.getToken(), action.getReceiverPhr(), doc); String resultIndex = resultId.toString(); action.setPhrIndex(resultId.toString()); // updates indexes to handle the case where two operations on this file are queued phrActionDAO.updatePhrIndexes(action.getPhrClassification(), action.getOscarId(), action.getSenderOscar(), resultIndex); actions = PHRAction.updateIndexes(action.getPhrClassification(), action.getOscarId(), resultIndex, actions); updated = true; // if updating } else if (action.getPhrClassification().equalsIgnoreCase("MESSAGE") && action.getActionType() == PHRAction.ACTION_UPDATE) { logger.info( "excuse me but since when can you ever update a message that's been sent? no messaging system allows that."); // logger.debug("HERE MESSAGE UPDATE"); // org.indivo.xml.JAXBUtils jaxbUtils = new org.indivo.xml.JAXBUtils(); // // IndivoDocumentType document = action.getIndivoDocument(); // // JAXBContext messageContext = JAXBContext.newInstance("org.indivo.xml.phr.message"); // MessageType msg = (MessageType) org.indivo.xml.phr.DocumentUtils.getDocumentAnyObject(document, messageContext.createUnmarshaller()); // // ??? Should i use reflection to abstract the call to ObjectFactory??? how will in know what method to call? the one that will take MessageType as a param??? // logger.debug("IS READ " + msg.isRead()); // Element element = jaxbUtils.marshalToElement(new org.indivo.xml.phr.message.ObjectFactory().createMessage(msg), JAXBContext.newInstance("org.indivo.xml.phr.message")); // // DocumentVersionGenerator dvg = new DocumentVersionGenerator(); // DocumentVersionType newVersion = dvg.generateDefaultDocumentVersion(auth.getUserId(), auth.getName(), auth.getRole(), element); // logger.debug("BEFORE UPDATE DOCUMENT calling with token " + auth.getToken() + " id " + auth.getUserId() + " idx " + action.getPhrIndex() + " v " + newVersion); // UpdateDocumentResultType updateDocRes = client.updateDocument(auth.getToken(), auth.getUserId(), action.getPhrIndex(), newVersion); // if (updateDocRes == null) { // logger.debug("UPDATE DOC IS NULL"); // } else { // logger.debug("UPDATE DOC IS NOT NULL" + updateDocRes.toString()); // } // logger.debug("AFTER UPDATE DOCUMENT"); // updated = true; } else if (action.getActionType() == PHRAction.ACTION_UPDATE) { logger.info( "sorry but there's no such thing as update for relationship / medical documents / messages, you can create or delete them only."); // logger.debug("else 2"); // if (action.getPhrIndex() == null && !action.getPhrClassification().equals(PHRConstants.DOCTYPE_ACCESSPOLICIES())) throw new Exception("Error: PHR index not set"); // // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_ACCESSPOLICIES())) action = apService.packageAccessPolicy(auth, action); // IndivoDocumentType doc = action.getIndivoDocument(); // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_BINARYDATA())) doc = PHRBinaryData.mountDocument(action.getOscarId(), doc); // Element documentElement = DocumentUtils.getDocumentAnyElement(doc); // // Retrieve current file record from indivo // logger.debug("phr index " + action.getPhrIndex()); // // ReadDocumentResultType readResult = client.readDocument(auth.getToken(), action.getSenderPhr(), action.getPhrIndex()); // // IndivoDocumentType phrDoc = readResult.getIndivoDocument(); // // IndivoDocumentType phrDoc = null; // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_MESSAGE())) { // PHRDocument phrd = phrDocumentDAO.getDocumentByIndex(action.getPhrIndex()); // JAXBContext docContext = JAXBContext.newInstance(IndivoDocumentType.class.getPackage().getName()); // Unmarshaller unmarshaller = docContext.createUnmarshaller(); // // JAXBElement jaxment = (JAXBElement) unmarshaller.unmarshal(new StringReader(phrd.getDocContent())); // phrDoc = (IndivoDocumentType) jaxment.getValue(); // } else { // ReadDocumentResultType readResult = client.readDocument(auth.getToken(), action.getReceiverPhr(), action.getPhrIndex()); // phrDoc = readResult.getIndivoDocument(); // } // // DocumentVersionType version = phrDoc.getDocumentVersion().get(phrDoc.getDocumentVersion().size() - 1); // // // send new version // VersionBodyType body = version.getVersionBody(); // body.setAny(documentElement); // version.setVersionBody(body); // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_MESSAGE())) { // client.updateDocument(auth.getToken(), auth.getUserId(), action.getPhrIndex(), version); // } else { // client.updateDocument(auth.getToken(), action.getReceiverPhr(), action.getPhrIndex(), version); // } // updated = true; } else { logger.debug("NOTHING IS GETTING CALLED FOR THIS "); } } catch (ActionNotPerformedException anpe) { // assuming user does not have authorization for the action - in this case mark it as unauthorized and stop trying to send logger.debug("Setting Status Not Authorized"); action.setStatus(PHRAction.STATUS_NOT_AUTHORIZED); phrActionDAO.update(action); } catch (IndivoException ie) { // assuming connection problems - in this case log the user off to take load off the server logger.debug("IndivoException thrown"); throw new Exception(ie); } catch (Exception e) { SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); logger.error( "Exception Thrown that is not due to connection or Authorization...probably jaxb problem " + formatter.format(new Date()), e); updated = false; action.setStatus(PHRAction.STATUS_OTHER_ERROR); phrActionDAO.update(action); } if (updated) { action.setStatus(PHRAction.STATUS_SENT); phrActionDAO.update(action); } } }
From source file:org.rdswicthboard.utils.rdf.oai.App.java
public static void main(String[] args) { // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file"); options.addOption("o", PROPERTY_OUTPUT_FILE, true, "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")"); options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")"); options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")"); options.addOption("I", PROPERTY_INPUT_ENCODING, true, "input file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("O", PROPERTY_OUTPUT_ENCODING, true, "output file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding"); options.addOption("h", PROPERTY_HELP, false, "print this message"); try {/*from ww w. ja va 2 s. c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(PROPERTY_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]", options); System.exit(0); } // variables to store program properties CompositeConfiguration config = new CompositeConfiguration(); config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE); config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC); config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT); // check if arguments has input file properties if (line.hasOption(PROPERTY_CONFIG_FILE)) { // if it does, load the specified configuration file Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE)); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } else throw new Exception("Invalid configuration file: " + defaultConfig.toString()); } else { // if it not, try to load default configurationfile Path defaultConfig = Paths.get(PROPERTIES_FILE); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } } // check if arguments has input file if (line.hasOption(PROPERTY_INPUT_FILE)) config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE)); // check if arguments has output file if (line.hasOption(PROPERTY_OUTPUT_FILE)) config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE)); // check if arguments has set spec name if (line.hasOption(PROPERTY_SET_SPEC)) config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC)); // check if arguments has input encoding if (line.hasOption(PROPERTY_INPUT_ENCODING)) config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_OUTPUT_ENCODING)) config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_FORMAT_OUTPUT)) config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes"); // check if arguments has input file without a key if (line.getArgs().length > 0) { config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]); // check if arguments has output file without a key if (line.getArgs().length > 1) { config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]); // check if there is too many arguments if (line.getArgs().length > 2) throw new Exception("Too many arguments"); } } // The program has default output file, but input file must be presented if (!config.containsKey(PROPERTY_INPUT_FILE)) throw new Exception("Please specify input file"); // extract input file String inputFile = config.getString(PROPERTY_INPUT_FILE); // extract output file String outputFile = config.getString(PROPERTY_OUTPUT_FILE); // extract set spec String setSpecName = config.getString(PROPERTY_SET_SPEC); // extract encoding String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING); String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING); boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT); // test if source is an regular file and it is readable Path source = Paths.get(inputFile); if (!Files.isRegularFile(source)) throw new Exception("The input file: " + source.toString() + " is not an regular file"); if (!Files.isReadable(source)) throw new Exception("The input file: " + source.toString() + " is not readable"); Path target = Paths.get(outputFile); if (Files.exists(target)) { if (!Files.isRegularFile(target)) throw new Exception("The output file: " + target.toString() + " is not an regular file"); if (!Files.isWritable(target)) throw new Exception("The output file: " + target.toString() + " is not writable"); } // create and setup document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // create new document builder DocumentBuilder builder = factory.newDocumentBuilder(); // create oai document Document oai = builder.newDocument(); // set document version oai.setXmlVersion("1.0"); oai.setXmlStandalone(true); // create root OAI-PMH element Element oaiPmh = oai.createElement("OAI-PMH"); // set document namespaces oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/"); oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); oaiPmh.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"); // append root node oai.appendChild(oaiPmh); // create responseDate element Element responseDate = oai.createElement("responseDate"); // create simple date format DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT); // generate date String date = dateFormat.format(new Date()); // set current date and time responseDate.setTextContent(date); oaiPmh.appendChild(responseDate); Element listRecords = oai.createElement("ListRecords"); oaiPmh.appendChild(listRecords); // create xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); // create namespace context NamespaceContext namespaceContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix.equals("rdf")) return RDF_NAMESPACE; else if (prefix.equals("rns")) return RNF_NAMESPACE; else return null; } @Override public Iterator<?> getPrefixes(String val) { throw new IllegalAccessError("Not implemented!"); } @Override public String getPrefix(String uri) { throw new IllegalAccessError("Not implemented!"); } }; // create xpath object XPath xpath = xPathfactory.newXPath(); // set namespace contex xpath.setNamespaceContext(namespaceContext); // create XPath expressions XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about"); XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']"); // create RegEx patterns Pattern pattern = Pattern.compile( "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>"); // read file into a string String content = new String(Files.readAllBytes(source), inputEncoding); Matcher matcher = pattern.matcher(content); // process all records while (matcher.find()) { // convert string to input stream ByteArrayInputStream input = new ByteArrayInputStream( matcher.group().getBytes(StandardCharsets.UTF_8.toString())); // parse the xml document Document doc = builder.parse(input); // remove all spaces NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyNodes.getLength(); i++) { Node emptyTextNode = emptyNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } // obtain researcher id String id = (String) idExpr.evaluate(doc, XPathConstants.STRING); if (StringUtils.isEmpty(id)) throw new Exception("The record identifier can not be empty"); // create record element Element record = oai.createElement("record"); listRecords.appendChild(record); // create header element Element header = oai.createElement("header"); record.appendChild(header); // create identifier element Element identifier = oai.createElement("identifier"); identifier.setTextContent(id); header.appendChild(identifier); // create datestamp element Element datestamp = oai.createElement("datestamp"); datestamp.setTextContent(date); header.appendChild(datestamp); // create set spec element if it exists if (!StringUtils.isEmpty(setSpecName)) { Element setSpec = oai.createElement("setSpec"); setSpec.setTextContent(setSpecName); header.appendChild(setSpec); } // create metadata element Element metadata = oai.createElement("metadata"); record.appendChild(metadata); // import the record metadata.appendChild(oai.importNode(doc.getDocumentElement(), true)); } // create transformer factory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create transformer Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); if (formatOutput) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } else transformer.setOutputProperty(OutputKeys.INDENT, "no"); // create dom source DOMSource oaiSource = new DOMSource(oai); // create stream result StreamResult result = new StreamResult(target.toFile()); // stream xml to file transformer.transform(oaiSource, result); // optional stream xml to console for testing //StreamResult consoleResult = new StreamResult(System.out); //transformer.transform(oaiSource, consoleResult); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); System.exit(1); } }
From source file:org.regenstrief.util.XMLUtil.java
/** * copies a node and optionally all its children from one xml document to another provides a way * to attach xml as a string to xml as a dom object * /*from ww w.ja v a 2s. c o m*/ * @param doc Document xml document * @param childNode Node node that will be copied to xml document * @param deep boolean whether children of the Node should be changed * @return Node new node created from document * @throws DOMException if the Document cannot be changed */ public static Node changeNodeDocument(final Document doc, final Node childNode, final boolean deep) throws DOMException { return doc.importNode(childNode, deep); }
From source file:org.regenstrief.util.XMLUtil.java
/** * Imports a Node into a Document without creating new prefixes like Document.importNode * // w ww .j a v a 2 s. co m * @param doc the Document * @param toImport the Node to import * @return the imported Node **/ public final static Node importNode(final Document doc, final Node toImport) { Node imported; NodeList list; NamedNodeMap map; int i, size; if (toImport instanceof Element) { //imported = doc.createElement(((Element) toImport).getTagName()); // Ever want this? // This should copy toImport's prefix; I don't think that's what we want, but we don't have a namespace context for doc imported = doc.createElementNS(toImport.getNamespaceURI(), toImport.getNodeName()); for (map = toImport.getAttributes(), size = size(map), i = 0; i < size; i++) { final Node n = map.item(i); if (n != null) { ((Element) imported).setAttributeNode((Attr) importNode(doc, n)); } } } else if (toImport instanceof Attr) { final String uri = toImport.getNamespaceURI(); if (Util.isEmpty(uri)) { imported = doc.createAttribute( "xmlns".equals(getPrefix(toImport)) ? toImport.getNodeName() : getLocalName(toImport)); } else { imported = doc.createAttributeNS(uri, toImport.getNodeName()); } //imported.setNodeValue(toImport.getNodeValue()); // The value will be copied when we import children below } else { imported = doc.importNode(toImport, false); } for (list = toImport.getChildNodes(), size = size(list), i = 0; i < size; i++) { final Node n = list.item(i); if (n != null) { imported.appendChild(importNode(doc, n)); } } return imported; }
From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java
@Override public String archive(String siteId, Document doc, Stack<Element> stack, String archivePath, List<Reference> attachments) { String message = "archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR + SiteService.MAIN_CONTAINER + ".\n"; log.debug(message);/*from w w w .j av a 2 s . c om*/ // start with an element with our very own (service) name Element element = doc.createElement(AssignmentService.class.getName()); stack.peek().appendChild(element); stack.push(element); Collection<Assignment> assignments = getAssignmentsForContext(siteId); for (Assignment assignment : assignments) { String xml = assignmentRepository.toXML(assignment); try { InputSource in = new InputSource(new StringReader(xml)); Document assignmentDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); Element assignmentElement = assignmentDocument.getDocumentElement(); Node assignmentNode = doc.importNode(assignmentElement, true); element.appendChild(assignmentNode); } catch (Exception e) { log.warn("could not append assignment {} to archive, {}", assignment.getId(), e.getMessage()); } } stack.pop(); return message; }