Exemplo n.º 1
0
 private String getTagData(Element root, String name) {
   // Isolate the EPC code using a very painful recursive method.
   Element tagReportData = root.getChild("TagReportData", root.getNamespace());
   Element dataElement = tagReportData.getChild(name, root.getNamespace());
   String data = dataElement.getContent(0).getValue();
   return data.toString();
 }
Exemplo n.º 2
0
  public XMIVersionExtractor(File xmlFile) {
    try {
      SAXBuilder builder = new SAXBuilder();
      Document doc = builder.build(xmlFile);

      Element root = doc.getRootElement();
      if (root.getName().equals("XMI")) {
        String version = null;
        version = root.getAttributeValue("xmi.version");
        if (version != null) {
          this.version = version;
        } else {
          version = root.getAttributeValue("version", root.getNamespace());
          if (version != null) this.version = version;
        }
      } else {
        Element xmiRoot = root.getChild("XMI");
        if (xmiRoot != null) {
          String version = null;
          version = xmiRoot.getAttributeValue("xmi.version");
          if (version != null) {
            this.version = version;
          } else {
            version = xmiRoot.getAttributeValue("version", xmiRoot.getNamespace());
            if (version != null) this.version = version;
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 3
0
 /**
  * Test if two elements have the same namespace and name.
  *
  * @param elem1 an element, can be <code>null</code>.
  * @param elem2 an element, can be <code>null</code>.
  * @return <code>true</code> if both elements have the same name and namespace, or if both are
  *     <code>null</code>.
  */
 public static boolean equals(Element elem1, Element elem2) {
   if (elem1 == null && elem2 == null) return true;
   else if (elem1 == null || elem2 == null) return false;
   else
     return elem1.getName().equals(elem2.getName())
         && elem1.getNamespace().equals(elem2.getNamespace());
 }
Exemplo n.º 4
0
  /* (non-Javadoc)
   * @see edu.xtec.qv.qti.QTIObject#createFromXML(org.jdom.Element)
   */
  public void createFromXML(Element eElement) {
    if (eElement != null) {
      setAttribute(VIEW, eElement.getChildText(VIEW.getTagName()));

      // Add qticomment
      if (eElement.getChild(QTICOMMENT.getTagName(), eElement.getNamespace()) != null) {
        QTIComment oComment =
            new QTIComment(eElement.getChild(QTICOMMENT.getTagName(), eElement.getNamespace()));
        setAttribute(QTICOMMENT, oComment);
      }

      // Add material and flow_mat
      Vector vContents = new Vector();
      Iterator itContents = eElement.getChildren().iterator();
      while (itContents.hasNext()) {
        Element eContent = (Element) itContents.next();
        QTIObject oContent = null;
        if (FLOW_MAT.equals(eContent.getName())) {
          oContent = new FlowMat(eContent);
        } else if (MATERIAL.equals(eContent.getName())) {
          oContent = new Material(eContent);
        }
        if (oContent != null) {
          vContents.addElement(oContent);
        }
      }
      setAttribute(CONTENT, vContents);
    }
  }
Exemplo n.º 5
0
 private static String getTagElement(Element elem, String tagName) {
   if (elem != null && elem.getChild(tagName, elem.getNamespace("sla")) != null) {
     return elem.getChild(tagName, elem.getNamespace("sla")).getText().trim();
   } else {
     return null;
   }
 }
Exemplo n.º 6
0
 protected void initNamespaces() {
   this.namespaces = new HashMap<String, Namespace>();
   Element root = this.getRoot();
   this.namespaces.put(root.getNamespace().getPrefix().toLowerCase(), root.getNamespace());
   for (Namespace a : (List<Namespace>) root.getAdditionalNamespaces()) {
     this.namespaces.put(a.getPrefix().toLowerCase(), a);
   }
 }
 private static Element getOrCreateElement(final Element parentElement, final String elementName) {
   Element child = parentElement.getChild(elementName, parentElement.getNamespace());
   if (child == null) {
     child = new Element(elementName, parentElement.getNamespace());
     parentElement.addContent(child);
   }
   return child;
 }
Exemplo n.º 8
0
 private String getStyleVersion(Element extDataElement) {
   Element serviceFeaturesElement =
       extDataElement.getChild("ServiceFeatures", extDataElement.getNamespace());
   Element serviceStyleElement =
       serviceFeaturesElement.getChild("ServiceStyle", serviceFeaturesElement.getNamespace());
   String styleVersion = null;
   if (serviceStyleElement != null) {
     styleVersion = serviceStyleElement.getAttributeValue("version");
   }
   return styleVersion;
 }
Exemplo n.º 9
0
 /**
  * Cleanup output-events directories
  *
  * @param eAction coordinator action xml
  */
 @SuppressWarnings("unchecked")
 private void cleanupOutputEvents(Element eAction) throws CommandException {
   Element outputList = eAction.getChild("output-events", eAction.getNamespace());
   if (outputList != null) {
     for (Element data :
         (List<Element>) outputList.getChildren("data-out", eAction.getNamespace())) {
       String nocleanup = data.getAttributeValue("nocleanup");
       if (data.getChild("uris", data.getNamespace()) != null
           && (nocleanup == null || !nocleanup.equals("true"))) {
         String uris = data.getChild("uris", data.getNamespace()).getTextTrim();
         if (uris != null) {
           String[] uriArr = uris.split(CoordELFunctions.INSTANCE_SEPARATOR);
           Configuration actionConf = null;
           try {
             actionConf = new XConfiguration(new StringReader(coordJob.getConf()));
           } catch (IOException e) {
             throw new CommandException(
                 ErrorCode.E0907, "failed to read coord job conf to clean up output data");
           }
           HashMap<String, Context> contextMap = new HashMap<String, Context>();
           try {
             for (String uriStr : uriArr) {
               URI uri = new URI(uriStr);
               URIHandler handler = Services.get().get(URIHandlerService.class).getURIHandler(uri);
               String schemeWithAuthority = uri.getScheme() + "://" + uri.getAuthority();
               if (!contextMap.containsKey(schemeWithAuthority)) {
                 Context context = handler.getContext(uri, actionConf, coordJob.getUser(), false);
                 contextMap.put(schemeWithAuthority, context);
               }
               handler.delete(uri, contextMap.get(schemeWithAuthority));
               LOG.info("Cleanup the output data " + uri.toString());
             }
           } catch (URISyntaxException e) {
             throw new CommandException(ErrorCode.E0907, e.getMessage());
           } catch (URIHandlerException e) {
             throw new CommandException(ErrorCode.E0907, e.getMessage());
           } finally {
             Iterator<Entry<String, Context>> itr = contextMap.entrySet().iterator();
             while (itr.hasNext()) {
               Entry<String, Context> entry = itr.next();
               entry.getValue().destroy();
               itr.remove();
             }
           }
         }
       }
     }
   } else {
     LOG.info("No output-events defined in coordinator xml. Therefore nothing to cleanup");
   }
 }
Exemplo n.º 10
0
 /**
  * Add namespace declaration to <code>elem</code> if needed. Necessary since JDOM uses a simple
  * list.
  *
  * @param elem the element where namespaces should be available.
  * @param c the namespaces to add.
  * @see Element#addNamespaceDeclaration(Namespace)
  */
 public static void addNamespaces(final Element elem, final Collection<Namespace> c) {
   if (c instanceof RandomAccess && c instanceof List) {
     final List<Namespace> list = (List<Namespace>) c;
     final int stop = c.size() - 1;
     for (int i = 0; i < stop; i++) {
       final Namespace ns = list.get(i);
       if (elem.getNamespace(ns.getPrefix()) == null) elem.addNamespaceDeclaration(ns);
     }
   } else {
     for (final Namespace ns : c) {
       if (elem.getNamespace(ns.getPrefix()) == null) elem.addNamespaceDeclaration(ns);
     }
   }
 }
Exemplo n.º 11
0
  /**
   * Resolve datasets using job configuration.
   *
   * @param eAppXml : Job Element XML
   * @throws Exception thrown if failed to resolve datasets
   */
  @SuppressWarnings("unchecked")
  private void resolveDataSets(Element eAppXml) throws Exception {
    Element datasetList = eAppXml.getChild("datasets", eAppXml.getNamespace());
    if (datasetList != null) {

      List<Element> dsElems = datasetList.getChildren("dataset", eAppXml.getNamespace());
      resolveDataSets(dsElems);
      resolveTagContents(
          "app-path",
          eAppXml
              .getChild("action", eAppXml.getNamespace())
              .getChild("workflow", eAppXml.getNamespace()),
          evalNofuncs);
    }
  }
Exemplo n.º 12
0
 /**
  * Create SLA RegistrationEvent
  *
  * @param actionXml action xml
  * @param actionBean coordinator action bean
  * @param user user name
  * @param group group name
  * @throws Exception thrown if unable to write sla registration event
  */
 private void writeActionRegistration(
     String actionXml, CoordinatorActionBean actionBean, String user, String group)
     throws Exception {
   Element eAction = XmlUtils.parseXml(actionXml);
   Element eSla =
       eAction
           .getChild("action", eAction.getNamespace())
           .getChild("info", eAction.getNamespace("sla"));
   SLAEventBean slaEvent =
       SLADbOperations.createSlaRegistrationEvent(
           eSla, actionBean.getId(), SlaAppType.COORDINATOR_ACTION, user, group, LOG);
   if (slaEvent != null) {
     insertList.add(slaEvent);
   }
 }
 /*
  * @see org.rssowl.core.interpreter.IFormatInterpreter#interpret(org.jdom.Document,
  * org.rssowl.core.interpreter.types.IFeed)
  */
 public void interpret(Document document, IFeed feed) {
   Element root = document.getRootElement();
   setDefaultNamespaceUri(root.getNamespace().getURI());
   setRootElementName(root.getName());
   feed.setFormat("RSS"); // $NON-NLS-1$
   processFeed(root, feed);
 }
Exemplo n.º 14
0
  /**
   * For Ajax Editing : swap element with sibling ([up] and [down] links).
   *
   * @param dbms
   * @param session
   * @param id
   * @param ref
   * @param down
   * @throws Exception
   */
  public synchronized void swapElementEmbedded(
      Dbms dbms, UserSession session, String id, String ref, boolean down) throws Exception {
    dataManager.getMetadataSchema(dbms, id);

    // --- get metadata from session
    Element md = getMetadataFromSession(session, id);

    // --- get element to swap
    EditLib editLib = dataManager.getEditLib();
    Element elSwap = editLib.findElement(md, ref);

    if (elSwap == null) throw new IllegalStateException(MSG_ELEMENT_NOT_FOUND_AT_REF + ref);

    // --- swap the elements
    int iSwapIndex = -1;

    List list = ((Element) elSwap.getParent()).getChildren(elSwap.getName(), elSwap.getNamespace());

    for (int i = 0; i < list.size(); i++)
      if (list.get(i) == elSwap) {
        iSwapIndex = i;
        break;
      }

    if (iSwapIndex == -1)
      throw new IllegalStateException("Index not found for element --> " + elSwap);

    if (down) swapElements(elSwap, (Element) list.get(iSwapIndex + 1));
    else swapElements(elSwap, (Element) list.get(iSwapIndex - 1));

    // --- store the metadata in the session again
    setMetadataIntoSession(session, (Element) md.clone(), id);
  }
Exemplo n.º 15
0
  public Element createXML() {
    if (agents.getSelectedIndex() + 1 < agents.getModel().getSize()) {
      Element e = (Element) AgentComboBoxModel.getAgents().get(agents.getSelectedIndex());
      Vector settings = new Vector();
      // Eigenschaften ab 7 werden als Settings fürs Tool ausgelesen (EXIF-Tags) :)
      // ist keines gesetzt, so wird der Vector wieder auf null gesetzt :)
      boolean atLeastOneSettingDefined = false;
      Iterator itVals = ctm.getValues().iterator();
      int tempCount = 0;
      for (Object o : ctm.getKeys()) {
        String tempKey = (String) o;
        String tempVal = (String) itVals.next();
        if (tempVal.length() > 0
            && tempCount > 5) { // Wenn Wert da und wenns keiner der ersten 6 std werte is
          settings.add(tempKey + "=" + tempVal);
          atLeastOneSettingDefined = true;
        }
        tempCount++;
      }
      if (!atLeastOneSettingDefined) settings = null;
      String time = null;
      if (datatable.getValueAt(0, 1).toString().length() > 0)
        time = datatable.getValueAt(0, 1).toString();

      String tool = null;
      int count = 0;
      for (Object o1 : ctm.getKeys()) {
        String s = (String) o1;
        if (s.equals("Make")) {
          if (tool == null) tool = new String();
          tool = ctm.getValues().get(count) + " " + tool;
        }
        if (s.equals("Model")) {
          if (tool == null) tool = new String();
          tool = tool + ctm.getValues().get(count);
        }
        count++;
      }
      Mpeg7CreationInformation m7ci = new Mpeg7CreationInformation(e, tool, settings, time);
      // Getting data ....
      String bits = null, fformat = null, fsize = null, ih = null, iw = null;
      if (datatable.getValueAt(1, 1).toString().length() > 0)
        fformat = datatable.getValueAt(1, 1).toString();
      if (datatable.getValueAt(2, 1).toString().length() > 0)
        fsize = datatable.getValueAt(2, 1).toString();
      if (datatable.getValueAt(4, 1).toString().length() > 0)
        ih = datatable.getValueAt(4, 1).toString();
      if (datatable.getValueAt(3, 1).toString().length() > 0)
        iw = datatable.getValueAt(3, 1).toString();
      if (datatable.getValueAt(5, 1).toString().length() > 0)
        bits = datatable.getValueAt(5, 1).toString();
      Mpeg7MediaFormat m7mf = new Mpeg7MediaFormat(bits, fformat, fsize, ih, iw);
      Element mediaFormat = m7mf.createDocument();
      Element ret = new Element("return", mediaFormat.getNamespace()).addContent(mediaFormat);
      ret.addContent(m7ci.createDocument().detach());
      return ret;
    } else {
      return null;
    }
  }
Exemplo n.º 16
0
  /* (non-Javadoc)
   * @see org.dspace.app.dav.DAVResource#proppatchInternal(int, org.jdom.Element)
   */
  @Override
  protected int proppatchInternal(int action, Element prop)
      throws SQLException, AuthorizeException, IOException, DAVStatusException {
    // Don't need any authorization checks since the Item layer
    // checks authorization for write and delete.

    Namespace ns = prop.getNamespace();
    String propName = prop.getName();

    // "submitter" is the only Item-specific mutable property, rest are
    // live and unchangeable.
    if (ns != null && ns.equals(DAV.NS_DSPACE) && propName.equals("submitter")) {
      if (action == DAV.PROPPATCH_REMOVE) {
        throw new DAVStatusException(DAV.SC_CONFLICT, "The submitter property cannot be removed.");
      }
      String newName = prop.getText();
      EPerson ep = EPerson.findByEmail(this.context, newName);
      if (ep == null) {
        throw new DAVStatusException(
            DAV.SC_CONFLICT,
            "Cannot set submitter, no EPerson found for email address: " + newName);
      }
      this.item.setSubmitter(ep);
      this.item.update();
      return HttpServletResponse.SC_OK;
    }
    throw new DAVStatusException(
        DAV.SC_CONFLICT, "The " + prop.getName() + " property cannot be changed.");
  }
Exemplo n.º 17
0
 public void testIsReferencingElement3() throws Exception {
   loadContentPackage1();
   // Dependency Element - true
   Element element =
       cpCore.getElementByIdentifier(cpCore.getRootManifestElement(), CP_Package1.RESOURCE1_ID);
   element = element.getChild(CP_Core.DEPENDENCY, element.getNamespace());
   assertTrue("Should be referencing element", cpCore.isReferencingElement(element));
 }
Exemplo n.º 18
0
 /**
  * Check to see if the object matches a predefined set of rules.
  *
  * @param obj The object to verify.
  * @return <code>true</code> if the objected matched a predfined set of rules.
  */
 public boolean matches(Object obj) {
   if (obj instanceof Element) {
     Element el = (Element) obj;
     return (this.name == null || this.name.equals(el.getName()))
         && (this.namespace == null || this.namespace.equals(el.getNamespace()));
   }
   return false;
 }
Exemplo n.º 19
0
  public String getNamespaceURI(String prefix) {
    Namespace namespace = element.getNamespace(prefix);
    if (namespace == null) {
      return null;
    }

    return namespace.getURI();
  }
Exemplo n.º 20
0
  /**
   * Returns the prefix for the request: http://wms.jpl.nasa.gov/wms.cgi?
   *
   * @return
   */
  public String getBaseUrl() {
    Element onlineResource = tiledPatterns.getChild("OnlineResource"); // $NON-NLS-1$
    Namespace xlink = onlineResource.getNamespace("xlink"); // $NON-NLS-1$
    Attribute href = onlineResource.getAttribute("href", xlink); // $NON-NLS-1$
    String baseUrl = href.getValue();

    return baseUrl;
  }
Exemplo n.º 21
0
  // apply metadata values returned in DIM to the target item.
  private void applyDim(List dimList, Item item) throws MetadataValidationException {
    Iterator di = dimList.iterator();
    while (di.hasNext()) {
      Element elt = (Element) di.next();
      if (elt.getName().equals("field") && elt.getNamespace().equals(DIM_NS))
        applyDimField(elt, item);

      // if it's a <dim> container, apply its guts
      else if (elt.getName().equals("dim") && elt.getNamespace().equals(DIM_NS))
        applyDim(elt.getChildren(), item);
      else {
        log.error("Got unexpected element in DIM list: " + elt.toString());
        throw new MetadataValidationException(
            "Got unexpected element in DIM list: " + elt.toString());
      }
    }
  }
 protected void transformXML(File[] files) {
   int number = 0;
   try {
     SAXBuilder builder = new SAXBuilder();
     for (int f = 0; f < files.length; f++) {
       int fn = f + 1;
       // split by treatment
       Document doc = builder.build(files[f]);
       Element root = doc.getRootElement();
       List<Element> treatments =
           XPath.selectNodes(root, "/tax:taxonx/tax:taxonxBody/tax:treatment");
       // detach all but one treatments from doc
       ArrayList<Element> saved = new ArrayList<Element>();
       for (int t = 1; t < treatments.size(); t++) {
         Element e = treatments.get(t);
         doc.removeContent(e);
         e.detach();
         saved.add(e);
       }
       // now doc is a template to create other treatment files
       // root.detach();
       formatDescription(
           (Element) XPath.selectSingleNode(root, "/tax:taxonx/tax:taxonxBody/tax:treatment"),
           ".//tax:div[@type='description']",
           ".//tax:p",
           fn,
           0);
       root.detach();
       writeTreatment2Transformed(root, fn, 0);
       listener.info((number++) + "", fn + "_0.xml"); // list the file on GUI here
       getDescriptionFrom(root, fn, 0);
       // replace treatement in doc with a new treatment in saved
       Iterator<Element> it = saved.iterator();
       int count = 1;
       while (it.hasNext()) {
         Element e = it.next();
         Element body = root.getChild("taxonxBody", root.getNamespace());
         Element treatment =
             (Element) XPath.selectSingleNode(root, "/tax:taxonx/tax:taxonxBody/tax:treatment");
         // in treatment/div[@type="description"], replace <tax:p> tag with <description
         // pid="1.txtp436_1.txt">
         int index = body.indexOf(treatment);
         e = formatDescription(e, ".//tax:div[@type='description']", ".//tax:p", fn, count);
         body.setContent(index, e);
         // write each treatment as a file in the target/transfromed folder
         // write description text in the target/description folder
         root.detach();
         writeTreatment2Transformed(root, fn, count);
         listener.info((number++) + "", fn + "_" + count + ".xml"); // list the file on GUI here
         getDescriptionFrom(root, fn, count);
         count++;
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     LOGGER.error("Type4Transformer : error.", e);
   }
 }
Exemplo n.º 23
0
 /**
  * Gets the unmodified bpel process as xml element. <br>
  * All elements needed for instrumentating will be saved
  *
  * @param unmodified bpel process
  */
 public void setOriginalBPELProcess(Element process) {
   ElementFilter filter = new ElementFilter(process.getNamespace());
   elementsOfBPEL = new ArrayList<Element>();
   for (Iterator<Element> iter = process.getDescendants(filter); iter.hasNext(); ) {
     Element basicActivity = iter.next();
     if (activities_to_respekt.contains(basicActivity.getName()))
       elementsOfBPEL.add(basicActivity);
   }
 }
Exemplo n.º 24
0
 @Override
 public void translate(Document dom) throws Exception {
   Element root = dom.getRootElement();
   namespace = root.getNamespace();
   List<Element> children = dom.getRootElement().getChildren(SERVICE_NODE, namespace);
   for (Element child : children) {
     visit(child);
   }
 }
Exemplo n.º 25
0
  /* (non-Javadoc)
   * @see org.dspace.app.dav.DAVDSpaceObject#propfindInternal(org.jdom.Element)
   */
  @Override
  protected Element propfindInternal(Element property)
      throws SQLException, AuthorizeException, IOException, DAVStatusException {
    String value = null;

    /*
     * FIXME: This implements permission check that really belongs in
     * business logic. Although communities and collections don't check for
     * read auth, Item may contain sensitive data and should always check
     * for READ permission. Exception: allow "withdrawn" property to be
     * checked regardless of authorization since all permissions are removed
     * when item is withdrawn.
     */
    if (!elementsEqualIsh(property, withdrawnProperty)) {
      AuthorizeManager.authorizeAction(this.context, this.item, Constants.READ);
    }

    if (elementsEqualIsh(property, withdrawnProperty)) {
      value = String.valueOf(this.item.isWithdrawn());
    } else if (elementsEqualIsh(property, displaynameProperty)) {
      // displayname - title or handle.
      DCValue titleDc[] = this.item.getDC("title", Item.ANY, Item.ANY);
      value = titleDc.length > 0 ? titleDc[0].value : this.item.getHandle();
    } else if (elementsEqualIsh(property, handleProperty)) {
      value = canonicalizeHandle(this.item.getHandle());
    } else if (elementsEqualIsh(property, submitterProperty)) {
      EPerson ep = this.item.getSubmitter();
      if (ep != null) {
        value = hrefToEPerson(ep);
      }
    } else if (elementsEqualIsh(property, owning_collectionProperty)) {
      Collection owner = this.item.getOwningCollection();
      if (owner != null) {
        value = canonicalizeHandle(owner.getHandle());
      }
    } else if (elementsEqualIsh(property, getlastmodifiedProperty)) {
      value = DAV.HttpDateFormat.format(this.item.getLastModified());
    } else if (elementsEqualIsh(property, licenseProperty)) {
      value = getLicenseAsString();
    } else if (elementsEqualIsh(property, cc_license_textProperty)) {
      value = LicenceController.getLicenseText(this.item);
    } else if (elementsEqualIsh(property, cc_license_rdfProperty)) {
      value = LicenceController.getLicenseRDF(this.item);
    } else if (elementsEqualIsh(property, cc_license_urlProperty)) {
      value = LicenceController.getLicenseURL(this.item);
    } else {
      return super.propfindInternal(property);
    }

    // value was set up by "if" clause:
    if (value == null) {
      throw new DAVStatusException(HttpServletResponse.SC_NOT_FOUND, "Not found.");
    }
    Element p = new Element(property.getName(), property.getNamespace());
    p.setText(filterForXML(value));
    return p;
  }
Exemplo n.º 26
0
 @SuppressWarnings("unchecked")
 public static Element mediaContent(Entry syndEntry) {
   for (Element element : (List<Element>) syndEntry.getForeignMarkup()) {
     if (NS_MEDIA_RSS.equals(element.getNamespace()) && "content".equals(element.getName())) {
       return element;
     }
   }
   return null;
 }
  /**
   * Add a new policy to the device repository in use. This will add the policy to the definitions
   * document and to the master device file.
   *
   * @param policyName the name of the new policy. Cannot be null.
   * @param composition the PolicyTypeComposition of the new policy
   * @param type the PolicyType of the new policy
   * @throws IllegalArgumentException if the named policy already exists or if any of the arguments
   *     are null.
   */
  private void addNewPolicyToRepository(
      String policyName, PolicyTypeComposition composition, PolicyType type) {
    if (policyName == null) {
      throw new IllegalArgumentException("Cannot be null: " + policyName);
    }
    if (composition == null) {
      throw new IllegalArgumentException("Cannot be null: " + composition);
    }
    if (type == null) {
      throw new IllegalArgumentException("Cannot be null: " + type);
    }
    String masterDeviceName = context.getDeviceRepositoryAccessorManager().retrieveRootDeviceName();
    boolean policyExists =
        context.getDeviceRepositoryAccessorManager().retrievePolicy(masterDeviceName, policyName)
            != null;

    if (policyExists) {
      throw new IllegalArgumentException(
          "Policy " + policyName + " already exists. Aborting new policy.");
    }

    // Add the policy to the definitions document
    Element category = categoriesComposite.getSelectedCategoryElement();
    Element policy =
        context
            .getODOMFactory()
            .element(DeviceRepositorySchemaConstants.POLICY_ELEMENT_NAME, category.getNamespace());
    policy.setAttribute(DeviceRepositorySchemaConstants.POLICY_NAME_ATTRIBUTE, policyName);
    category.addContent(policy);
    composition.addTypeElement(policy, type, context.getODOMFactory());

    // Add the policy to the master device
    Element masterDevice =
        context.getDeviceRepositoryAccessorManager().retrieveDeviceElement(masterDeviceName);

    StringBuffer xPathBuffer = new StringBuffer();
    xPathBuffer
        .append("//")
        . //$NON-NLS-1$
        append(MCSNamespace.DEVICE.getPrefix())
        .append(':')
        .append(DeviceRepositorySchemaConstants.POLICIES_ELEMENT_NAME);
    XPath policiesXPath = new XPath(xPathBuffer.toString(), new Namespace[] {MCSNamespace.DEVICE});

    try {
      Element policies = policiesXPath.selectSingleElement(masterDevice);
      composition.addDefaultPolicyValue(
          policies,
          policyName,
          type,
          context.getODOMFactory(),
          context.getDeviceRepositoryAccessorManager());
    } catch (XPathException e) {
      EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e);
    }
  }
Exemplo n.º 28
0
 /**
  * This will take the supplied <code>{@link Element}</code> and transfer its namespaces to the
  * global namespace storage.
  *
  * @param element <code>Element</code> to read namespaces from.
  */
 private void transferNamespaces(Element element) {
   Iterator i = declaredNamespaces.iterator();
   while (i.hasNext()) {
     Namespace ns = (Namespace) i.next();
     if (ns != element.getNamespace()) {
       element.addNamespaceDeclaration(ns);
     }
   }
   declaredNamespaces.clear();
 }
Exemplo n.º 29
0
 /**
  * Remove a dataset from a list of dataset.
  *
  * @param eDatasets : List of dataset
  * @param name : Dataset name to be removed.
  */
 @SuppressWarnings("unchecked")
 private static void removeDataSet(Element eDatasets, String name) {
   for (Element eDataset :
       (List<Element>) eDatasets.getChildren("dataset", eDatasets.getNamespace())) {
     if (eDataset.getAttributeValue("name").equals(name)) {
       eDataset.detach();
     }
   }
   throw new RuntimeException("undefined dataset: " + name);
 }
Exemplo n.º 30
0
 /**
  * Insert data set into data-in and data-out tags.
  *
  * @param eAppXml : coordinator application XML
  * @param eDatasets : DataSet XML
  */
 @SuppressWarnings("unchecked")
 private void insertDataSet(Element eAppXml, Element eDatasets) {
   // Adding DS definition in the coordinator XML
   Element inputList = eAppXml.getChild("input-events", eAppXml.getNamespace());
   if (inputList != null) {
     for (Element dataIn :
         (List<Element>) inputList.getChildren("data-in", eAppXml.getNamespace())) {
       Element eDataset = findDataSet(eDatasets, dataIn.getAttributeValue("dataset"));
       dataIn.getContent().add(0, eDataset);
     }
   }
   Element outputList = eAppXml.getChild("output-events", eAppXml.getNamespace());
   if (outputList != null) {
     for (Element dataOut :
         (List<Element>) outputList.getChildren("data-out", eAppXml.getNamespace())) {
       Element eDataset = findDataSet(eDatasets, dataOut.getAttributeValue("dataset"));
       dataOut.getContent().add(0, eDataset);
     }
   }
 }