Example #1
1
  /**
   * Reads the payload of a tag, given the name and type.
   *
   * @param type The type.
   * @param name The name.
   * @param depth The depth.
   * @return The tag.
   * @throws IOException if an I/O error occurs.
   */
  private Tag readTagPayload(int type, String name, int depth) throws IOException {
    switch (type) {
      case NBTConstants.TYPE_END:
        if (depth == 0) {
          throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
        } else {
          return new EndTag();
        }
      case NBTConstants.TYPE_BYTE:
        return new ByteTag(name, is.readByte());
      case NBTConstants.TYPE_SHORT:
        return new ShortTag(name, is.readShort());
      case NBTConstants.TYPE_INT:
        return new IntTag(name, is.readInt());
      case NBTConstants.TYPE_LONG:
        return new LongTag(name, is.readLong());
      case NBTConstants.TYPE_FLOAT:
        return new FloatTag(name, is.readFloat());
      case NBTConstants.TYPE_DOUBLE:
        return new DoubleTag(name, is.readDouble());
      case NBTConstants.TYPE_BYTE_ARRAY:
        int length = is.readInt();
        byte[] bytes = new byte[length];
        is.readFully(bytes);
        return new ByteArrayTag(name, bytes);
      case NBTConstants.TYPE_STRING:
        length = is.readShort();
        bytes = new byte[length];
        is.readFully(bytes);
        return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
      case NBTConstants.TYPE_LIST:
        int childType = is.readByte();
        length = is.readInt();

        List<Tag> tagList = new ArrayList<Tag>();
        for (int i = 0; i < length; i++) {
          Tag tag = readTagPayload(childType, "", depth + 1);
          if (tag instanceof EndTag) {
            throw new IOException("TAG_End not permitted in a list.");
          }
          tagList.add(tag);
        }

        return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
      case NBTConstants.TYPE_COMPOUND:
        Map<String, Tag> tagMap = new HashMap<String, Tag>();
        while (true) {
          Tag tag = readTag(depth + 1);
          if (tag instanceof EndTag) {
            break;
          } else {
            tagMap.put(tag.getName(), tag);
          }
        }

        return new CompoundTag(name, tagMap);
      default:
        throw new IOException("Invalid tag type: " + type + ".");
    }
  }
Example #2
0
 /** {@inheritDoc} */
 public Content getTagletOutput(Tag tag, TagletWriter writer) {
   ArrayList inlineTags = new ArrayList();
   inlineTags.add(new TextTag(tag.holder(), "<b>"));
   inlineTags.addAll(Arrays.asList(tag.inlineTags()));
   inlineTags.add(new TextTag(tag.holder(), "</b>"));
   return writer.commentTagsToOutput(tag, (Tag[]) inlineTags.toArray(new Tag[] {}));
 }
  private void processContentTag(String tagName, int startLine, int cursorStart, boolean emptyTag)
      throws TemplateParseException {
    if (_ignoring)
      templateParseProblem(
          Tapestry.format(
              "TemplateParser.content-block-may-not-be-ignored",
              tagName,
              Integer.toString(startLine)),
          new Location(_resourceLocation, startLine),
          startLine,
          cursorStart);

    if (emptyTag)
      templateParseProblem(
          Tapestry.format(
              "TemplateParser.content-block-may-not-be-empty",
              tagName,
              Integer.toString(startLine)),
          new Location(_resourceLocation, startLine),
          startLine,
          cursorStart);

    _tokens.clear();
    _blockStart = -1;

    Tag tag = new Tag(tagName, startLine);

    tag._mustBalance = true;
    tag._content = true;

    _stack.clear();
    _stack.add(tag);

    advance();
  }
Example #4
0
 /**
  * Translate a delimted list of tag names to a delimited list of correponding local tagIds
  *
  * @throws ServiceException
  */
 public String localTagsFromNames(String tagNames, String inDelim, String outDelim)
     throws ServiceException {
   if (tagNames != null && tagNames.length() > 0) {
     StringBuilder sb = new StringBuilder();
     String[] names = tagNames.split(inDelim);
     for (String name : names) {
       if (name.trim().length() <= 0) {
         continue;
       }
       Integer tagId = localIdsByName.get(name);
       if (tagId == null) {
         try {
           Tag tag = mbox.getTagByName(null, name);
           tagId = tag.getId();
           localIdsByName.put(name, tagId);
         } catch (MailServiceException mse) {
           if (MailServiceException.NO_SUCH_TAG.equals(mse.getCode())) {
             OfflineLog.offline.debug(
                 "message has tag [" + name + "] which is not visible locally");
             continue;
           } else {
             throw mse;
           }
         }
       }
       sb.append(tagId).append(outDelim);
     }
     if (sb.length() >= outDelim.length()) {
       sb.setLength(sb.length() - outDelim.length());
     }
     return sb.toString();
   } else {
     return tagNames;
   }
 }
  /**
   * Perform the action of the plugin.
   *
   * @param document the current document.
   */
  public boolean perform(Document document) throws IOException {
    // Interact with the user to get the layer tag/

    Tag layerTag = getLayerTagFromUser(document);
    if (layerTag == null) return false; // User cancled.
    Tag endTag = new Tag(layerTag.getName(), false);
    // Get the output stream to hold the new document text.
    PrintWriter out = new PrintWriter(document.getOutput());
    // Create a lexical stream to tokenize the old document text.
    LexicalStream in = new LexicalStream(new SelectedHTMLReader(document.getInput(), out));
    for (; ; ) {
      // Get the next token of the document.
      Token token = in.next();
      if (token == null) break; //  Null means we've finished the document.
      else if (token instanceof Comment) {
        Comment comment = (Comment) token;
        if (comment.isSelectionStart()) {
          out.print(layerTag);
        } else if (comment.isSelectionEnd()) {
          out.print(comment);
          out.print(endTag);
          continue; // So comment isn't printed twice.
        }
      }
      out.print(token);
    }
    out.close();
    return true;
  }
Example #6
0
 private String[] determineQName(Tag tag) {
   TagAttribute attr = tag.getAttributes().get("jsfc");
   if (attr != null) {
     if (log.isLoggable(Level.FINE)) {
       log.fine(attr + " JSF Facelet Compile Directive Found");
     }
     String value = attr.getValue();
     String namespace, localName;
     int c = value.indexOf(':');
     if (c == -1) {
       namespace = this.namespaceManager.getNamespace("");
       localName = value;
     } else {
       String prefix = value.substring(0, c);
       namespace = this.namespaceManager.getNamespace(prefix);
       if (namespace == null) {
         throw new TagAttributeException(tag, attr, "No Namespace matched for: " + prefix);
       }
       localName = value.substring(c + 1);
     }
     return new String[] {namespace, localName};
   } else {
     return new String[] {tag.getNamespace(), tag.getLocalName()};
   }
 }
Example #7
0
  public HttpServletRequest addtagurl(HttpServletRequest req, HttpServletResponse response)
      throws SQLException {
    User user = User.getInstance();
    if (user == null) {
      this.parent.redirect("login", true);
      return req;
    } else {

      String uri = (String) req.getParameter("url");
      String listTag = (String) req.getParameter("list");
      Url url = user.getUrlById(Integer.valueOf(uri));
      String str[] = listTag.split("@");
      for (int i = 0; i < str.length; i++) {
        Tag tag = user.getTagByName(str[i]);
        if (tag == null) {
          // add tag
          tag = new Tag(str[i], user.getuId());
          tag.addTagtoBDD();
          tag.setTid(tag.getTagIdFromBDD());
          user.addOneTag(tag);
        }
        if (!url.hasTag(tag)) {
          TagMap tm = new TagMap(tag, url);
          tm.addTagMaptoBDD(user.getuId());
          tm.setTmId(tm.getIdFromBdd());
          user.addOneMap(tm);
        }
      }
      return req;
    }
  }
  public List<Tag> getTagsOfType(TagType type) {
    List<Tag> typedTags = new ArrayList<Tag>();

    for (Tag tag : allTags) if (tag.getType().equals(type)) typedTags.add(tag);

    return Collections.unmodifiableList(typedTags);
  }
 void load(DataInput dis) throws IOException {
   tags.clear();
   Tag tag;
   while ((tag = Tag.readNamedTag(dis)).getId() != Tag.TAG_End) {
     tags.put(tag.getName(), tag);
   }
 }
Example #10
0
 @Test
 public void testCreateTag() throws FOMException, JSONException, FluidException, IOException {
   // Lets create a tag underneath the user's default root namespace
   Namespace testNamespace = new Namespace(this.fdb, "", this.fdb.getUsername());
   String newName = UUID.randomUUID().toString();
   Tag newTag = testNamespace.createTag(newName, "This is a test tag", true);
   // if we successfully created a tag there'll be an id
   assertEquals(true, newTag.getId().length() > 0);
   testNamespace.getItem(); // not really needed
   assertEquals(true, TestUtils.contains(testNamespace.getTagNames(), newName));
   newTag.delete();
   testNamespace.getItem();
   assertEquals(false, TestUtils.contains(testNamespace.getTagNames(), newName));
   // Lets make sure validation works correctly...
   newName = "this is wrong"; // e.g. space is an invalid character
   String msg = "";
   try {
     newTag = testNamespace.createTag(newName, "This is a test namespace", false);
   } catch (FOMException ex) {
     msg = ex.getMessage();
   }
   assertEquals("Invalid name (incorrect characters or too long)", msg);
   // the new name is too long
   newName =
       "foobarbazhamandeggscheeseandpicklespamspamspamspamfoobarbazhamandeggscheeseandpicklespamspamspamspamfoobarbazhamandeggscheeseandpicklespamspamspamspamfoobarbazhamandeggscheeseandpicklespamspamspamspamfoobarbazhamandeggscheeseandpicklespamspamspamspam";
   msg = "";
   try {
     newTag = testNamespace.createTag(newName, "This is a test namespace", false);
   } catch (FOMException ex) {
     msg = ex.getMessage();
   }
   assertEquals("Invalid name (incorrect characters or too long)", msg);
 }
Example #11
0
  // getInstance//////////////////////////////////////////////////////////////////////////////////////
  public static synchronized RecordManager getInstance(Context context) {
    if (RECORDS == null
        || TAGS == null
        || TAG_NAMES == null
        || SUM == null
        || recordManager == null) {
      SUM = 0;
      RECORDS = new LinkedList<>();
      TAGS = new LinkedList<>();
      TAG_NAMES = new HashMap<>();
      recordManager = new RecordManager(context);

      db.getData();

      if (BuildConfig.DEBUG) {
        if (BuildConfig.DEBUG) Log.d("CoCoin", "Load " + RECORDS.size() + " records S");
        if (BuildConfig.DEBUG) Log.d("CoCoin", "Load " + TAGS.size() + " tags S");
      }

      TAGS.add(0, new Tag(-1, "Sum Histogram", -4));
      TAGS.add(0, new Tag(-2, "Sum Pie", -5));

      for (Tag tag : TAGS) TAG_NAMES.put(tag.getId(), tag.getName());

      sortTAGS();
    }
    return recordManager;
  }
Example #12
0
 public static int deleteTag(int id) {
   int deletedId = -1;
   if (BuildConfig.DEBUG)
     Log.d(
         "CoCoin",
         "Manager: Delete tag: " + "Tag(id = " + id + ", deletedId = " + deletedId + ")");
   boolean tagReference = false;
   for (CoCoinRecord coCoinRecord : RECORDS) {
     if (coCoinRecord.getTag() == id) {
       tagReference = true;
       break;
     }
   }
   if (tagReference) {
     return DELETE_TAG_ERROR_TAG_REFERENCE;
   }
   deletedId = db.deleteTag(id);
   if (deletedId == -1) {
     if (BuildConfig.DEBUG) Log.d("CoCoin", "Delete the above tag FAIL!");
     return DELETE_TAG_ERROR_DATABASE_ERROR;
   } else {
     if (BuildConfig.DEBUG) Log.d("CoCoin", "Delete the above tag SUCCESSFULLY!");
     for (Tag tag : TAGS) {
       if (tag.getId() == deletedId) {
         TAGS.remove(tag);
         break;
       }
     }
     TAG_NAMES.remove(id);
     sortTAGS();
   }
   return deletedId;
 }
Example #13
0
  public Tag unmarshall(JsonUnmarshallerContext context) throws Exception {
    Tag tag = new Tag();

    int originalDepth = context.getCurrentDepth();
    String currentParentElement = context.getCurrentParentElement();
    int targetDepth = originalDepth + 1;

    JsonToken token = context.getCurrentToken();
    if (token == null) token = context.nextToken();
    if (token == VALUE_NULL) return null;

    while (true) {
      if (token == null) break;

      if (token == FIELD_NAME || token == START_OBJECT) {
        if (context.testExpression("Key", targetDepth)) {
          context.nextToken();
          tag.setKey(context.getUnmarshaller(String.class).unmarshall(context));
        }
        if (context.testExpression("Value", targetDepth)) {
          context.nextToken();
          tag.setValue(context.getUnmarshaller(String.class).unmarshall(context));
        }
      } else if (token == END_ARRAY || token == END_OBJECT) {
        if (context.getLastParsedParentElement() == null
            || context.getLastParsedParentElement().equals(currentParentElement)) {
          if (context.getCurrentDepth() <= originalDepth) break;
        }
      }
      token = context.nextToken();
    }

    return tag;
  }
Example #14
0
  public ArrayList<Tag> Get_Tags() {
    try {
      SQLiteDatabase db = this.getReadableDatabase();
      SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
      builder.setTables(NotesContract.Tag.FTS_TABLE_NAME);

      String[] projection = NotesContract.Tag.getTagColumns();

      Cursor cur = builder.query(db, projection, null, null, null, null, null, null);

      if (cur != null) {
        cur.moveToFirst();
        do {
          Tag tag = new Tag();
          tag.setTagId(Integer.valueOf(cur.getString(1)));
          tag.setTagName(cur.getString(2));
          // add tag to list
          tags_list.add(tag);
        } while (cur.moveToNext());
      }
      cur.close();
      return tags_list;
    } catch (Exception e) {
      Log.e("SELECT All tags", " " + e);
    }
    return tags_list;
  }
Example #15
0
  /**
   * Write all the blocks in a Tag to the Mifare tag.
   *
   * @param t
   * @throws IOException
   */
  public void write(Tag t) throws IOException {

    if (t.getSectorCount() > mKeys.getSectorCount()) throw new IOException("Too few keys");

    mTag.connect();

    int sectors = mTag.getSectorCount();

    try {

      for (int s = 0; s < sectors; ++s) {

        // Authenticate for each sector (try B key, then A key)
        if (!mTag.authenticateSectorWithKeyB(s, mKeys.getKeyB(s))
            && !mTag.authenticateSectorWithKeyA(s, mKeys.getKeyA(s)))
          throw new IOException("Auth error");

        // Write to tag. Skip block 0 and the trailer of each sector
        int blockOffset = mTag.sectorToBlock(s);
        int lastBlock = blockOffset + mTag.getBlockCountInSector(s);

        // Skip block 0
        blockOffset = blockOffset == 0 ? 1 : blockOffset;

        for (int b = blockOffset; b < lastBlock; ++b) {
          mTag.writeBlock(b, t.getBlock(b));
          if (mProgressListener != null)
            mProgressListener.publishProgress((100 * b) / t.getBlockCount());
        }
      }
    } finally {
      mTag.close();
    }
  }
Example #16
0
  /**
   * Writes all exemplar of this tag and all his nodes recursively to files. One file to exemplar
   * (exemplar is text, representing tag with attribute - fn, replaced by fn value)
   *
   * @param tag - written tag
   */
  public void writeAllXml(Tag tag, String prefix, boolean toOutStream) {
    // initialise path in begin of export
    path = new ArrayList<>();
    XMLStreamWriter current;
    int n = tag.attrSizes();
    String extension = tag.getName();

    // if tag size > m, _trim it_
    if (limit >= 0 && limit < n) {
      n = limit;
    }

    // if tag size > WARNING_QUANTITY, ask user.
    // This tag is root tag of export, so quantity of files equals to its size
    if (n > WARNING_QUANTITY) {
      System.out.println("Write " + n + " files? y/n");
      try {
        int yn = System.in.read();
        if (yn != yCharCode) {
          System.out.println("Writing canceled\n Exit");
          System.exit(0);
        }
      } catch (IOException e) {
        Util.handleException(e);
      }
    }

    // if must be one file, export it
    if (n <= 1) {
      // if to out, print
      if (toOutStream) {
        writeExemplarXML(getXmlStreamWriter(null), tag, 0, 0);
      } else {
        // if to file, export
        current = getXmlStreamWriter(prefix + "." + extension);
        writeExemplarXML(current, tag, 0, 0);
        writeVersion(current);
      }
      // if files many,
    } else {
      // if to out,print all
      if (toOutStream) {
        for (int i = 0; i < n; i++) {
          writeExemplarXML(getXmlStreamWriter(null), tag, i, 0);
        }
      } else {
        // if to files, export all appended with __[№]
        for (int i = 0; i < n; i++) {
          current =
              getXmlStreamWriter(
                  prefix + "__(" + tag.getNameWithAttr(i).replace(" ", "_") + ")." + extension);
          writeExemplarXML(current, tag, i, 0);
          writeVersion(current);
        }
      }
    }

    // delete path in end of exort
    path = null;
  }
Example #17
0
  @Override
  public String toString() {
    final StringWriter writer = new StringWriter();
    final TableAppender tablewriter = new TableAppender(writer);

    tablewriter.appendHorizontalSeparator();
    tablewriter.append("OSM-RELATION\t \n");
    tablewriter.appendHorizontalSeparator();
    tablewriter.append("members count\t" + members.size() + "\n");
    for (int i = 0; i < members.size(); i++) {
      tablewriter.append("member " + i + "\t" + members.get(i) + "\n");
    }
    tablewriter.appendHorizontalSeparator();
    tablewriter.append("ID\t" + getId() + "\n");
    tablewriter.append("ChangeSet\t" + getChangeset() + "\n");
    tablewriter.append("User\t" + getUser() + "\n");
    tablewriter.append("TimeStamp\t" + new Date(getTimestamp()) + "\n");
    tablewriter.append("version\t" + getVersion() + "\n");
    tablewriter.appendHorizontalSeparator();
    for (Tag t : getTags()) {
      tablewriter.append(t.getK() + "\t" + t.getV() + "\n");
    }
    tablewriter.appendHorizontalSeparator();

    try {
      tablewriter.flush();
      writer.flush();
    } catch (IOException ex) {
      // will never happen is this case
      ex.printStackTrace();
    }

    return writer.getBuffer().toString();
  }
Example #18
0
  /**
   * Fonction tableauBord Gere la page tableau de bord de l'application
   *
   * @param req : HttpServletRequest
   */
  public HttpServletRequest tableaubord(HttpServletRequest req, HttpServletResponse response) {
    User user = User.getInstance();
    if (user == null) {
      this.parent.redirect("login", true);
      return req;
    } else {
      List<Tag> tags = user.getAllTag();
      int nbTags = tags.size();
      List<Url> urls = user.getAllUrl();
      int nbUrls = urls.size();
      List<Url> untaggedUrls = user.getUntaggedUrl();
      int nbUntaggedUrls = untaggedUrls.size();
      Map<Tag, List<Url>> mapTagUrls = new HashMap<Tag, List<Url>>();

      if (tags != null) {
        Iterator<Tag> it = tags.iterator();
        while (it.hasNext()) {
          Tag tag = it.next();
          mapTagUrls.put(tag, tag.getUrls());
        }
      }
      req.setAttribute("tags", tags);
      req.setAttribute("urls", urls);
      req.setAttribute("untaggedurls", untaggedUrls);
      req.setAttribute("mapTagUrls", mapTagUrls);
      req.setAttribute("nbTags", nbTags);
      req.setAttribute("nbUrls", nbUrls);
      req.setAttribute("nbUntaggedUrls", nbUntaggedUrls);
      return req;
    }
  }
Example #19
0
  public static List<String> extractAlbumId() throws MalformedURLException, IOException {
    Tag tag = new Tag();
    String result = null;
    String url = null;
    List<String> albumIdList = new ArrayList<String>();
    List<String> albumUrlList = new ArrayList<String>();
    String albumIdArray[];
    String albumId;

    for (String getTag : tag.getList()) {
      getTag = URLEncoder.encode(URLEncoder.encode(getTag, "utf-8"), "utf-8");
      url =
          "http://www.melon.com/cds/openalbum/web/oalbumsearch_list.htm?section=title&query="
              + getTag
              + "&pageLink=othersearch";
      albumUrlList.add(url);
    }

    for (String resultUrl : albumUrlList) {
      Source source = new Source(new URL(resultUrl));
      List<Element> elementList = source.getAllElementsByClass("album");
      for (Element element : elementList) {
        result = element.getAllElements(HTMLElementName.A).get(0).toString();
        albumIdArray = result.split("'");
        albumId = albumIdArray[1];
        albumIdList.add(albumId);
      }
    }

    return albumIdList;
  }
Example #20
0
  public HttpServletRequest tagbyid(HttpServletRequest req, HttpServletResponse response) {
    User user = User.getInstance();
    if (user == null) {
      this.parent.redirect("login", true);
      return req;
    } else {

      String id = req.getParameter("id");
      List<Tag> tags = user.getAllTag();
      int nbTags = tags.size();
      List<Url> urls = user.getAllUrl();
      int nbUrls = urls.size();
      List<Url> untaggedUrls = user.getUntaggedUrl();
      int nbUntaggedUrls = untaggedUrls.size();
      Tag tag = user.getTagById(Integer.valueOf(id));
      List<Url> listUrls = tag.getUrls();

      req.setAttribute("tag", tag);
      req.setAttribute("nbTags", nbTags);
      req.setAttribute("nbUrls", nbUrls);
      req.setAttribute("nbUntaggedUrls", nbUntaggedUrls);
      req.setAttribute("listUrls", listUrls);
      return req;
    }
  }
 @Override
 public void createOriginalData() {
   super.createOriginalData();
   for (Tag subTag : subTags) {
     subTag.createOriginalData();
   }
 }
Example #22
0
 private Tag trimNSAttributes(Tag tag) {
   TagAttribute[] attr = (TagAttribute[]) tag.getAttributes().getAll();
   int remove = 0;
   for (int i = 0; i < attr.length; i++) {
     if (attr[i].getQName().startsWith("xmlns")
         && this.tagLibrary.containsNamespace(attr[i].getValue(), null)) {
       remove |= 1 << i;
       if (log.isLoggable(Level.FINE)) {
         log.fine(attr[i] + " Namespace Bound to TagLibrary");
       }
     }
   }
   if (remove == 0) {
     return tag;
   } else {
     List attrList = new ArrayList(attr.length);
     int p = 0;
     for (int i = 0; i < attr.length; i++) {
       p = 1 << i;
       if ((p & remove) == p) {
         continue;
       }
       attrList.add(attr[i]);
     }
     attr = (TagAttribute[]) attrList.toArray(new TagAttribute[attrList.size()]);
     return new Tag(
         tag.getLocation(),
         tag.getNamespace(),
         tag.getLocalName(),
         tag.getQName(),
         new TagAttributesImpl(attr));
   }
 }
  public Tag unmarshall(StaxUnmarshallerContext context) throws Exception {
    Tag tag = new Tag();
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) targetDepth += 1;

    while (true) {
      XMLEvent xmlEvent = context.nextEvent();
      if (xmlEvent.isEndDocument()) return tag;

      if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

        if (context.testExpression("key", targetDepth)) {
          tag.setKey(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }

        if (context.testExpression("value", targetDepth)) {
          tag.setValue(StringStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }
      } else if (xmlEvent.isEndElement()) {
        if (context.getCurrentDepth() < originalDepth) {
          return tag;
        }
      }
    }
  }
Example #24
0
 /**
  * Attaches an object as mixin to this entity.
  *
  * <p>More specifically, a given, {@link Mixin}-annotated object is registered with this entity to
  * be available with its attributes and actions.
  *
  * <p>During attachment, several semantic checks are done:
  *
  * <ol>
  *   <li>the object carries a {@link Mixin} annotation,
  *   <li>the object carries a {@link Category} annotation, and
  *   <li>this entity supports the provided mixin as indicated by its {@link Attaches} annotation.
  * </ol>
  *
  * If either of the former are missing, or the latter is indicated, an exception is thrown.
  *
  * @param o The object to be attached as a mixin to this entity.
  * @throws InvalidMixinException if the provided object is missing either {@link Mixin} or {@link
  *     Category} annotations.
  * @throws UnsupportedMixinException if the provided object's class is not listed in this entity's
  *     {@link Attaches} annotation.
  */
 public final void attachMixin(Object o) throws InvalidMixinException, UnsupportedMixinException {
   /*
    * Check whether the examined object is annotated properly.
    */
   if (o.getClass().isAnnotationPresent(Mixin.class)) {
     /*
      * yes: Check whether the provided mixin is supported by this resource type.
      */
     if (this.supportsMixin(o.getClass())) {
       /*
        * yes: Add to list of attached mixins and notify subclasses.
        */
       String key = null;
       if (o instanceof Tag) {
         Tag t = (Tag) o;
         key = new StringBuilder().append(t.getScheme()).append(t.getTerm()).toString();
       } else {
         if (o.getClass().isAnnotationPresent(Category.class)) {
           Category c = o.getClass().getAnnotation(Category.class);
           key = new StringBuilder().append(c.scheme()).append(c.term()).toString();
         } else {
           String message =
               new StringBuilder("mixin not usable: '@Category' annotation missing on \"")
                   .append(o.getClass().getName())
                   .append("\".")
                   .toString();
           throw new InvalidMixinException(message);
         }
       }
       this.mixins.put(key, o);
     } // if
     else {
       /*
        * no: throw an exception denoting that the provided mixin is not supported.
        */
       Category category = o.getClass().getAnnotation(Category.class);
       String message =
           new StringBuilder("not supported: '")
               .append(this.getClass().getName())
               .append("' cannot attach mixins of category \"")
               .append(category.scheme())
               .append(category.term())
               .append("\".")
               .toString();
       throw new UnsupportedMixinException(message);
     } // else
   } // if
   else {
     /*
      * no: throw an exception denoting that the provided object is no mixin.
      */
     String message =
         new StringBuilder("not a mixin: '@Mixin' annotations missing on \"")
             .append(o.getClass().getName())
             .append("\".")
             .toString();
     throw new InvalidMixinException(message);
   } // else
 }
Example #25
0
 static {
   final Map<String, Tag> map = new HashMap<String, Tag>();
   for (Tag element : values()) {
     final String name = element.getLocalName();
     if (name != null) map.put(name, element);
   }
   MAP = map;
 }
Example #26
0
 /** Returns a map containing a copy of the tags in this list. */
 @Override
 public Map<String, String> asMap() {
   Map<String, String> stringMap = new HashMap<String, String>(size());
   for (Tag t : tagSortedMap.values()) {
     stringMap.put(t.getKey(), t.getValue());
   }
   return stringMap;
 }
Example #27
0
 private void writeEndTag(Tag t) {
   if (!t.end) {
     int indent = t.depth;
     write(indent(indent, t.name));
     write("</" + t.getQualifiedName() + ">");
     t.end = true;
   }
 }
Example #28
0
 public static boolean isTag(String Name) {
   for (Tag tag : PiritaProtect.Plugin.Tags) {
     if (tag.getName().equalsIgnoreCase(Name)) {
       return true;
     }
   }
   return false;
 }
Example #29
0
 public static boolean isTagAndValue(String Name, String Value) {
   for (Tag tag : PiritaProtect.Plugin.Tags) {
     if (tag.getName().equalsIgnoreCase(Name) && tag.getValues().contains(Value.toLowerCase())) {
       return true;
     }
   }
   return false;
 }
 /**
  * Whether current event matches any tag from {@link #tags}.
  *
  * @param event AuditEvent to test match on {@link #tags}.
  * @return true if event matches any tag from {@link #tags}, false otherwise.
  */
 private boolean matchesTag(AuditEvent event) {
   for (final Tag tag : tags) {
     if (tag.isMatch(event)) {
       return true;
     }
   }
   return false;
 }