List of usage examples for org.jdom2 Element getAttribute
public Attribute getAttribute(final String attname)
This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.
From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java
License:Open Source License
private static void changePropertyName(String oldPropertyName, String newPropertyName, Document document, String elementName) {/*from www . jav a2 s . c o m*/ for (Content content : document.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (elementName == null || elementName.equals(element.getName())) { if (element.getAttribute(oldPropertyName) != null) { element.getAttribute(oldPropertyName).setName(newPropertyName); } } } } }
From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java
License:Open Source License
private static String retrieveVirtualModelInstanceURI(Document document) { for (Content content : document.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getName().equals("AddressedVirtualModelModelSlot") || element.getName().equals("FMLRTModelSlot")) { if (element.getAttribute("name") != null && (element.getAttributeValue("name").equals("this") || element.getAttributeValue("name").equals("virtualModelInstance")) && element.getAttribute("virtualModelURI") != null) { return element.getAttributeValue("virtualModelURI"); }// w w w . java 2 s . co m } } } return null; }
From source file:org.openflexo.foundation.viewpoint.rm.ViewPointResourceImpl.java
License:Open Source License
private static void convertDiagramSpecification16ToVirtualModel17(File file, Document diagram, List<File> oldPaletteFiles, List<File> oldExampleDiagramFiles, ViewPointResource viewPointResource) { // Create the diagram specification and a virtual model with a diagram typed model slot referencing this diagram specification final String ADDRESSED_DIAGRAM_MODEL_SLOT = "AddressedDiagramModelSlot"; final String MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT = "ModelSlot_VirtualModelModelSlot"; final String MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT = "ModelSlot_TypedDiagramModelSlot"; try {//from ww w.j a va 2s . co m String diagramName = file.getName().replace(".xml", ""); // Create a folder that contains the diagram specification File diagramSpecificationFolder = new File( file.getParentFile() + "/" + diagramName + ".diagramspecification"); diagramSpecificationFolder.mkdir(); // Retrieve diagram drop schemes Iterator<Element> dropSchemeElements = diagram.getDescendants(new ElementFilter("DropScheme")); List<Element> dropSchemes = IteratorUtils.toList(dropSchemeElements); // Retrieve Diagram Model slots references Iterator<? extends Content> thisModelSlotsIterator = diagram.getDescendants( new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT))); List<Element> thisModelSlots = IteratorUtils.toList(thisModelSlotsIterator); // Retrieve the DiagramModelSlot (this), and transform it to a virtual model slot with a virtual model uri int thisID = 0; String newThisUri = viewPointResource.getURI() + "/" + diagramName; String diagramSpecificationURI = newThisUri + "/" + diagramName + ".diagramspecification"; Element typedDiagramModelSlot = null; boolean foundThis = false; for (Element thisMs : thisModelSlots) { // Retriev the ID and URI of this DiagramModelSlot if (thisMs.getAttribute("name") != null && thisMs.getAttributeValue("name").equals("this") && !foundThis) { // Store its ID and its URI thisID = thisMs.getAttribute("id").getIntValue(); if (thisMs.getAttributeValue("virtualModelURI") != null) { newThisUri = thisMs.getAttributeValue("virtualModelURI"); thisMs.removeAttribute("virtualModelURI"); thisMs.removeAttribute("name"); thisMs.getAttribute("id").setName("idref"); thisMs.setAttribute("idref", Integer.toString(thisID)); } // Replace by a Typed model slot typedDiagramModelSlot = new Element(MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT); typedDiagramModelSlot.setAttribute("metaModelURI", diagramSpecificationURI); typedDiagramModelSlot.setAttribute("name", "typedDiagramModelSlot"); typedDiagramModelSlot.setAttribute("id", Integer.toString(computeNewID(diagram))); foundThis = true; } } // Replace the Diagram Model Slot by a Virtual Model Model slot for (Element thisMs : thisModelSlots) { if (hasSameID(thisMs, thisID) && thisMs.getName().equals("DiagramModelSlot")) { thisMs.setName("VirtualModelModelSlot"); thisMs.getAttributes().add(new Attribute("virtualModelURI", newThisUri)); thisMs.getAttributes().add(new Attribute("name", "virtualModelInstance")); thisMs.getAttributes().add(new Attribute("id", Integer.toString(thisID))); thisMs.removeAttribute("idref"); } } // Update ids for all model slots Iterator<? extends Content> diagramModelSlotsIterator = diagram.getDescendants( new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT))); List<Element> thisDiagramModelSlots = IteratorUtils.toList(diagramModelSlotsIterator); for (Element diagramMs : thisDiagramModelSlots) { if (diagramMs.getAttribute("id") != null && typedDiagramModelSlot != null) { diagramMs.setAttribute("id", typedDiagramModelSlot.getAttributeValue("id")); } if (diagramMs.getAttribute("idref") != null) { // Change to TypedDiagramModelSlot if (diagramMs.getParentElement().getName().equals("AddShape") || diagramMs.getParentElement().getName().equals("AddConnector") || diagramMs.getParentElement().getName().equals("AddDiagram") || diagramMs.getParentElement().getName().equals("ContainedShapePatternRole") || diagramMs.getParentElement().getName().equals("ContainedConnectorPatternRole") || diagramMs.getParentElement().getName().equals("ContainedDiagramPatternRole")) { if (typedDiagramModelSlot.getAttributeValue("id") != null) { diagramMs.setAttribute("idref", typedDiagramModelSlot.getAttributeValue("id")); diagramMs.setName("TypedDiagramModelSlot"); } } else { diagramMs.setName(MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT); } } } for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getName().equals("AddShape") || element.getName().equals("AddConnector") || element.getName().equals("AddDiagram")) { if (element.getChild("TypedDiagramModelSlot") == null && element.getChild("AddressedDiagramModelSlot") == null) { Element adressedMsElement = new Element("TypedDiagramModelSlot"); Attribute newIdRefAttribute = new Attribute("idref", typedDiagramModelSlot.getAttributeValue("id")); adressedMsElement.getAttributes().add(newIdRefAttribute); element.addContent(adressedMsElement); } } } } // Update DiagramSpecification URI for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getAttribute("diagramSpecificationURI") != null) { String oldDiagramSpecificationUri = element.getAttributeValue("diagramSpecificationURI"); String diagramSpecificationName = oldDiagramSpecificationUri .substring(oldDiagramSpecificationUri.lastIndexOf("/")); String newDiagramSpecificationUri = oldDiagramSpecificationUri + diagramSpecificationName + ".diagramspecification"; element.getAttribute("diagramSpecificationURI").setValue(newDiagramSpecificationUri); } } } // Change all the "diagram" binding with "this", and "toplevel" with typedDiagramModelSlot.topLevel" in case of not // DropSchemeAction for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; for (Attribute attribute : element.getAttributes()) { if (attribute.getValue().startsWith("diagram")) { attribute.setValue(attribute.getValue().replace("diagram", "this")); } if (attribute.getValue().startsWith("topLevel")) { boolean diagramScheme = false; Element parentElement = element.getParentElement(); while (parentElement != null) { if (parentElement.getName().equals("DropScheme") || parentElement.getName().equals("LinkScheme")) { diagramScheme = true; } parentElement = parentElement.getParentElement(); } if (!diagramScheme) { attribute.setValue(attribute.getValue().replace("topLevel", "virtualModelInstance.typedDiagramModelSlot")); } } } } } // Create the diagram specificaion xml file File diagramSpecificationFile = new File(diagramSpecificationFolder, file.getName()); Document diagramSpecification = new Document(); Element rootElement = new Element("DiagramSpecification"); Attribute name = new Attribute("name", diagramName); Attribute diagramSpecificationURIAttribute = new Attribute("uri", diagramSpecificationURI); diagramSpecification.addContent(rootElement); rootElement.getAttributes().add(name); rootElement.getAttributes().add(diagramSpecificationURIAttribute); XMLUtils.saveXMLFile(diagramSpecification, diagramSpecificationFile); // Copy the palette files inside diagram specification repository ArrayList<File> newPaletteFiles = new ArrayList<File>(); for (File paletteFile : oldPaletteFiles) { File newFile = new File(diagramSpecificationFolder + "/" + paletteFile.getName()); FileUtils.rename(paletteFile, newFile); newPaletteFiles.add(newFile); Document palette = XMLUtils.readXMLFile(newFile); Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI); palette.getRootElement().getAttributes().add(diagramSpecUri); convertNames16ToNames17(palette); XMLUtils.saveXMLFile(palette, newFile); } // Copy the example diagram files inside diagram specification repository ArrayList<File> newExampleDiagramFiles = new ArrayList<File>(); for (File exampleDiagramFile : oldExampleDiagramFiles) { File newFile = new File(diagramSpecificationFolder + "/" + exampleDiagramFile.getName()); FileUtils.rename(exampleDiagramFile, newFile); newExampleDiagramFiles.add(newFile); Document exampleDiagram = XMLUtils.readXMLFile(newFile); exampleDiagram.getRootElement().setAttribute("uri", diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name")); Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI); exampleDiagram.getRootElement().getAttributes().add(diagramSpecUri); exampleDiagram.getRootElement().setAttribute("uri", diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name")); convertNames16ToNames17(exampleDiagram); XMLUtils.saveXMLFile(exampleDiagram, newFile); } // Update the diagram palette element bindings ArrayList<Element> paletteElementBindings = new ArrayList<Element>(); for (File paletteFile : newPaletteFiles) { Document palette = XMLUtils.readXMLFile(paletteFile); String paletteUri = diagramSpecificationURI + "/" + palette.getRootElement().getAttribute("name").getValue() + ".palette"; Iterator<? extends Content> paletteElements = palette .getDescendants(new ElementFilter("DiagramPaletteElement")); while (paletteElements.hasNext()) { Element paletteElement = (Element) paletteElements.next(); Element binding = createPaletteElementBinding(paletteElement, paletteUri, dropSchemes); if (binding != null) { paletteElementBindings.add(binding); } } XMLUtils.saveXMLFile(palette, paletteFile); } // Add the Palette Element Bindings to the TypedDiagramModelSlot if (!paletteElementBindings.isEmpty()) { typedDiagramModelSlot.addContent(paletteElementBindings); } if (typedDiagramModelSlot != null) { diagram.getRootElement().addContent(typedDiagramModelSlot); } // Update names convertNames16ToNames17(diagram); convertOldNameToNewNames("DiagramSpecification", "VirtualModel", diagram); // Save the files XMLUtils.saveXMLFile(diagram, file); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.openflexo.foundation.viewpoint.rm.ViewPointResourceImpl.java
License:Open Source License
private static void convertNames16ToNames17(Document document) { // Convert common properties addProperty("userID", "FLX", document, null); // Edition Patterns // Edition patterns name convertOldNameToNewNames("EditionPattern", "FlexoConcept", document); // Parent pattern role is no more an attribute but an element IteratorIterable<? extends Content> fcElementsIterator = document .getDescendants(new ElementFilter("FlexoConcept")); List<Element> fcElements = IteratorUtils.toList(fcElementsIterator); for (Element fc : fcElements) { if (fc.getAttribute("parentEditionPattern") != null) { Element parentEp = new Element("ParentFlexoConcept"); Attribute parentIdRef = new Attribute("idref", getFlexoConceptID(document, fc.getAttributeValue("parentEditionPattern"))); parentEp.getAttributes().add(parentIdRef); fc.removeAttribute("parentEditionPattern"); fc.addContent(parentEp);//from w ww. j a va2 s.co m } } // Pattern Roles // Pattern roles properties changePropertyName("editionPatternTypeURI", "flexoConceptTypeURI", document, "ContainedEditionPatternInstancePatternRole"); changePropertyName("editionPatternTypeURI", "flexoConceptTypeURI", document, "AddressedSelectEditionPatternInstance"); changePropertyName("editionPatternTypeURI", "flexoConceptTypeURI", document, "SelectEditionPatternInstance"); changePropertyName("editionPatternTypeURI", "flexoConceptTypeURI", document, "EditionPatternInstanceParameter"); changePropertyName("paletteElementID", "paletteElementId", document, "FMLDiagramPaletteElementBinding"); changePropertyName("editionPattern", "flexoConcept", document, "PaletteElement"); removeProperties("patternRole", document); removeProperty("className", document, "DrawingGraphicalRepresentation"); removeProperty("className", document, "ShapeGraphicalRepresentation"); removeProperty("className", document, "ConnectorGraphicalRepresentation"); // Pattern roles name convertOldNameToNewNames("ContainedEditionPatternInstancePatternRole", "FlexoConceptInstanceRole", document); convertOldNameToNewNames("EditionPatternInstancePatternRole", "FlexoConceptInstanceRole", document); convertOldNameToNewNames("ContainedShapePatternRole", "ShapeRole", document); convertOldNameToNewNames("ShapePatternRole", "ShapeRole", document); convertOldNameToNewNames("ContextShapePatternRole", "ShapeRole", document); convertOldNameToNewNames("ParentShapePatternRole", "ParentShapeRole", document); convertOldNameToNewNames("ContainedEMFObjectIndividualPatternRole", "EMFObjectIndividualRole", document); convertOldNameToNewNames("EMFObjectIndividualPatternRole", "EMFObjectIndividualRole", document); convertOldNameToNewNames("ContainedConnectorPatternRole", "ConnectorRole", document); convertOldNameToNewNames("ConnectorPatternRole", "ConnectorRole", document); convertOldNameToNewNames("ContainedOWLIndividualPatternRole", "OWLIndividualRole", document); convertOldNameToNewNames("OWLIndividualPatternRole", "OWLIndividualRole", document); convertOldNameToNewNames("ContainedObjectPropertyStatementPatternRole", "ObjectPropertyStatementRole", document); convertOldNameToNewNames("ObjectPropertyStatementPatternRole", "ObjectPropertyStatementRole", document); convertOldNameToNewNames("ContainedDataPropertyStatementPatternRole", "DataPropertyStatementRole", document); convertOldNameToNewNames("DataPropertyStatementPatternRole", "DataPropertyStatementRole", document); convertOldNameToNewNames("ContainedExcelCellPatternRole", "ExcelCellRole", document); convertOldNameToNewNames("ExcelCellPatternRole", "ExcelCellRole", document); convertOldNameToNewNames("ContainedExcelSheetPatternRole", "ExcelSheetRole", document); convertOldNameToNewNames("ExcelSheetPatternRole", "ExcelSheetRole", document); convertOldNameToNewNames("ContainedExcelRowPatternRole", "ExcelRowRole", document); convertOldNameToNewNames("ExcelRowPatternRole", "ExcelRowRole", document); convertOldNameToNewNames("ContainedDiagramPatternRole", "DiagramRole", document); convertOldNameToNewNames("DiagramPatternRole", "DiagramRole", document); convertOldNameToNewNames("ContainedXMLIndividualPatternRole", "XMLIndividualRole", document); convertOldNameToNewNames("XMLIndividualPatternRole", "XMLIndividualRole", document); convertOldNameToNewNames("ContainedXSIndividualPatternRole", "XSIndividualRole", document); convertOldNameToNewNames("XSIndividualPatternRole", "XSIndividualRole", document); convertOldNameToNewNames("ContainedXSClassPatternRole", "XSClassRole", document); convertOldNameToNewNames("XSClassPatternRole", "XSClassRole", document); // Actions convertOldNameToNewNames("EditionPatternInstanceParameter", "FlexoConceptInstanceParameter", document); convertOldNameToNewNames("MatchEditionPatternInstance", "MatchFlexoConceptInstance", document); convertOldNameToNewNames("CreateEditionPatternInstanceParameter", "CreateFlexoConceptInstanceParameter", document); // Retrieve Fetch Actions IteratorIterable<? extends Content> fetchElementsIterator = document .getDescendants(new ElementFilter("FetchRequestIterationAction")); List<Element> fetchElements = IteratorUtils.toList(fetchElementsIterator); for (Element fetchElement : fetchElements) { for (Element child : fetchElement.getChildren()) { if (child.getName().equals("AddressedSelectEditionPatternInstance")) { child.setName("FetchRequest_SelectFlexoConceptInstance"); } if (child.getName().equals("AddressedSelectEMFObjectIndividual")) { child.setName("FetchRequest_SelectEMFObjectIndividual"); } if (child.getName().equals("AddressedSelectIndividual")) { child.setName("FetchRequest_SelectIndividual"); } if (child.getName().equals("AddressedSelectExcelCell")) { child.setName("FetchRequest_SelectExcelCell"); } if (child.getName().equals("AddressedSelectExcelRow")) { child.setName("FetchRequest_SelectExcelRow"); } if (child.getName().equals("AddressedSelectExcelSheet")) { child.setName("FetchRequest_SelectExcelSheet"); } if (child.getName().equals("AddressedSelectEditionPatternInstance")) { child.setName("FetchRequest_SelectFlexoConceptInstance"); } } } // Built-in actions convertOldNameToNewNames("DeclarePatternRole", "DeclareFlexoRole", document); convertOldNameToNewNames("AddEditionPatternInstance", "AddFlexoConceptInstance", document); convertOldNameToNewNames("AddEditionPatternInstanceParameter", "AddFlexoConceptInstanceParameter", document); convertOldNameToNewNames("AddressedSelectEditionPatternInstance", "SelectFlexoConceptInstance", document); convertOldNameToNewNames("AddressedSelectFlexoConceptInstance", "SelectFlexoConceptInstance", document); convertOldNameToNewNames("SelectEditionPatternInstance", "SelectFlexoConceptInstance", document); // Model Slots for (Content content : document.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if ((element.getParentElement() != null) && (element.getParentElement().getName().equals("DiagramSpecification") || element.getParentElement().getName().equals("VirtualModel"))) { if (element.getName().equals("EMFModelSlot")) { element.setName("ModelSlot_EMFModelSlot"); } else if (element.getName().equals("XMLModelSlot")) { element.setName("ModelSlot_XMLModelSlot"); } else if (element.getName().equals("XSDModelSlot")) { element.setName("ModelSlot_XSDModelSlot"); } else if (element.getName().equals("BasicExcelModelSlot")) { element.setName("ModelSlot_BasicExcelModelSlot"); } else if (element.getName().equals("SemanticsExcelModelSlot")) { element.setName("ModelSlot_SemanticsExcelModelSlot"); } else if (element.getName().equals("BasicPowerpointModelSlot")) { element.setName("ModelSlot_SemanticsPowerpointModelSlot"); } else if (element.getName().equals("OWLModelSlot")) { element.setName("ModelSlot_OWLModelSlot"); } else if (element.getName().equals("VirtualModelModelSlot")) { element.setName("ModelSlot_VirtualModelModelSlot"); } } else { if (element.getName().equals("AddressedEMFModelSlot")) { element.setName("EMFModelSlot"); } else if (element.getName().equals("AddressedXMLModelSlot")) { element.setName("XMLModelSlot"); } else if (element.getName().equals("AddressedXSDModelSlot")) { element.setName("XSDModelSlot"); } else if (element.getName().equals("AddressedBasicExcelModelSlot")) { element.setName("BasicExcelModelSlot"); } else if (element.getName().equals("AddressedSemanticsExcelModelSlot")) { element.setName("SemanticsExcelModelSlot"); } else if (element.getName().equals("AddressedBasicPowerpointModelSlot")) { element.setName("BasicPowerpointModelSlot"); } else if (element.getName().equals("AddressedSemanticsPowerpointModelSlot")) { element.setName("SemanticsPowerpointModelSlot"); } else if (element.getName().equals("AddressedOWLModelSlot")) { element.setName("OWLModelSlot"); } else if (element.getName().equals("AddressedDiagramModelSlot")) { element.setName("TypedDiagramModelSlot"); } else if (element.getName().equals("AddressedVirtualModelModelSlot")) { element.setName("VirtualModelModelSlot"); } } } } // Palettes/ExampleDiagrams // Retrieve Connector GRs IteratorIterable<? extends Content> connectorGRElementsIterator = document .getDescendants(new ElementFilter("ConnectorGraphicalRepresentation")); List<Element> connectorGRElements = IteratorUtils.toList(connectorGRElementsIterator); for (Element connectorGRElement : connectorGRElements) { Element grSpec = null; if (connectorGRElement.getChild("RectPolylinConnector") != null) { grSpec = connectorGRElement.getChild("RectPolylinConnector"); } else if (connectorGRElement.getChild("LineConnector") != null) { grSpec = connectorGRElement.getChild("LineConnector"); } else if (connectorGRElement.getChild("CurvedPolylinConnector") != null) { grSpec = connectorGRElement.getChild("CurvedPolylinConnector"); } else if (connectorGRElement.getChild("ArcConnector") != null) { grSpec = connectorGRElement.getChild("ArcConnector"); } if (connectorGRElement.getAttribute("startSymbol") != null) { Attribute startSymbol = new Attribute("startSymbol", connectorGRElement.getAttributeValue("startSymbol")); grSpec.getAttributes().add(startSymbol); connectorGRElement.removeAttribute("startSymbol"); } if (connectorGRElement.getAttribute("endSymbol") != null) { Attribute endSymbol = new Attribute("endSymbol", connectorGRElement.getAttributeValue("endSymbol")); grSpec.getAttributes().add(endSymbol); connectorGRElement.removeAttribute("endSymbol"); } if (connectorGRElement.getAttribute("middleSymbol") != null) { Attribute middleSymbol = new Attribute("middleSymbol", connectorGRElement.getAttributeValue("middleSymbol")); grSpec.getAttributes().add(middleSymbol); connectorGRElement.removeAttribute("middleSymbol"); } if (connectorGRElement.getAttribute("startSymbolSize") != null) { Attribute startSymbolSize = new Attribute("startSymbolSize", connectorGRElement.getAttributeValue("startSymbolSize")); grSpec.getAttributes().add(startSymbolSize); connectorGRElement.removeAttribute("startSymbolSize"); } if (connectorGRElement.getAttribute("endSymbolSize") != null) { Attribute endSymbolSize = new Attribute("endSymbolSize", connectorGRElement.getAttributeValue("endSymbolSize")); grSpec.getAttributes().add(endSymbolSize); connectorGRElement.removeAttribute("endSymbolSize"); } if (connectorGRElement.getAttribute("middleSymbolSize") != null) { Attribute middleSymbolSize = new Attribute("middleSymbolSize", connectorGRElement.getAttributeValue("middleSymbolSize")); grSpec.getAttributes().add(middleSymbolSize); connectorGRElement.removeAttribute("middleSymbolSize"); } if (connectorGRElement.getAttribute("relativeMiddleSymbolLocation") != null) { Attribute relativeMiddleSymbolLocation = new Attribute("relativeMiddleSymbolLocation", connectorGRElement.getAttributeValue("relativeMiddleSymbolLocation")); grSpec.getAttributes().add(relativeMiddleSymbolLocation); connectorGRElement.removeAttribute("relativeMiddleSymbolLocation"); } } convertOldNameToNewNames("Palette", "DiagramPalette", document); convertOldNameToNewNames("PaletteElement", "DiagramPaletteElement", document); convertOldNameToNewNames("Shema", "Diagram", document); convertOldNameToNewNames("ContainedShape", "Shape", document); convertOldNameToNewNames("ContainedConnector", "Connector", document); convertOldNameToNewNames("FromShape", "StartShape", document); convertOldNameToNewNames("ToShape", "EndShape", document); convertOldNameToNewNames("Border", "ShapeBorder", document); convertOldNameToNewNames("LineConnector", "LineConnectorSpecification", document); convertOldNameToNewNames("CurvedPolylinConnector", "CurvedPolylinConnectorSpecification", document); convertOldNameToNewNames("RectPolylinConnector", "RectPolylinConnectorSpecification", document); removeNamedElements(document, "PrimaryConceptOWLIndividualPatternRole"); removeNamedElements(document, "StartShapeGraphicalRepresentation"); removeNamedElements(document, "EndShapeGraphicalRepresentation"); removeNamedElements(document, "ArtifactFromShapeGraphicalRepresentation"); removeNamedElements(document, "ArtifactToShapeGraphicalRepresentation"); removeNamedElements(document, "PrimaryRepresentationConnectorPatternRole"); removeNamedElements(document, "PrimaryRepresentationShapePatternRole"); removeNamedElements(document, "PrimaryConceptObjectPropertyStatementPatternRole"); removeNamedElements(document, "ToShapePatternRole"); removeNamedElements(document, "StartShapeGraphicalRepresentation"); removeNamedElements(document, "EndShapeGraphicalRepresentation"); // Change all "this" for (Content content : document.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; for (Attribute attribute : element.getAttributes()) { if (attribute.getValue().startsWith("this")) { if (element.getName().equals("ModelSlot_VirtualModelModelSlot")) { attribute.setValue(attribute.getValue().replace("this", "virtualModelInstance")); } if (element.getName().equals("VirtualModelModelSlot")) { attribute.setValue(attribute.getValue().replace("this", "virtualModelInstance")); } if (attribute.getName().equals("virtualModelInstance")) { attribute.setValue(attribute.getValue().replace("this", "virtualModelInstance")); } else { attribute.setValue(attribute.getValue().replace("this", "flexoBehaviourInstance")); } } } } } }
From source file:org.openflexo.foundation.viewpoint.rm.ViewPointResourceImpl.java
License:Open Source License
private static String retrieveVirtualModelInstanceURI(Document document) { for (Content content : document.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getName().equals("AddressedVirtualModelModelSlot") || element.getName().equals("VirtualModelModelSlot")) { if (element.getAttribute("name") != null && (element.getAttributeValue("name").equals("this") || element.getAttributeValue("name").equals("virtualModelInstance")) && element.getAttribute("virtualModelURI") != null) { return element.getAttributeValue("virtualModelURI"); }//w w w .j a v a 2 s.c om } } } return null; }
From source file:org.openthinclient.jnlp.servlet.JnlpFileHandler.java
License:Open Source License
public synchronized DownloadResponse getJnlpFileEx(JnlpResource jnlpres, DownloadRequest dreq) throws IOException { String path = jnlpres.getPath(); URL resource = jnlpres.getResource(); long lastModified = jnlpres.getLastModified(); _log.addDebug("lastModified: " + lastModified + " " + new Date(lastModified)); if (lastModified == 0) { _log.addWarning("servlet.log.warning.nolastmodified", path); }/*from w ww . j a va2 s. c o m*/ // fix for 4474854: use the request URL as key to look up jnlp file // in hash map String reqUrl = HttpUtils.getRequestURL(dreq.getHttpRequest()).toString(); // SQE: To support query string, we changed the hash key from Request URL to (Request URL + query string) if (dreq.getQuery() != null) reqUrl += dreq.getQuery(); // Check if entry already exist in HashMap JnlpFileEntry jnlpFile = (JnlpFileEntry) _jnlpFiles.get(reqUrl); if (jnlpFile != null && jnlpFile.getLastModified() == lastModified) { // Entry found in cache, so return it return jnlpFile.getResponse(); } // Read information from WAR file long timeStamp = lastModified; String mimeType = _servletContext.getMimeType(path); if (mimeType == null) mimeType = JNLP_MIME_TYPE; StringBuffer jnlpFileTemplate = new StringBuffer(); URLConnection conn = resource.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = br.readLine(); if (line != null && line.startsWith("TS:")) { timeStamp = parseTimeStamp(line.substring(3)); _log.addDebug("Timestamp: " + timeStamp + " " + new Date(timeStamp)); if (timeStamp == 0) { _log.addWarning("servlet.log.warning.notimestamp", path); timeStamp = lastModified; } line = br.readLine(); } while (line != null) { jnlpFileTemplate.append(line); line = br.readLine(); } String jnlpFileContent = specializeJnlpTemplate(dreq.getHttpRequest(), path, jnlpFileTemplate.toString()); /* SQE: We need to add query string back to href in jnlp file. We also need to handle JRE requirement for * the test. We reconstruct the xml DOM object, modify the value, then regenerate the jnlpFileContent. */ String query = dreq.getQuery(); String testJRE = dreq.getTestJRE(); _log.addDebug("Double check query string: " + query); // For backward compatibility: Always check if the href value exists. // Bug 4939273: We will retain the jnlp template structure and will NOT add href value. Above old // approach to always check href value caused some test case not run. // NOTE OTC: // This section has been rewritten: // - Switched from JAX to JDOM, allowing to preserve the formatting of the file // - regeneration based on the DOM will only be done if there are any changes to the file if (query != null && query.trim().length() > 0) { byte[] cb = jnlpFileContent.getBytes("UTF-8"); try { final XMLInputFactory factory = XMLInputFactory.newFactory(); final XMLEventReader reader = factory.createXMLEventReader(new ByteArrayInputStream(cb)); final StAXEventBuilder builder = new StAXEventBuilder(); final org.jdom2.Document document = builder.build(reader); boolean modified = false; final org.jdom2.Element root = document.getRootElement(); if (root.getAttribute("href") != null) { String href = root.getAttribute("href").getValue(); root.setAttribute("href", href + "?" + query); modified = true; } // Update version value for j2se tag if (testJRE != null) { org.jdom2.Element j2se = root.getChild("j2se"); if (j2se != null) { String ver = j2se.getAttribute("version").getValue(); if (ver.length() > 0) { j2se.setAttribute("version", testJRE); modified = true; } } } if (modified) { // we're only regenerating only if there have been any changes. final XMLOutputter outputter = new XMLOutputter(); final StringWriter sw = new StringWriter(); outputter.output(document, sw); jnlpFileContent = sw.toString(); } _log.addDebug("Converted jnlpFileContent: " + jnlpFileContent); // Since we modified the file on the fly, we always update the timestamp value with current time if (modified) { timeStamp = new Date().getTime(); _log.addDebug("Last modified on the fly: " + timeStamp); } } catch (Exception e) { _log.addDebug(e.toString(), e); } } // Convert to bytes as a UTF-8 encoding byte[] byteContent = jnlpFileContent.getBytes("UTF-8"); // Create entry DownloadResponse resp = DownloadResponse.getFileDownloadResponse(byteContent, mimeType, timeStamp, jnlpres.getReturnVersionId()); jnlpFile = new JnlpFileEntry(resp, lastModified); _jnlpFiles.put(reqUrl, jnlpFile); return resp; }
From source file:org.richfaces.examples.richrates.RatesBean.java
License:Open Source License
/** * Downloads an XML file from European Central Bank containing exchange rates for over 30 currencies for las 90 days * and parses it.//from w w w.j a v a 2s . co m */ private void getRates() { logger.info("Parsing exchange rates"); try { // TODO put into external file // http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml // http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml // http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml URL url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml"); Document document = new SAXBuilder().build(url); // TODO put into external file Namespace namespace = Namespace.getNamespace("http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); // TODO use XPath instead of the following line List<Element> dateElements = (List<Element>) document.getRootElement().getChild("Cube", namespace) .getChildren("Cube", namespace); String timeAttribute = null; Date date = null; // get newest date timeAttribute = dateElements.iterator().next().getAttributeValue("time"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setTimeZone(timeZone); issueDate = sdf.parse(timeAttribute); for (Element e : dateElements) { timeAttribute = e.getAttributeValue("time"); date = sdf.parse(timeAttribute); List<Element> children = (List<Element>) e.getChildren("Cube", namespace); Map<String, Double> oneDayRates = new HashMap<String, Double>(); for (Element node : children) { String currency = node.getAttributeValue("currency"); double rate = node.getAttribute("rate").getDoubleValue(); oneDayRates.put(currency, rate); } currencies.put(date, oneDayRates); } logger.info("List with exchange rates parsed"); } catch (JDOMException e) { logger.log(Level.SEVERE, "Could not parse XML with exchange rates"); e.printStackTrace(); } catch (ParseException e) { logger.log(Level.SEVERE, "Could not parse date format"); e.printStackTrace(); } catch (MalformedURLException e) { logger.log(Level.SEVERE, "Could not parse the URL with exchange rates"); e.printStackTrace(); } catch (IOException e) { logger.log(Level.SEVERE, "An I/O error prevents a document from being fully parsed"); e.printStackTrace(); } }
From source file:org.rometools.feed.module.itunes.io.ITunesParser.java
License:Open Source License
public com.sun.syndication.feed.module.Module parse(org.jdom2.Element element) { AbstractITunesObject module = null;/*w ww . j a v a2 s. c o m*/ if (element.getName().equals("channel")) { FeedInformationImpl feedInfo = new FeedInformationImpl(); module = feedInfo; //Now I am going to get the channel specific tags Element owner = element.getChild("owner", ns); if (owner != null) { Element name = owner.getChild("name", ns); if (name != null) { feedInfo.setOwnerName(name.getValue().trim()); } Element email = owner.getChild("email", ns); if (email != null) { feedInfo.setOwnerEmailAddress(email.getValue().trim()); } } Element image = element.getChild("image", ns); if ((image != null) && (image.getAttributeValue("href") != null)) { try { URL imageURL = new URL(image.getAttributeValue("href").trim()); feedInfo.setImage(imageURL); } catch (MalformedURLException e) { log.finer( "Malformed URL Exception reading itunes:image tag: " + image.getAttributeValue("href")); } } List categories = element.getChildren("category", ns); for (Iterator it = categories.iterator(); it.hasNext();) { Element category = (Element) it.next(); if ((category != null) && (category.getAttribute("text") != null)) { Category cat = new Category(); cat.setName(category.getAttribute("text").getValue().trim()); Element subcategory = category.getChild("category", ns); if (subcategory != null && subcategory.getAttribute("text") != null) { Subcategory subcat = new Subcategory(); subcat.setName(subcategory.getAttribute("text").getValue().trim()); cat.setSubcategory(subcat); } feedInfo.getCategories().add(cat); } } } else if (element.getName().equals("item")) { EntryInformationImpl entryInfo = new EntryInformationImpl(); module = entryInfo; //Now I am going to get the item specific tags Element duration = element.getChild("duration", ns); if (duration != null && duration.getValue() != null) { Duration dur = new Duration(duration.getValue().trim()); entryInfo.setDuration(dur); } } if (module != null) { //All these are common to both Channel and Item Element author = element.getChild("author", ns); if (author != null && author.getText() != null) { module.setAuthor(author.getText()); } Element block = element.getChild("block", ns); if (block != null) { module.setBlock(true); } Element explicit = element.getChild("explicit", ns); if ((explicit != null) && explicit.getValue() != null && explicit.getValue().trim().equalsIgnoreCase("yes")) { module.setExplicit(true); } Element keywords = element.getChild("keywords", ns); if (keywords != null) { StringTokenizer tok = new StringTokenizer(getXmlInnerText(keywords).trim(), ","); String[] keywordsArray = new String[tok.countTokens()]; for (int i = 0; tok.hasMoreTokens(); i++) { keywordsArray[i] = tok.nextToken(); } module.setKeywords(keywordsArray); } Element subtitle = element.getChild("subtitle", ns); if (subtitle != null) { module.setSubtitle(subtitle.getTextTrim()); } Element summary = element.getChild("summary", ns); if (summary != null) { module.setSummary(summary.getTextTrim()); } } return module; }
From source file:org.rometools.feed.module.opensearch.impl.OpenSearchModuleParser.java
License:Apache License
/** Use feed links and/or xml:base attribute to determine baseURI of feed */ private static URL findBaseURI(Element root) { URL baseURI = null;/*from w w w.j a va2 s. c o m*/ List linksList = root.getChildren("link", OS_NS); if (linksList != null) { for (Iterator links = linksList.iterator(); links.hasNext();) { Element link = (Element) links.next(); if (!root.equals(link.getParent())) break; String href = link.getAttribute("href").getValue(); if (link.getAttribute("rel", OS_NS) == null || link.getAttribute("rel", OS_NS).getValue().equals("alternate")) { href = resolveURI(null, link, href); try { baseURI = new URL(href); break; } catch (MalformedURLException e) { System.err.println("Base URI is malformed: " + href); } } } } return baseURI; }
From source file:org.rometools.feed.module.sle.io.ModuleParser.java
License:Apache License
/** * Parses the XML node (JDOM element) extracting module information. * <p>/*from w w w . ja v a2s . com*/ * * @param element the XML node (JDOM element) to extract module information from. * @return a module instance, <b>null</b> if the element did not have module information. */ public Module parse(Element element) { if (element.getChild("treatAs", NS) == null) { return null; } SimpleListExtension sle = new SimpleListExtensionImpl(); sle.setTreatAs(element.getChildText("treatAs", NS)); Element listInfo = element.getChild("listinfo", NS); List groups = listInfo.getChildren("group", NS); ArrayList values = new ArrayList(); for (int i = 0; (groups != null) && (i < groups.size()); i++) { Element ge = (Element) groups.get(i); Namespace ns = (ge.getAttribute("ns") == null) ? element.getNamespace() : Namespace.getNamespace(ge.getAttributeValue("ns")); String elementName = ge.getAttributeValue("element"); String label = ge.getAttributeValue("label"); values.add(new Group(ns, elementName, label)); } sle.setGroupFields((Group[]) values.toArray(new Group[values.size()])); values = (values.size() == 0) ? values : new ArrayList(); List sorts = listInfo.getChildren("sort", NS); for (int i = 0; (sorts != null) && (i < sorts.size()); i++) { Element se = (Element) sorts.get(i); System.out.println( "Parse cf:sort " + se.getAttributeValue("element") + se.getAttributeValue("data-type")); Namespace ns = (se.getAttributeValue("ns") == null) ? element.getNamespace() : Namespace.getNamespace(se.getAttributeValue("ns")); String elementName = se.getAttributeValue("element"); String label = se.getAttributeValue("label"); String dataType = se.getAttributeValue("data-type"); boolean defaultOrder = (se.getAttributeValue("default") == null) ? false : new Boolean(se.getAttributeValue("default")).booleanValue(); values.add(new Sort(ns, elementName, dataType, label, defaultOrder)); } sle.setSortFields((Sort[]) values.toArray(new Sort[values.size()])); insertValues(sle, element.getChildren()); return sle; }