/*    public static Entry ToPackageEntry(PackageItem p, UriInfo uriInfo) {
      UriBuilder base;
      if(p.isHistoricalVersion()) {
          base = uriInfo.getBaseUriBuilder().path("packages").path(p.getName()).path("versions").path(Long.toString(p.getVersionNumber()));
      } else {
          base = uriInfo.getBaseUriBuilder().path("packages").path(p.getName());
      }

      //NOTE: Entry extension is not supported in RESTEasy. We need to either use Abdera or get extension
      //supported in RESTEasy
      //PackageMetadata metadata = new PackageMetadata();
      //metadata.setUuid(p.getUUID());
      //metadata.setCreated(p.getCreatedDate().getTime());
      //metadata.setLastModified(p.getLastModified().getTime());
      //metadata.setLastContributor(p.getLastContributor());
      //c.setJAXBObject(metadata);

      Entry e =new Entry();
      e.setTitle(p.getTitle());
      e.setSummary(p.getDescription());
      e.setPublished(new Date(p.getLastModified().getTimeInMillis()));
      e.setBase(base.clone().build());

      e.setId(base.clone().build());

      Iterator<AssetItem> i = p.getAssets();
      while (i.hasNext()) {
          AssetItem item = i.next();
          Link link = new Link();
          link.setHref((base.clone().path("assets").path(item.getName())).build());
          link.setTitle(item.getTitle());
          link.setRel("asset");
          e.getLinks().add(link);
      }

      Content c = new Content();
      c.setType(MediaType.APPLICATION_OCTET_STREAM_TYPE);
      c.setSrc(base.clone().path("binary").build());
      e.setContent(c);

      return e;
  }*/
  public static Entry toAssetEntryAbdera(AssetItem a, UriInfo uriInfo) {
    URI baseURL;
    if (a.isHistoricalVersion()) {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/assets/{assetName}/versions/{version}")
              .build(a.getModuleName(), a.getName(), Long.toString(a.getVersionNumber()));
    } else {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/assets/{assetName}")
              .build(a.getModuleName(), a.getName());
    }

    Factory factory = Abdera.getNewFactory();

    org.apache.abdera.model.Entry e = factory.getAbdera().newEntry();
    e.setTitle(a.getTitle());
    e.setSummary(a.getDescription());
    e.setPublished(new Date(a.getLastModified().getTimeInMillis()));
    e.setBaseUri(baseURL.toString());
    e.addAuthor(a.getLastContributor());

    e.setId(baseURL.toString());

    // generate meta data
    ExtensibleElement extension = e.addExtension(METADATA);
    ExtensibleElement childExtension = extension.addExtension(ARCHIVED);
    // childExtension.setAttributeValue("type", ArtifactsRepository.METADATA_TYPE_STRING);
    childExtension.addSimpleExtension(VALUE, a.isArchived() ? "true" : "false");

    childExtension = extension.addExtension(UUID);
    childExtension.addSimpleExtension(VALUE, a.getUUID());

    childExtension = extension.addExtension(STATE);
    childExtension.addSimpleExtension(VALUE, a.getState() == null ? "" : a.getState().getName());

    childExtension = extension.addExtension(FORMAT);
    childExtension.addSimpleExtension(VALUE, a.getFormat());

    childExtension = extension.addExtension(VERSION_NUMBER);
    childExtension.addSimpleExtension(VALUE, String.valueOf(a.getVersionNumber()));

    childExtension = extension.addExtension(CHECKIN_COMMENT);
    childExtension.addSimpleExtension(VALUE, a.getCheckinComment());

    List<CategoryItem> categories = a.getCategories();
    childExtension = extension.addExtension(CATEGORIES);
    for (CategoryItem c : categories) {
      childExtension.addSimpleExtension(VALUE, c.getName());
    }

    org.apache.abdera.model.Content content = factory.newContent();
    content.setSrc(UriBuilder.fromUri(baseURL).path("binary").build().toString());
    content.setMimeType("application/octet-stream");
    content.setContentType(Type.MEDIA);
    e.setContentElement(content);

    return e;
  }
  public static void main(String[] args) throws Exception {

    Abdera abdera = new Abdera();
    AbderaClient abderaClient = new AbderaClient(abdera);
    Factory factory = abdera.getFactory();

    // Perform introspection. This is an optional step. If you already
    // know the URI of the APP collection to POST to, you can skip it.
    Document<Service> introspection =
        abderaClient.get("http://localhost:9080/EmployeeService/").getDocument();
    Service service = introspection.getRoot();
    Collection collection =
        service.getCollection("Employee Directory Workspace", "itc Employee Database");
    report("The Collection Element", collection.toString());

    // Create the entry to post to the collection
    Entry entry = factory.newEntry();
    entry.setId("tag:example.org,2006:foo");
    entry.setTitle("This is the title");
    entry.setUpdated(new AtomDate().getValue());
    entry.setPublished(new AtomDate().getValue());
    entry.addLink("/employee");
    entry.addAuthor("James");
    entry.setContent("This is the content");
    report("The Entry to Post", entry.toString());

    // Post the entry. Be sure to grab the resolved HREF of the collection
    Document<Entry> doc =
        abderaClient.post(collection.getResolvedHref().toString(), entry).getDocument();

    // In some implementations (such as Google's GData API, the entry URI is
    // distinct from it's edit URI. To be safe, we should assume it may be
    // different
    IRI entryUri = doc.getBaseUri();
    report("The Created Entry", doc.getRoot().toString());

    // Grab the Edit URI from the entry. The entry MAY have more than one
    // edit link. We need to make sure we grab the right one.
    IRI editUri = getEditUri(doc.getRoot());

    // If there is an Edit Link, we can edit the entry
    if (editUri != null) {
      // Before we can edit, we need to grab an "editable" representation
      doc = abderaClient.get(editUri.toString()).getDocument();

      // Change whatever you want in the retrieved entry
      // doc.getRoot().getTitleElement().setValue("This is the changed title");

      // Put it back to the server
      abderaClient.put(editUri.toString(), doc.getRoot());

      // This is just to show that the entry has been modified
      doc = abderaClient.get(entryUri.toString()).getDocument();
      report("The Modified Entry", doc.getRoot().toString());
    } else {
      // Otherwise, the entry cannot be modified (no suitable edit link was found)
      report("The Entry cannot be modified", null);
    }

    // Delete the entry. Again, we need to make sure that we have the current
    // edit link for the entry
    doc = abderaClient.get(entryUri.toString()).getDocument();
    editUri = getEditUri(doc.getRoot());
    if (editUri != null) {
      abderaClient.delete(editUri.toString());
      report("The Enry has been deleted", null);
    } else {
      report("The Entry cannot be deleted", null);
    }
  }
  public static Entry toPackageEntryAbdera(ModuleItem p, UriInfo uriInfo) {
    URI baseURL;
    if (p.isHistoricalVersion()) {
      baseURL =
          uriInfo
              .getBaseUriBuilder()
              .path("packages/{packageName}/versions/{version}")
              .build(p.getName(), Long.toString(p.getVersionNumber()));
    } else {
      baseURL = uriInfo.getBaseUriBuilder().path("packages/{packageName}").build(p.getName());
    }

    Factory factory = Abdera.getNewFactory();

    org.apache.abdera.model.Entry e = factory.getAbdera().newEntry();
    e.setTitle(p.getTitle());
    e.setSummary(p.getDescription());
    e.setPublished(new Date(p.getLastModified().getTimeInMillis()));
    e.setBaseUri(baseURL.toString());
    e.addAuthor(p.getLastContributor());

    e.setId(baseURL.toString());

    Iterator<AssetItem> i = p.getAssets();
    while (i.hasNext()) {
      AssetItem item = i.next();
      org.apache.abdera.model.Link l = factory.newLink();

      l.setHref(
          UriBuilder.fromUri(baseURL).path("assets/{assetName}").build(item.getName()).toString());
      l.setTitle(item.getTitle());
      l.setRel("asset");
      e.addLink(l);
    }

    // generate meta data
    ExtensibleElement extension = e.addExtension(METADATA);
    ExtensibleElement childExtension = extension.addExtension(ARCHIVED);
    // childExtension.setAttributeValue("type", ArtifactsRepository.METADATA_TYPE_STRING);
    childExtension.addSimpleExtension(VALUE, p.isArchived() ? "true" : "false");

    childExtension = extension.addExtension(UUID);
    childExtension.addSimpleExtension(VALUE, p.getUUID());

    childExtension = extension.addExtension(STATE);
    childExtension.addSimpleExtension(VALUE, p.getState() == null ? "" : p.getState().getName());

    childExtension = extension.addExtension(VERSION_NUMBER);
    childExtension.addSimpleExtension(VALUE, String.valueOf(p.getVersionNumber()));

    childExtension = extension.addExtension(CHECKIN_COMMENT);
    childExtension.addSimpleExtension(VALUE, p.getCheckinComment());

    org.apache.abdera.model.Content content = factory.newContent();
    content.setSrc(UriBuilder.fromUri(baseURL).path("binary").build().toString());
    content.setMimeType("application/octet-stream");
    content.setContentType(Type.MEDIA);
    e.setContentElement(content);

    return e;
  }
  public org.apache.abdera.model.Entry transform(
      final Document document, final org.apache.abdera.model.Entry entry)
      throws TransformerException {
    final List<String> categories = this.getCategories(document);
    for (final String category : categories) {
      entry.addCategory(category);
    }
    final String title = this.getTitle(document);
    if (NullChecker.isNotEmpty(title)) {
      entry.setTitle(title, Text.Type.TEXT);
    }
    final String editedDate = this.getEditedDate(document);
    if (NullChecker.isNotEmpty(editedDate)) {
      final Date date = this.parseDate(editedDate);
      entry.setEdited(date);
    }

    final String id = this.getId(document);
    if (NullChecker.isNotEmpty(id)) {
      entry.setId(id);
    }

    final String published = this.getPublished(document);
    if (NullChecker.isNotEmpty(published)) {
      final Date date = this.parseDate(published);
      entry.setPublished(date);
    }

    final String rights = this.getRights(document);
    if (NullChecker.isNotEmpty(rights)) {
      entry.setRights(rights);
    }

    final String summary = this.getSummary(document);
    if (NullChecker.isNotEmpty(summary)) {
      entry.setSummaryAsHtml(summary);
    }

    final String updated = this.getUpdated(document);
    if (NullChecker.isNotEmpty(updated)) {
      final Date date = this.parseDate(updated);
      entry.setUpdated(date);
    }

    final String author = this.getAuthor(document);
    if (NullChecker.isNotEmpty(author)) {
      entry.addAuthor(author);
    }

    final String comment = this.getComment(document);
    if (NullChecker.isNotEmpty(comment)) {
      entry.addComment(comment);
    }

    final String contributor = this.getContributor(document);
    if (NullChecker.isNotEmpty(contributor)) {
      entry.addContributor(contributor);
    }

    final Map<QName, String> extensions = this.getExtensions(document);
    for (final java.util.Map.Entry<QName, String> extension : extensions.entrySet()) {
      final QName extensionQName = extension.getKey();
      final String text = extension.getValue();
      final Element element = entry.addExtension(extensionQName);
      element.setText(text);
    }
    final String content = this.xmlToString.transform(document);
    entry.setContent(content, MediaType.APPLICATION_XML);

    return entry;
  }