private void populateEntry(Context context, Entry entry, Bitstream bitstream)
      throws DSpaceSwordException {
    BitstreamFormat format = bitstream.getFormat();
    String contentType = null;
    if (format != null) {
      contentType = format.getMIMEType();
    }

    SwordUrlManager urlManager = new SwordUrlManager(new SwordConfigurationDSpace(), context);
    String bsUrl = urlManager.getBitstreamUrl(bitstream);

    entry.setId(bsUrl);
    entry.setTitle(bitstream.getName());
    String desc = bitstream.getDescription();
    if ("".equals(desc) || desc == null) {
      desc = bitstream.getName();
    }
    entry.setSummary(desc);
    entry.setUpdated(new Date()); // required, though content is spurious

    // add an edit-media link for the bitstream ...
    Abdera abdera = new Abdera();
    Link link = abdera.getFactory().newLink();
    link.setHref(urlManager.getActionableBitstreamUrl(bitstream));
    link.setMimeType(contentType);
    link.setRel("edit-media");
    entry.addLink(link);

    // set the content of the bitstream
    entry.setContent(new IRI(bsUrl), contentType);
  }
 private void addTasksToFeed(
     RequestContext context, Feed feed, Task[] tasks, String token, String user) throws Exception {
   for (Task t : tasks) {
     Entry entry = feed.addEntry();
     entry.setId(t.getID());
     entry.setTitle(t.getDescription());
     entry.setUpdated(new Date());
     setLinkForTask(t, token, context, entry, user);
   }
 }
  private void addAtomManagedDatastream(Feed feed, String contentLocation) throws Exception {
    String dsId = "DS";

    Entry dsEntry = feed.addEntry();
    dsEntry.setId(feed.getId().toString() + "/" + dsId);

    Entry dsvEntry = feed.addEntry();
    dsvEntry.setId(dsEntry.getId().toString() + "/" + feed.getUpdatedString());

    dsEntry.setTitle(feed.getTitle());
    dsEntry.setUpdated(feed.getUpdated());
    dsEntry.addLink(dsvEntry.getId().toString(), Link.REL_ALTERNATE);
    dsEntry.addCategory(MODEL.STATE.uri, "A", null);
    dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "M", null);
    dsEntry.addCategory(MODEL.VERSIONABLE.uri, "true", null);

    dsvEntry.setTitle(feed.getTitle());
    dsvEntry.setUpdated(feed.getUpdated());
    ThreadHelper.addInReplyTo(dsvEntry, dsEntry.getId());
    dsvEntry.setSummary("summary");
    dsvEntry.setContent(new IRI(contentLocation), "text/plain");
  }
    public AdapterResponse<Feed> adapterResponse(int entriesOnFeed, boolean hasNextMarker) {
      final Feed feed = Abdera.getInstance().newFeed();

      for (int i = 1; i <= entriesOnFeed; i++) {
        Entry entry = Abdera.getInstance().newEntry();
        entry.setId(Integer.toString(i));
        feed.addEntry(entry);
      }

      if (hasNextMarker) {
        feed.addLink("next", REL_NEXT);
      }

      return new FeedSourceAdapterResponse<Feed>(feed, HttpStatus.OK, "");
    }
  private Entry createBookEntry(int id, String name) throws Exception {

    Book b = new Book();
    b.setId(id);
    b.setName(name);

    Factory factory = Abdera.getNewFactory();
    JAXBContext jc = JAXBContext.newInstance(Book.class);

    Entry e = factory.getAbdera().newEntry();
    e.setTitle(b.getName());
    e.setId(Long.toString(b.getId()));

    StringWriter writer = new StringWriter();
    jc.createMarshaller().marshal(b, writer);

    Content ct = factory.newContent(Content.Type.XML);
    ct.setValue(writer.toString());
    e.setContentElement(ct);
    return e;
  }
  /*    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 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 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);
    }
  }
  @Override
  public AdapterResponse<Entry> postEntry(PostEntryRequest postEntryRequest) {
    final Entry abderaParsedEntry = postEntryRequest.getEntry();
    final PersistedEntry persistedEntry = new PersistedEntry();

    // Update our category indicies
    final Set<PersistedCategory> entryCategories =
        feedRepository.updateCategories(processCategories(abderaParsedEntry.getCategories()));
    persistedEntry.setCategories(entryCategories);

    boolean entryIdSent = abderaParsedEntry.getId() != null;

    // Generate an ID for this entry
    if (allowOverrideId
        && entryIdSent
        && StringUtils.isNotBlank(abderaParsedEntry.getId().toString().trim())) {
      String entryId = abderaParsedEntry.getId().toString();
      // Check to see if entry with this id already exists
      PersistedEntry exists = feedRepository.getEntry(entryId, postEntryRequest.getFeedName());
      if (exists != null) {
        String errMsg =
            String.format("Unable to persist entry. Reason: entryId (%s) not unique.", entryId);
        throw new PublicationException(errMsg);
      }
      persistedEntry.setEntryId(abderaParsedEntry.getId().toString());
    } else {
      persistedEntry.setEntryId(UUID_URI_SCHEME + UUID.randomUUID().toString());
      abderaParsedEntry.setId(persistedEntry.getEntryId());
    }

    if (allowOverrideDate) {
      Date updated = abderaParsedEntry.getUpdated();

      if (updated != null) {
        persistedEntry.setDateLastUpdated(updated);
        persistedEntry.setCreationDate(updated);
      }
    }

    if (abderaParsedEntry.getSelfLink() == null) {
      abderaParsedEntry
          .addLink(
              decode(
                      postEntryRequest.urlFor(
                          new EnumKeyedTemplateParameters<URITemplate>(URITemplate.FEED)))
                  + "entries/"
                  + persistedEntry.getEntryId())
          .setRel(LINKREL_SELF);
    }

    final PersistedFeed feedRef =
        new PersistedFeed(
            postEntryRequest.getFeedName(), UUID_URI_SCHEME + UUID.randomUUID().toString());

    persistedEntry.setFeed(feedRef);
    persistedEntry.setEntryBody(entryToString(abderaParsedEntry));

    abderaParsedEntry.setUpdated(persistedEntry.getDateLastUpdated());

    feedRepository.saveEntry(persistedEntry);

    return ResponseBuilder.created(abderaParsedEntry);
  }
  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;
  }