Java Code Examples for org.jdom2.Attribute#getValue()

The following examples show how to use org.jdom2.Attribute#getValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MCRMetsSave.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Searches a file in a group, which matches a filename.
 *
 * @param mets the mets file to search
 * @param path the path to the alto file (e.g. "alto/alto_file.xml" when searching in DEFAULT_FILE_GROUP_USE or
 *             "image_file.jpg" when searchin in ALTO_FILE_GROUP_USE)
 * @param searchFileGroup
 * @return the id of the matching file or null if there is no matching file
 */
private static String searchFileInGroup(Document mets, String path, String searchFileGroup) {
    XPathExpression<Element> xpath;// first check all files in default file group
    String relatedFileExistPathString = String.format(Locale.ROOT,
        "mets:mets/mets:fileSec/mets:fileGrp[@USE='%s']/mets:file/mets:FLocat", searchFileGroup);
    xpath = XPathFactory.instance().compile(relatedFileExistPathString, Filters.element(), null,
        MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    List<Element> fileLocList = xpath.evaluate(mets);
    String matchId = null;

    // iterate over all files
    String cleanPath = getCleanPath(path);

    for (Element fileLoc : fileLocList) {
        Attribute hrefAttribute = fileLoc.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
        String hrefAttributeValue = hrefAttribute.getValue();
        String hrefPath = getCleanPath(removeExtension(hrefAttributeValue));

        if (hrefPath.equals(removeExtension(cleanPath))) {
            matchId = ((Element) fileLoc.getParent()).getAttributeValue("ID");
            break;
        }
    }
    return matchId;
}
 
Example 2
Source File: OpenSearchModuleParser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Use xml:base attributes at feed and entry level to resolve relative links
 */
private static String resolveURI(final URL baseURI, final Parent parent, String url) {
    url = url.equals(".") || url.equals("./") ? "" : url;
    if (isRelativeURI(url) && parent != null && parent instanceof Element) {
        final Attribute baseAtt = ((Element) parent).getAttribute("base", Namespace.XML_NAMESPACE);
        String xmlBase = baseAtt == null ? "" : baseAtt.getValue();
        if (!isRelativeURI(xmlBase) && !xmlBase.endsWith("/")) {
            xmlBase = xmlBase.substring(0, xmlBase.lastIndexOf("/") + 1);
        }
        return resolveURI(baseURI, parent.getParent(), xmlBase + url);
    } else if (isRelativeURI(url) && parent == null) {
        return baseURI + url;
    } else if (baseURI != null && url.startsWith("/")) {
        String hostURI = baseURI.getProtocol() + "://" + baseURI.getHost();
        if (baseURI.getPort() != baseURI.getDefaultPort()) {
            hostURI = hostURI + ":" + baseURI.getPort();
        }
        return hostURI + url;
    }
    return url;
}
 
Example 3
Source File: MCRMODSMetadataShareAgent.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Recursivly checks <code>relatedItem</code> and parent &lt;mods:relatedItem&gt; elements for multiple {@link MCRObjectID}s.
 * @param relatedItem &lt;mods:relatedItem&gt;
 * @param idCollected of IDs collected so far
 * @throws MCRPersistenceException if {@link MCRObjectID} of <code>relatedItem</code> is in <code>idCollected</code>
 */
private void checkHierarchy(Element relatedItem, Set<MCRObjectID> idCollected) throws MCRPersistenceException {
    final Attribute href = relatedItem.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
    if (href != null) {
        final String testId = href.getValue();
        LOGGER.debug("Checking relatedItem {}.", testId);
        if (MCRObjectID.isValid(testId)) {
            final MCRObjectID relatedItemId = MCRObjectID.getInstance(testId);
            LOGGER.debug("Checking if {} is in {}.", relatedItemId, idCollected);
            if (!idCollected.add(relatedItemId)) {
                throw new MCRPersistenceException(
                    "Hierarchy of mods:relatedItem contains ciruit by object " + relatedItemId);
            }
        }
    }
    final Element parentElement = relatedItem.getParentElement();
    if (parentElement.getName().equals("relatedItem")) {
        checkHierarchy(parentElement, idCollected);
    }
}
 
Example 4
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Parse a piece of formatted text, which can be either plain text with legacy
 * formatting codes, or JSON chat components.
 */
public static BaseComponent parseFormattedText(@Nullable Node node, BaseComponent def) throws InvalidXMLException {
    if(node == null) return def;

    // <blah translate="x"/> is shorthand for <blah>{"translate":"x"}</blah>
    if(node.isElement()) {
        final Attribute translate = node.asElement().getAttribute("translate");
        if(translate != null) {
            return new TranslatableComponent(translate.getValue());
        }
    }

    String text = node.getValueNormalize();
    if(looksLikeJson(text)) {
        try {
            return Components.concat(ComponentSerializer.parse(node.getValue()));
        } catch(JsonParseException e) {
            throw new InvalidXMLException(e.getMessage(), node, e);
        }
    } else {
        return Components.concat(TextComponent.fromLegacyText(BukkitUtils.colorize(text)));
    }
}
 
Example 5
Source File: XMLConfigProvider.java    From java-trader with Apache License 2.0 5 votes vote down vote up
private String getItem(String[] configParts){
    LinkedList<String> parts = new LinkedList<String>( Arrays.asList(configParts));

    Element elem = doc.getRootElement();
    Attribute attr= null;
    while( elem!=null && !parts.isEmpty() ){
        String part = parts.poll();
        if ( part.length()==0 ){
            continue;
        }
        Element child = getChildElem(elem, part);
        if ( child!=null ){
            elem = child;
            attr = null;
            continue;
        }
        attr = elem.getAttribute(part);
        if ( child==null && attr==null ){
            elem = null;
            break;
        }
        continue;
    }
    if ( attr!=null ){
        return attr.getValue();
    }
    if ( elem!=null ){
        return elem.getText();
    }
    return null;
}
 
Example 6
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static BaseComponent parseLocalizedText(Element el) throws InvalidXMLException {
    final Attribute translate = el.getAttribute("translate");
    if(translate != null) {
        return new TranslatableComponent(translate.getValue());
    } else {
        return new Component(el.getTextNormalize());
    }
}
 
Example 7
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static DyeColor parseDyeColor(Attribute attr) throws InvalidXMLException {
    String name = attr.getValue().replace(" ", "_").toUpperCase();
    try {
        return DyeColor.valueOf(name);
    }
    catch(IllegalArgumentException e) {
        throw new InvalidXMLException("Invalid dye color '" + attr.getValue() + "'", attr);
    }
}
 
Example 8
Source File: ApiXmlResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Get a page corresponding to a page node.
 * 
 * @param wiki Wiki.
 * @param pageNode Page node.
 * @param knownPages Already known pages.
 * @param useDisambig True if disambiguation property should be used.
 * @return Page.
 */
protected static Page getPage(
    EnumWikipedia wiki,
    Element pageNode, List<Page> knownPages,
    boolean useDisambig) {
  if (pageNode == null) {
    return null;
  }
  String title = pageNode.getAttributeValue("title");
  Attribute pageIdAttr = pageNode.getAttribute("pageid");
  Integer pageId = null;
  if (pageIdAttr != null) {
    try {
      String tmp = pageIdAttr.getValue();
      pageId = Integer.valueOf(tmp);
    } catch (NumberFormatException e) {
      //
    }
  }
  String revisionId = pageNode.getAttributeValue("lastrevid");
  Page page = DataManager.getPage(wiki, title, pageId, revisionId, knownPages);
  page.setNamespace(pageNode.getAttributeValue("ns"));
  if (pageNode.getAttribute("missing") != null) {
    page.setExisting(Boolean.FALSE);
  } else if (pageId != null) {
    page.setExisting(Boolean.TRUE);
  }
  if (pageNode.getAttribute("redirect") != null) {
    page.getRedirects().isRedirect(true);
  }
  if (useDisambig) {
    Element pageProps = pageNode.getChild("pageprops");
    boolean dabPage = (pageProps != null) && (pageProps.getAttribute("disambiguation") != null);
    page.setDisambiguationPage(Boolean.valueOf(dabPage));
  }
  return page;
}
 
Example 9
Source File: JAXBWriter.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
private String getRESTProtocolVersion() throws Exception {
    InputStream in = null;
    try {
        in = StringUtil.class.getResourceAsStream("/subsonic-rest-api.xsd");
        Document document = createSAXBuilder().build(in);
        Attribute version = document.getRootElement().getAttribute("version");
        return version.getValue();
    } finally {
        FileUtil.closeQuietly(in);
    }
}
 
Example 10
Source File: JAXBWriter.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
private static String parseRESTProtocolVersion() {
    try (InputStream in = StringUtil.class.getResourceAsStream("/subsonic-rest-api.xsd")) {
        Document document = createSAXBuilder().build(in);
        Attribute version = document.getRootElement().getAttribute("version");
        return version.getValue();
    } catch (Exception x) {
        throw new RuntimeException(x);
    }
}
 
Example 11
Source File: NmasResponseSet.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ChallengeSet parseNmasUserResponseXML( final String str )
        throws IOException, JDOMException, ChaiValidationException
{
    final List<Challenge> returnList = new ArrayList<Challenge>();

    final Reader xmlreader = new StringReader( str );
    final SAXBuilder builder = new SAXBuilder();
    final Document doc = builder.build( xmlreader );

    final Element rootElement = doc.getRootElement();
    final int minRandom = StringHelper.convertStrToInt( rootElement.getAttributeValue( "RandomQuestions" ), 0 );

    final String guidValue;
    {
        final Attribute guidAttribute = rootElement.getAttribute( "GUID" );
        guidValue = guidAttribute == null ? null : guidAttribute.getValue();
    }

    for ( Iterator iter = doc.getDescendants( new ElementFilter( "Challenge" ) ); iter.hasNext(); )
    {
        final Element loopQ = ( Element ) iter.next();
        final int maxLength = StringHelper.convertStrToInt( loopQ.getAttributeValue( "MaxLength" ), 255 );
        final int minLength = StringHelper.convertStrToInt( loopQ.getAttributeValue( "MinLength" ), 2 );
        final String defineStrValue = loopQ.getAttributeValue( "Define" );
        final boolean adminDefined = "Admin".equalsIgnoreCase( defineStrValue );
        final String typeStrValue = loopQ.getAttributeValue( "Type" );
        final boolean required = "Required".equalsIgnoreCase( typeStrValue );
        final String challengeText = loopQ.getText();

        final Challenge challenge = new ChaiChallenge( required, challengeText, minLength, maxLength, adminDefined, 0, false );
        returnList.add( challenge );
    }

    return new ChaiChallengeSet( returnList, minRandom, null, guidValue );
}
 
Example 12
Source File: ApiJsonResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Get a page corresponding to a page node.
 * 
 * @param wiki Wiki.
 * @param pageNode Page node.
 * @param knownPages Already known pages.
 * @param useDisambig True if disambiguation property should be used.
 * @return Page.
 */
protected static Page getPage(
    EnumWikipedia wiki,
    Element pageNode, List<Page> knownPages,
    boolean useDisambig) {
  if (pageNode == null) {
    return null;
  }
  String title = pageNode.getAttributeValue("title");
  Attribute pageIdAttr = pageNode.getAttribute("pageid");
  Integer pageId = null;
  if (pageIdAttr != null) {
    try {
      String tmp = pageIdAttr.getValue();
      pageId = Integer.valueOf(tmp);
    } catch (NumberFormatException e) {
      //
    }
  }
  String revisionId = pageNode.getAttributeValue("lastrevid");
  Page page = DataManager.getPage(wiki, title, pageId, revisionId, knownPages);
  page.setNamespace(pageNode.getAttributeValue("ns"));
  if (pageNode.getAttribute("missing") != null) {
    page.setExisting(Boolean.FALSE);
  } else if (pageId != null) {
    page.setExisting(Boolean.TRUE);
  }
  if (pageNode.getAttribute("redirect") != null) {
    page.getRedirects().isRedirect(true);
  }
  if (useDisambig) {
    Element pageProps = pageNode.getChild("pageprops");
    boolean dabPage = (pageProps != null) && (pageProps.getAttribute("disambiguation") != null);
    page.setDisambiguationPage(Boolean.valueOf(dabPage));
  }
  return page;
}
 
Example 13
Source File: TeamModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public TeamFactory parseTeam(Attribute attr, MapFactory factory) throws InvalidXMLException {
  if (attr == null) {
    return null;
  }
  String name = attr.getValue();
  TeamFactory team = Teams.getTeam(name, factory);

  if (team == null) {
    throw new InvalidXMLException("unknown team '" + name + "'", attr);
  }
  return team;
}
 
Example 14
Source File: XMLUtils.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public static DyeColor parseDyeColor(Attribute attr) throws InvalidXMLException {
  String name = attr.getValue().replace(" ", "_").toUpperCase();
  try {
    return DyeColor.valueOf(name);
  } catch (IllegalArgumentException e) {
    throw new InvalidXMLException("Invalid dye color '" + attr.getValue() + "'", attr);
  }
}
 
Example 15
Source File: ExtractionTest.java    From emissary with Apache License 2.0 4 votes vote down vote up
protected void checkStringValue(Element meta, String data, String tname) {
    String key = meta.getChildTextTrim("name");
    String value = meta.getChildText("value");
    String matchMode = "equals";
    Attribute mm = meta.getAttribute("matchMode");

    if (value == null) {
        return; // checking the value is optional
    }

    if (mm != null) {
        matchMode = mm.getValue();
    }

    if (matchMode.equals("equals")) {
        assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not equal '" + value + "'",
                value, data);
    } else if (matchMode.equals("index")) {
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not index '" + value + "'",
                data.indexOf(value) > -1);
    } else if (matchMode.equals("match")) {
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
                data.matches(value));
    } else if (matchMode.equals("base64")) {
        // decode value as a base64 encoded byte[] array and use the string
        // representation of the byte array for comparison to the incoming value
        value = new String(DatatypeConverter.parseBase64Binary(value));
        assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
                value, data);
    } else if ("collection".equalsIgnoreCase(matchMode)) {
        Attribute separatorAttribute = meta.getAttribute("collectionSeparator");
        String separator = null != separatorAttribute ? separatorAttribute.getValue() : ","; // comma is default
        // separator
        Collection<String> expectedValues = Arrays.asList(value.split(separator));
        Collection<String> actualValues = Arrays.asList(data.split(separator));
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " did not have equal collection, value ' " + data
                + "' does not equal '" + value + "' split by separator '" + separator + "'",
                CollectionUtils.isEqualCollection(expectedValues, actualValues));

    } else {
        fail("Problematic matchMode specified for test '" + matchMode + "' on " + key + " in element " + meta.getName());
    }
}
 
Example 16
Source File: CraftingModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
public Recipe parseShapedRecipe(MapFactory factory, Element elRecipe)
    throws InvalidXMLException {
  ShapedRecipe recipe = new ShapedRecipe(parseRecipeResult(factory, elRecipe));

  Element elShape = XMLUtils.getRequiredUniqueChild(elRecipe, "shape");
  List<String> rows = new ArrayList<>(3);

  for (Element elRow : elShape.getChildren("row")) {
    String row = elRow.getTextNormalize();

    if (rows.size() >= 3) {
      throw new InvalidXMLException(
          "Shape must have no more than 3 rows (" + row + ")", elShape);
    }

    if (rows.isEmpty()) {
      if (row.length() > 3) {
        throw new InvalidXMLException(
            "Shape must have no more than 3 columns (" + row + ")", elShape);
      }
    } else if (row.length() != rows.get(0).length()) {
      throw new InvalidXMLException("All rows must be the same width", elShape);
    }

    rows.add(row);
  }

  if (rows.isEmpty()) {
    throw new InvalidXMLException("Shape must have at least one row", elShape);
  }

  recipe.shape(rows.toArray(new String[rows.size()]));
  Set<Character> keys =
      recipe
          .getIngredientMap()
          .keySet(); // All shape symbols are present and mapped to null at this point

  for (Element elIngredient : elRecipe.getChildren("ingredient")) {
    SingleMaterialMatcher item = XMLUtils.parseMaterialPattern(elIngredient);
    Attribute attrSymbol = XMLUtils.getRequiredAttribute(elIngredient, "symbol");
    String symbol = attrSymbol.getValue();

    if (symbol.length() != 1) {
      throw new InvalidXMLException(
          "Ingredient key must be a single character from the recipe shape", attrSymbol);
    }

    char key = symbol.charAt(0);
    if (!keys.contains(key)) {
      throw new InvalidXMLException(
          "Ingredient key '" + key + "' does not appear in the recipe shape", attrSymbol);
    }

    if (item.dataMatters()) {
      recipe.setIngredient(key, item.getMaterialData());
    } else {
      recipe.setIngredient(key, item.getMaterial());
    }
  }

  if (recipe.getIngredientMap().isEmpty()) {
    throw new InvalidXMLException(
        "Crafting recipe must have at least one ingredient", elRecipe);
  }

  return recipe;
}
 
Example 17
Source File: AOI.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private boolean load(final File file) {
    Document doc;
    try {
        doc = XMLSupport.LoadXML(file.getAbsolutePath());

        final Element root = doc.getRootElement();
        final Attribute nameAttrib = root.getAttribute("name");
        if (nameAttrib != null)
            this.name = nameAttrib.getValue();

        final List<GeoPos> geoPosList = new ArrayList<GeoPos>();

        final List<Content> children = root.getContent();
        for (Object aChild : children) {
            if (aChild instanceof Element) {
                final Element child = (Element) aChild;
                if (child.getName().equals("param")) {
                    inputFolder = XMLSupport.getAttrib(child, "inputFolder");
                    outputFolder = XMLSupport.getAttrib(child, "outputFolder");
                    processingGraph = XMLSupport.getAttrib(child, "graph");
                    lastProcessed = XMLSupport.getAttrib(child, "lastProcessed");
                    final Attribute findSlavesAttrib = child.getAttribute("findSlaves");
                    if (findSlavesAttrib != null)
                        findSlaves = Boolean.parseBoolean(findSlavesAttrib.getValue());
                    final Attribute maxSlavesAttrib = child.getAttribute("maxSlaves");
                    if (maxSlavesAttrib != null)
                        maxSlaves = Integer.parseInt(maxSlavesAttrib.getValue());
                } else if (child.getName().equals("points")) {
                    final List<Content> pntsList = child.getContent();
                    for (Object o : pntsList) {
                        if (o instanceof Element) {
                            final Element pntElem = (Element) o;
                            final String latStr = XMLSupport.getAttrib(pntElem, "lat");
                            final String lonStr = XMLSupport.getAttrib(pntElem, "lon");
                            if (!latStr.isEmpty() && !lonStr.isEmpty()) {
                                final float lat = Float.parseFloat(latStr);
                                final float lon = Float.parseFloat(lonStr);
                                geoPosList.add(new GeoPos(lat, lon));
                            }
                        }
                    }
                } else if (child.getName().equals(DBQuery.DB_QUERY)) {
                    slaveDBQuery = new DBQuery();
                    //todo slaveDBQuery.fromXML(child);
                }
            }
        }

        aoiPoints = geoPosList.toArray(new GeoPos[geoPosList.size()]);
    } catch (IOException e) {
        SnapApp.getDefault().handleError("Unable to load AOI", e);
        return false;
    }
    return true;
}
 
Example 18
Source File: YDecompositionParser.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
private YDecomposition createDecomposition(Element decompElem) {
    Namespace schemaInstanceNS = decompElem.getNamespace("xsi");
    String xsiType = _decompElem.getAttributeValue("type", schemaInstanceNS);
    String id = _decompElem.getAttributeValue("id");

    String elementName = _decompElem.getName();
    if ("NetFactsType".equals(xsiType) || "rootNet".equals(elementName)) {
        _decomposition = new YNet(id, _specificationParser.getSpecification());
        parseNet((YNet) _decomposition, decompElem);
    }
    else if ("WebServiceGatewayFactsType".equals(xsiType)) {
        _decomposition = new YAWLServiceGateway(id, _specificationParser.getSpecification());
        parseWebServiceGateway((YAWLServiceGateway) _decomposition, decompElem);
    }
    /**
     * AJH: Added to support XML attribute pass-thru from specification into task output data doclet.
     * Load element attributes
     */
    for (Attribute attr : decompElem.getAttributes()) {
        String attname = attr.getName();
        boolean isXsiNS = attr.getNamespace() == schemaInstanceNS;

        //don't add the standard YAWL schema attributes to the pass through list.
        if(!("id".equals(attname) || ("type".equals(attname) && isXsiNS))) {
            String value = attr.getValue();
            if (value.startsWith("dynamic{")) {
                _decomposition.setAttribute(attr.getName(),
                        new DynamicValue(value, _decomposition));
            }
            else _decomposition.setAttribute(attr.getName(), value);
        }
    }
    
    parseDecompositionRoles(_decomposition, decompElem);
    _decomposition.setLogPredicate(parseLogPredicate(decompElem, _yawlNS));

    // added for resourcing
    parseExternalInteraction(_decomposition, decompElem);
    parseCodelet(_decomposition, decompElem);

    return _decomposition;
}
 
Example 19
Source File: NmasResponseSet.java    From ldapchai with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static String readDisplayString( final Element questionElement, final Locale locale )
{

    final Namespace xmlNamespace = Namespace.getNamespace( "xml", "http://www.w3.org/XML/1998/namespace" );

    // someday ResoureBundle won't suck and this will be a 5 line method.

    // see if the node has any localized displays.
    final List displayChildren = questionElement.getChildren( "display" );

    // if no locale specified, or if no localized text is available, just use the default.
    if ( locale == null || displayChildren == null || displayChildren.size() < 1 )
    {
        return questionElement.getText();
    }

    // convert the xml 'display' elements to a map of locales/strings
    final Map<Locale, String> localizedStringMap = new HashMap<Locale, String>();
    for ( final Object loopDisplayChild : displayChildren )
    {
        final Element loopDisplay = ( Element ) loopDisplayChild;
        final Attribute localeAttr = loopDisplay.getAttribute( "lang", xmlNamespace );
        if ( localeAttr != null )
        {
            final String localeStr = localeAttr.getValue();
            final String displayStr = loopDisplay.getText();
            final Locale localeKey = parseLocaleString( localeStr );
            localizedStringMap.put( localeKey, displayStr );
        }
    }

    final Locale matchedLocale = localeResolver( locale, localizedStringMap.keySet() );

    if ( matchedLocale != null )
    {
        return localizedStringMap.get( matchedLocale );
    }

    // none found, so just return the default string.
    return questionElement.getText();
}
 
Example 20
Source File: DDSXMLParser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Arrays have special parsing need as their syntax is different from
 * that of a typical BaseType derived type or a container type. The
 * array is based on a template variable that can have ANY structure
 * that can be represented by the OPeNDAP data model. With the exception
 * of (you knew this was comming, right?) of other arrays. IE You can't
 * have Arrays of Arrays. This caveat is enforced by the XML schema.
 */
private void parseArray(Element ArrayElement, DArray da, String indent)
    throws DASException, NoSuchTypeException, BadSemanticsException {

  int countTemplateVars = 0;
  int numDims = 0;


  for (Element e : ArrayElement.getChildren()) {

    if (_Debug)
      System.out.println(indent + "Working on Array element: " + e.getName());

    // Is this element an Attribute of the Array?
    if (e.getName().equals("Attribute")) {
      // Then ignore it!
    }
    // Is this element an Attribute of the Alias?
    else if (e.getName().equals("Alias")) {
      // Then ignore it!
    }
    // Is this element an array dimension?
    else if (e.getName().equals("dimension")) {

      // Then count it,
      numDims++;

      // And now let's add it to the array...

      // Array dimension are not required to have names, so
      // the schema does not enforce the use of the name attribute.

      // try to get the dimension's name, and use it id it's there.
      String name = null;
      Attribute nameAttr = e.getAttribute("name");

      if (nameAttr != null)
        name = nameAttr.getValue();

      // The presence of the 'size' attribute is enforeced by the schema.
      // get it, parse it, use it.
      int size = Integer.parseInt(e.getAttribute("size").getValue());

      // add the dimension to the array.
      da.appendDim(size, (name));
    } else { // otherwise, it must be THE template element.

      // Just to make sure the schema validation didn't fail (because
      // I am basically paranoid about software) count the number of
      // template candidates we find and throw an Exception later
      // if there was more than one.
      countTemplateVars++;

      // The template element is just another BaseType
      // derived element. So, let's go build it!
      BaseType template = buildArrayTemplate(e, indent);

      // Oddly, in the OPeNDAP implementation of Array, the Array variable
      // takes it's name from it's (internal) template variable. This
      // is probably an artifact of the original DDSParser.

      // So, set the name of the template variable to the name of the Array.
      template.setClearName(da.getClearName());

      // Add the template variable to the Array
      da.addVariable(template);

    }
  }

  if (_Debug) {
    System.out.println(indent + "Built Array: ");
    da.printDecl(System.out, indent);
    System.out.println(indent + "dimensions: " + numDims + "  templates: " + countTemplateVars);
  }


  if (countTemplateVars != 1) {
    throw new NoSuchTypeException("ONLY ONE (1) TEMPLATE VARIABLE ALLOWED PER ARRAY!");
  }

}