@Test
  @RunAsClient
  public void testUpdateAssetFromAtomWithStateNotExist(@ArquillianResource URL baseURL)
      throws Exception {
    URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();

    // Update state
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    stateExtension.<Element>getExtension(Translator.VALUE).setText("NonExistState");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);
    entry.writeTo(connection.getOutputStream());
    assertEquals(500, connection.getResponseCode());
    connection.disconnect();
  }
Example #2
0
  @Test
  public void testGetBooks() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookstore/books/feed";
    Feed feed = getFeed(endpointAddress, null);
    assertEquals(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/feed",
        feed.getBaseUri().toString());
    assertEquals("Collection of Books", feed.getTitle());

    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/feed",
        "resources/expected_atom_books_json.txt",
        "application/json");

    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/jsonfeed",
        "resources/expected_atom_books_jsonfeed.txt",
        "application/json, text/html, application/xml;q=0.9,"
            + " application/xhtml+xml, image/png, image/jpeg, image/gif,"
            + " image/x-xbitmap, */*;q=0.1");

    Entry entry = addEntry(endpointAddress);
    entry = addEntry(endpointAddress + "/relative");

    endpointAddress = "http://localhost:" + PORT + "/bookstore/bookstore/books/subresources/123";
    entry = getEntry(endpointAddress, null);
    assertEquals("CXF in Action", entry.getTitle());

    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123",
        "resources/expected_atom_book_json.txt",
        "application/json");

    getAndCompareJson(
        "http://localhost:"
            + PORT
            + "/bookstore/bookstore/books/entries/123?_type="
            + "application/json",
        "resources/expected_atom_book_json.txt",
        "*/*");
    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123?_type=" + "json",
        "resources/expected_atom_book_json.txt",
        "*/*");

    // do the same using extension mappings
    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123.json",
        "resources/expected_atom_book_json.txt",
        "*/*");
    // do the same using extension mappings & matrix parameters
    getAndCompareJson(
        "http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123.json;a=b",
        "resources/expected_atom_book_json_matrix.txt",
        "*/*");
  }
 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);
   }
 }
  @Override
  public List<OrganizationResource> getOrganizationResources() {

    List<OrganizationResource> organizationResources = new ArrayList<OrganizationResource>();

    for (Entry entry : entries) {
      organizationResources.add(new OrganizationResourceImpl(entry.getLink(REL_ALT)));
    }

    return organizationResources;
  }
    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, "");
    }
 @Override
 public List<String> getStatuses() {
   ArrayList<String> statuses = new ArrayList<String>();
   try {
     ResourceLink link = getRelatedResourceUris().getFirst("statuses");
     WebResource resource = getClient().resource(getUri().resolve(link.getUri()));
     resource.accept(link.getMimeType());
     Feed statusFeed = resource.get(Feed.class);
     for (Entry entry : statusFeed.getEntries()) {
       statuses.add(entry.getContent());
     }
   } catch (Exception ex) {
     logger.warn("Could not fetch statuses!", ex);
   }
   return statuses;
 }
Example #7
0
 /** Existing agents are detected based on email address as well as URI key. */
 @Override
 public Agent getExistingRecord(RequestContext request) throws ResponseContextException {
   // Try super method first
   Agent existingAgent = super.getExistingRecord(request);
   if (existingAgent != null) {
     return existingAgent;
   }
   // If not, it's time for some Agent-specific searching
   Entry entry = getEntryFromRequest(request);
   for (Link link : entry.getLinks(Constants.REL_MBOX)) {
     InternetAddress emailAddress = getAdapterInputHelper().getEmailFromHref(link.getHref());
     existingAgent = getAgentWithEmail(emailAddress);
     if (existingAgent != null) {
       return existingAgent;
     }
   }
   return null;
 }
  @Test
  @RunAsClient
  public void testGetDRLAndDSLAssetsAsAtom(@ArquillianResource URL baseURL) throws Exception {
    AbderaClient client = new AbderaClient(abdera);
    client.addCredentials(
        baseURL.toExternalForm(),
        null,
        null,
        new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));

    RequestOptions options = client.getDefaultRequestOptions();
    options.setAccept(MediaType.APPLICATION_ATOM_XML);

    ClientResponse resp =
        client.get(
            new URL(baseURL, "rest/packages/restPackage1/assets?format=drl&format=dsl")
                .toExternalForm(),
            options);

    if (resp.getType() != ResponseType.SUCCESS) {
      fail(
          "Couldn't retrieve DRL and DSL assets-> "
              + resp.getStatus()
              + ": "
              + resp.getStatusText());
    }

    // Get the entry element
    Document<Feed> document = resp.getDocument();

    // Check number of results
    assertEquals(3, document.getRoot().getEntries().size());

    // Check assets names
    List<String> assetNames = new ArrayList<String>();
    for (Entry entry : document.getRoot().getEntries()) {
      assetNames.add(entry.getTitle());
    }

    assertTrue(assetNames.contains("rule1"));
    assertTrue(assetNames.contains("rule4"));
    assertTrue(assetNames.contains("myDSL"));
  }
Example #9
0
  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;
  }
  private void iterateAndListCollections(ServiceDocument sd, AuthCredentials auth)
      throws Exception {
    if (sd == null) {
      System.out.println("--- Service Document was NULL --");
      return;
    }

    List<SWORDWorkspace> ws = sd.getWorkspaces();
    for (SWORDWorkspace w : ws) {
      List<SWORDCollection> collections = w.getCollections();
      for (SWORDCollection c : collections) {
        System.out.println("Collection: " + c.getTitle());
        IRI href = c.getHref();
        CollectionEntries ces = client.listCollection(href.toString(), auth);
        for (Entry entry : ces.getEntries()) {
          IRI id = entry.getId();
          System.out.println("\t\tID: " + id.toString());
        }
      }
    }
  }
 @Override
 public List<FieldDef> getFieldDefs() {
   if (getLastReadStateOfEntity() == null
       || getLastReadStateOfEntity().getEntries() == null
       || getLastReadStateOfEntity().getEntries().isEmpty()) {
     return Collections.emptyList();
   }
   List<FieldDef> defs = new ArrayList<FieldDef>(getLastReadStateOfEntity().getEntries().size());
   ObjectMapper mapper = new ObjectMapper();
   for (Entry entry : getLastReadStateOfEntity().getEntries()) {
     if (logger.isDebugEnabled()) {
       logger.debug("FiedDef JSON Content: " + entry.getContent());
     }
     try {
       defs.add(mapper.readValue(entry.getContent(), FieldDef.class));
     } catch (Exception ex) {
       logger.error("Could not parse Field Def JSON", ex);
     }
   }
   return defs;
 }
Example #12
0
  @Test
  public void testGetBaseUrlForInvalidValue() {
    Entry newEntry = new Abdera().newEntry();
    // illegal argument exception
    newEntry.setBaseUri(new IRI("foo"));
    try {
      AtomUtil.getBaseUrl(newEntry);
      fail("IllegalArgumentException should have thrown");
    } catch (Exception e) {
      assertTrue(e instanceof IllegalArgumentException);
    }

    // malformed url exception
    newEntry.setBaseUri(new IRI("foo://test:8080/bar"));
    try {
      AtomUtil.getBaseUrl(newEntry);
      fail("IllegalArgumentException should have thrown");
    } catch (Exception e) {
      assertTrue(e.getCause() instanceof MalformedURLException);
    }
  }
Example #13
0
  private Entry addEntry(String endpointAddress) throws Exception {
    Entry e = createBookEntry(256, "AtomBook");
    StringWriter w = new StringWriter();
    e.writeTo(w);

    PostMethod post = new PostMethod(endpointAddress);
    post.setRequestEntity(new StringRequestEntity(w.toString(), "application/atom+xml", null));
    HttpClient httpclient = new HttpClient();

    String location = null;
    try {
      int result = httpclient.executeMethod(post);
      assertEquals(201, result);
      location = post.getResponseHeader("Location").getValue();
      InputStream ins = post.getResponseBodyAsStream();
      Document<Entry> entryDoc = abdera.getParser().parse(copyIn(ins));
      assertEquals(entryDoc.getRoot().toString(), e.toString());
    } finally {
      post.releaseConnection();
    }

    Entry entry = getEntry(location, null);
    assertEquals(location, entry.getBaseUri().toString());
    assertEquals("AtomBook", entry.getTitle());
    return entry;
  }
  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 String entryToString(Entry entry) {
    final StringWriter writer = new StringWriter();

    try {
      entry.writeTo(writer);
    } catch (IOException ioe) {
      LOG.error(
          "Unable to write entry to string. Unable to persist entry. Reason: " + ioe.getMessage(),
          ioe);

      throw new PublicationException(ioe.getMessage(), ioe);
    }

    return writer.toString();
  }
  @Test
  @RunAsClient
  public void testGetAssetAsAtom(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    // System.out.println(getContent(connection));

    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();
    assertEquals(
        baseURL.getPath() + "rest/packages/restPackage1/assets/model1",
        entry.getBaseUri().getPath());
    assertEquals("model1", entry.getTitle());
    assertNotNull(entry.getPublished());
    assertNotNull(entry.getAuthor().getName());
    assertEquals("desc for model1", entry.getSummary());
    // assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(),
    // entry.getContentMimeType().getPrimaryType());
    assertEquals(
        baseURL.getPath() + "rest/packages/restPackage1/assets/model1/binary",
        entry.getContentSrc().getPath());

    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED);
    assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID);
    assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES);
    assertEquals(
        "AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE));
  }
 public ResponseContext getEntry(RequestContext requestcontext) {
   Entry entry = (Entry) getAbderaEntry(requestcontext);
   if (entry != null) {
     Feed feed = entry.getParentElement();
     entry = (Entry) entry.clone();
     entry.setSource(feed.getAsSource());
     Document<Entry> entry_doc = entry.getDocument();
     return ProviderHelper.returnBase(entry_doc, 200, entry.getEdited())
         .setEntityTag(ProviderHelper.calculateEntityTag(entry));
   } else {
     return ProviderHelper.notfound(requestcontext);
   }
 }
Example #18
0
 private static IRI getEditUri(Entry entry) throws Exception {
   IRI editUri = null;
   List<Link> editLinks = entry.getLinks("edit");
   for (Link link : editLinks) {
     // if there is more than one edit link, we should not automatically
     // assume that it's always going to point to an Atom document
     // representation.
     if (link.getMimeType() != null) {
       if (link.getMimeType().match("application/atom+xml")) {
         editUri = link.getResolvedHref();
         break;
       }
     } else { // assume that an edit link with no type attribute is the right one to use
       editUri = link.getResolvedHref();
       break;
     }
   }
   return editUri;
 }
 private void setLinkForTask(Task t, String ticket, RequestContext context, Entry e, String user)
     throws Exception {
   Factory factory = context.getAbdera().getFactory();
   Link link = factory.newLink();
   String formLink = URIUtils.getFormURLForTask(_manager, t, ticket, user);
   // if the URL of the form manager are relative URLs, we want to have a proper link back to the
   // machine.
   // localhost won't work for most RSS readers, so using loopback ip address in this very specific
   // case
   if (!formLink.toLowerCase().startsWith("http")) { // relative URL
     IRI baseUri = context.getBaseUri();
     String host = baseUri.getHost();
     host = host.equals("localhost") ? "127.0.0.1" : host;
     String base = baseUri.getScheme() + "//" + host + ":" + baseUri.getPort();
     link.setBaseUri(base);
   } else {
     link.setBaseUri(StringUtils.EMPTY);
   }
   link.setHref(formLink);
   link.setTitle("Link to " + t.getDescription());
   link.setText("Link to " + t.getDescription());
   e.addLink(link);
 }
Example #20
0
  /*    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;
  }
  @Override
  public ResponseContext postEntry(RequestContext request) {
    DetachedItemTarget target = (DetachedItemTarget) request.getTarget();
    NoteItem master = target.getMaster();
    NoteItem occurrence = target.getOccurrence();

    if (log.isDebugEnabled())
      log.debug("detaching occurrence " + occurrence.getUid() + " from master " + master.getUid());

    ResponseContext frc = checkEntryWritePreconditions(request);
    if (frc != null) return frc;

    try {
      // XXX: does abdera automatically resolve external content?
      Entry entry = (Entry) request.getDocument().getRoot();
      ContentProcessor processor = createContentProcessor(entry);
      NoteItem detached = (NoteItem) master.copy();
      processor.processContent(entry.getContent(), detached);
      detached = detachOccurrence(master, detached, occurrence);

      ItemTarget itemTarget =
          new ItemTarget(request, detached, target.getProjection(), target.getFormat());
      ServiceLocator locator = createServiceLocator(request);
      ItemFeedGenerator generator = createItemFeedGenerator(itemTarget, locator);
      entry = generator.generateEntry(detached);

      return created(request, entry, detached, locator);
    } catch (IOException e) {
      String reason = "Unable to read request content: " + e.getMessage();
      log.error(reason, e);
      return ProviderHelper.servererror(request, reason, e);
    } catch (UnsupportedContentTypeException e) {
      return ProviderHelper.badrequest(
          request,
          "Entry content type must be one of "
              + StringUtils.join(getProcessorFactory().getSupportedContentTypes(), ", "));
    } catch (ParseException e) {
      String reason = "Unparseable content: ";
      if (e.getCause() != null) reason = reason + e.getCause().getMessage();
      else reason = reason + e.getMessage();
      return ProviderHelper.badrequest(request, reason);
    } catch (ValidationException e) {
      String reason = "Invalid content: ";
      if (e.getCause() != null) reason = reason + e.getCause().getMessage();
      else reason = reason + e.getMessage();
      return ProviderHelper.badrequest(request, reason);
    } catch (UidInUseException e) {
      return ProviderHelper.conflict(request, "Uid already in use");
    } catch (ProcessorException e) {
      String reason = "Unknown content processing error: " + e.getMessage();
      log.error(reason, e);
      return ProviderHelper.servererror(request, reason, e);
    } catch (CollectionLockedException e) {
      return locked(request);
    } catch (GeneratorException e) {
      String reason = "Unknown entry generation error: " + e.getMessage();
      log.error(reason, e);
      return ProviderHelper.servererror(request, reason, e);
    } catch (CosmoSecurityException e) {
      if (e instanceof ItemSecurityException)
        return insufficientPrivileges(
            request, new InsufficientPrivilegesException((ItemSecurityException) e));
      else return ProviderHelper.forbidden(request, e.getMessage());
    }
  }
Example #22
0
  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 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;
  }
  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");
  }
  @Test
  @RunAsClient
  public void testUpdateAssetFromAtom(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    // System.out.println(GetContent(connection));

    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();
    assertEquals(
        baseURL.getPath() + "rest/packages/restPackage1/assets/model1",
        entry.getBaseUri().getPath());
    assertEquals("model1", entry.getTitle());
    assertNotNull(entry.getPublished());
    assertNotNull(entry.getAuthor().getName());
    assertEquals("desc for model1", entry.getSummary());
    // assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(),
    // entry.getContentMimeType().getPrimaryType());
    assertEquals(
        baseURL.getPath() + "rest/packages/restPackage1/assets/model1/binary",
        entry.getContentSrc().getPath());

    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED);
    assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID);
    assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES);
    assertEquals(
        "AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE));
    connection.disconnect();

    // Update category. Add a new category tag
    categoryExtension.addSimpleExtension(Translator.VALUE, "AssetPackageResourceTestCategory2");
    // Update state
    stateExtension.<Element>getExtension(Translator.VALUE).setText("Dev");
    // Update format
    formatExtension.<Element>getExtension(Translator.VALUE).setText("anotherformat");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);
    entry.writeTo(connection.getOutputStream());
    assertEquals(204, connection.getResponseCode());
    connection.disconnect();

    // Verify again
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    // System.out.println(GetContent(connection));

    in = connection.getInputStream();
    assertNotNull(in);
    doc = abdera.getParser().parse(in);
    entry = doc.getRoot();

    metadataExtension = entry.getExtension(Translator.METADATA);
    archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED);
    assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE));
    stateExtension = metadataExtension.getExtension(Translator.STATE);
    assertEquals("Dev", stateExtension.getSimpleExtension(Translator.VALUE));
    formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("anotherformat", formatExtension.getSimpleExtension(Translator.VALUE));
    categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES);
    List<Element> categoryValues = categoryExtension.getExtensions(Translator.VALUE);
    assertTrue(categoryValues.size() == 2);
    boolean foundCategory1 = false;
    boolean foundCategory2 = false;
    for (Element cat : categoryValues) {
      String catgoryValue = cat.getText();
      if ("AssetPackageResourceTestCategory".equals(catgoryValue)) {
        foundCategory1 = true;
      }
      if ("AssetPackageResourceTestCategory2".equals(catgoryValue)) {
        foundCategory2 = true;
      }
    }
    assertTrue(foundCategory1);
    assertTrue(foundCategory2);
  }
  @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);
  }
  @Test
  @RunAsClient
  public void testCreateAssetFromAtom(@ArquillianResource URL baseURL) throws Exception {

    // Check there is no model1-New asset
    AbderaClient client = new AbderaClient(abdera);
    client.addCredentials(
        baseURL.toExternalForm(),
        null,
        null,
        new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));
    RequestOptions options = client.getDefaultRequestOptions();
    options.setAccept(MediaType.APPLICATION_ATOM_XML);

    ClientResponse resp =
        client.get(
            new URL(baseURL, "rest/packages/restPackage1/assets/model1-New").toExternalForm());

    // If the asset doesn't exist, an HTTP 500 Error is expected. :S
    if (resp.getType() != ResponseType.SERVER_ERROR) {
      fail(
          "I was expecting an HTTP 500 Error because 'model1-New' shouldn't exist. "
              + "Instead of that I got-> "
              + resp.getStatus()
              + ": "
              + resp.getStatusText());
    }

    // --------------------------------------------------------------

    // Get asset 'model1' from Guvnor
    client = new AbderaClient(abdera);
    client.addCredentials(
        baseURL.toExternalForm(),
        null,
        null,
        new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));

    options = client.getDefaultRequestOptions();
    options.setAccept(MediaType.APPLICATION_ATOM_XML);

    resp =
        client.get(new URL(baseURL, "rest/packages/restPackage1/assets/model1").toExternalForm());

    if (resp.getType() != ResponseType.SUCCESS) {
      fail("Couldn't retrieve 'model1' asset-> " + resp.getStatus() + ": " + resp.getStatusText());
    }

    // Get the entry element
    Document<Entry> doc = resp.getDocument();
    Entry entry = doc.getRoot();

    // --------------------------------------------------------------

    // Change the title of the asset
    entry.setTitle(entry.getTitle() + "-New");

    // Save it as a new Asset
    client = new AbderaClient(abdera);
    client.addCredentials(
        baseURL.toExternalForm(),
        null,
        null,
        new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));

    options = client.getDefaultRequestOptions();
    options.setContentType(MediaType.APPLICATION_ATOM_XML);

    resp =
        client.post(
            new URL(baseURL, "rest/packages/restPackage1/assets").toExternalForm(), entry, options);

    if (resp.getType() != ResponseType.SUCCESS) {
      fail("Couldn't store 'model1-New' asset-> " + resp.getStatus() + ": " + resp.getStatusText());
    }

    // --------------------------------------------------------------

    // Check that the new asset is in the repository
    client = new AbderaClient(abdera);
    client.addCredentials(
        baseURL.toExternalForm(),
        null,
        null,
        new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));
    options = client.getDefaultRequestOptions();
    options.setAccept(MediaType.APPLICATION_ATOM_XML);

    resp =
        client.get(
            new URL(baseURL, "rest/packages/restPackage1/assets/model1-New").toExternalForm());

    if (resp.getType() != ResponseType.SUCCESS) {
      fail(
          "Couldn't retrieve 'model1-New' asset-> "
              + resp.getStatus()
              + ": "
              + resp.getStatusText());
    }

    // Get the entry element
    doc = resp.getDocument();
    entry = doc.getRoot();

    // Compare the title :P
    assertEquals(entry.getTitle(), "model1-New");
  }
Example #28
0
 @Test
 public void testGetBaseUrl() {
   Entry newEntry = new Abdera().newEntry();
   newEntry.setBaseUri(new IRI("http://myserver:8080/myservice/Test.svc"));
   assertEquals("http://myserver:8080/myservice/Test.svc", AtomUtil.getBaseUrl(newEntry));
 }
Example #29
0
  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;
  }