public InputStream disseminate(Context context, Item item) throws DSpaceSwordException, SwordError, SwordServerException { try { Abdera abdera = new Abdera(); Feed feed = abdera.newFeed(); this.addMetadata(feed, item); Bundle[] originals = item.getBundles("ORIGINAL"); for (Bundle original : originals) { Bitstream[] bss = original.getBitstreams(); for (Bitstream bitstream : bss) { Entry entry = feed.addEntry(); this.populateEntry(context, entry, bitstream); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); feed.writeTo(baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); return bais; } catch (SQLException e) { throw new DSpaceSwordException(e); } catch (IOException e) { throw new DSpaceSwordException(e); } }
private byte[] getAtomObject(String pid, String contentLocation) throws Exception { Feed feed = createAtomObject(pid, contentLocation); Writer sWriter = new StringWriter(); feed.writeTo("prettyxml", sWriter); return sWriter.toString().getBytes("UTF-8"); }
/** * Add an new empty feed::dasextension element with only a completed management element to the * given Feed. Sets the responseTime value to now. Note: A proper sites::site element must be * added to the new feed::dasextension element for this new feed::dasextension element to be * valid. * * @param feed - mandatory * @return */ private Feed addEmptyDasExtension(Feed feed) { // check to make sure there's a dasextension QName dasextensionQname = new QName(this.dasextensionNamespace, "dasextension"); ExtensibleElement dasExt = feed.getExtension(dasextensionQname); if (NullChecker.isEmpty(dasExt)) { dasExt = feed.addExtension(dasextensionQname); // add the dasextension::management element QName managementQname = new QName(this.dasextensionNamespace, "management"); ExtensibleElement management = dasExt.getExtension(managementQname); if (NullChecker.isEmpty(management)) { management = dasExt.addExtension(managementQname); } QName responseTimeQname = new QName(this.dasextensionNamespace, "responseTime"); ExtensibleElement responseTime = management.getExtension(responseTimeQname); if (NullChecker.isEmpty(responseTime)) { responseTime = management.addExtension(responseTimeQname); } // set/reset the response time to now XMLGregorianCalendar xmlGregCalResponseTime = GregorianDateUtil.getGregorianCalendarByDate(new Date()); responseTime.setText(xmlGregCalResponseTime.toString()); // TODO: Verify date format } return feed; }
@Test public void testGetBooksWithCustomProvider() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookstore4/books/feed"; Feed feed = getFeed(endpointAddress, null); assertEquals( "http://localhost:" + PORT + "/bookstore/bookstore4/books/feed", feed.getBaseUri().toString()); assertEquals("Collection of Books", feed.getTitle()); }
@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", "*/*"); }
@Test public void shouldAddLinksAndElements() { final FeedPagingProcessor target = feedPagingProcessor(); final AdapterResponse<Feed> feedResponse = adapterResponse(TOTAL_FEED_ENTRIES); final RequestContext rc = requestContext(); target.process(rc, feedResponse); Feed feed = feedResponse.getBody().getAsFeed(); assertThat("Should set updated element", feed.getUpdated(), notNullValue()); }
@Test public void shouldNotAddMarkers() { final FeedPagingProcessor target = feedPagingProcessor(); final AdapterResponse<Feed> feedResponse = adapterResponse(TOTAL_FEED_ENTRIES); final RequestContext rc = requestContext(); target.process(rc, feedResponse); Feed feed = feedResponse.getBody().getAsFeed(); assertThat("Should not set current link", feed.getLink(REL_CURRENT), nullValue()); assertThat("Should not set next link", feed.getLink(REL_NEXT), nullValue()); }
@Test public void testGetBooks2() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/sub/"; Feed feed = getFeed(endpointAddress, null); assertEquals("http://localhost:" + PORT + "/bookstore/sub/", feed.getBaseUri().toString()); assertEquals("Collection of Books", feed.getTitle()); getAndCompareJson( "http://localhost:" + PORT + "/bookstore/sub/books/entries/123.json", "resources/expected_atom_book_json2.txt", "*/*"); }
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); } }
@Test public void shouldNotOverrideWhenNextIsSet() { final FeedPagingProcessor target = feedPagingProcessor(); final AdapterResponse<Feed> feedResponse = adapterResponse(1, true); final RequestContext rc = requestContext(); target.process(rc, feedResponse); Feed feed = feedResponse.getBody().getAsFeed(); assertThat( "Should not override next link", feed.getLink(REL_NEXT).getHref().toString(), equalTo(REL_NEXT)); }
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, ""); }
@Test public void listCollections() throws Exception { String pidString = "uuid:23425234532434"; String url = "https://localhost/services/collection/" + pidString; IRI iri = new IRI(url); Map<?, ?> response = this.generateImmediateChildrenResponse(10); when(tripleStoreQueryService.sendSPARQL(anyString())).thenReturn(response); Feed feed = manager.listCollectionContents(iri, new AuthCredentials("", "", ""), config); assertEquals(feed.getEntries().size(), 10); assertEquals(feed.getLinks().size(), 1); assertTrue(pidString.equals(feed.getId().toString())); }
private Feed getUserFeed() throws UriBuilderException, IllegalArgumentException { Feed userFeed = getFeed(userName, new Date()); userFeed.setTitle(userName); // add a self link userFeed.addLink(getSelfLink()); // add a edit link Link editLink = getAbderaFactory().newLink(); editLink.setHref(getUriInfo().getRequestUri().toString()); editLink.setRel(Link.REL_EDIT); editLink.setMimeType(MediaType.APPLICATION_JSON); userFeed.addLink(editLink); // add a alternate link Link altLink = getAbderaFactory().newLink(); altLink.setHref( getRelativeURIBuilder() .path(OrganizationUserResource.class) .path(USER_CONTENT_METHOD) .build(organizationUniqueShortName, userName) .toString()); altLink.setRel(Link.REL_ALTERNATE); altLink.setMimeType(MediaType.APPLICATION_JSON); userFeed.addLink(altLink); Link privilegesLink = getAbderaFactory().newLink(); privilegesLink.setHref( getRelativeURIBuilder() .path(UserPrivilegesResource.class) .build(organizationUniqueShortName, userName) .toString()); privilegesLink.setRel(REL_USER_PRIVILEGES); privilegesLink.setMimeType(MediaType.APPLICATION_JSON); userFeed.addLink(privilegesLink); Link rolesLink = getAbderaFactory().newLink(); rolesLink.setHref( getRelativeURIBuilder() .path(UserRolesResource.class) .build(organizationUniqueShortName, userName) .toString()); rolesLink.setRel(REL_USER_ROLES); rolesLink.setMimeType(MediaType.APPLICATION_JSON); userFeed.addLink(rolesLink); Link organizationLink = getAbderaFactory().newLink(); organizationLink.setHref( getRelativeURIBuilder() .path(OrganizationResource.class) .build(organizationUniqueShortName) .toString()); organizationLink.setRel("organization"); organizationLink.setMimeType(MediaType.APPLICATION_JSON); userFeed.addLink(organizationLink); return userFeed; }
@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; }
/** {@inheritDoc} */ protected void addFeedDetails(Feed feed, RequestContext request) throws ResponseContextException { try { String objectId = getId(request); String propertyFilter = request.getParameter(AtomCMIS.PARAM_FILTER); boolean includeAllowableActions = getBooleanParameter(request, AtomCMIS.PARAM_INCLUDE_ALLOWABLE_ACTIONS, false); int maxItems = getIntegerParameter(request, AtomCMIS.PARAM_MAX_ITEMS, CmisConstants.MAX_ITEMS); int skipCount = getIntegerParameter(request, AtomCMIS.PARAM_SKIP_COUNT, CmisConstants.SKIP_COUNT); Connection connection = getConnection(request); List<CmisObject> list = connection.getAllVersions(objectId, includeAllowableActions, true, propertyFilter); if (list.size() > 0) { // add cmisra:numItems Element numItems = feed.addExtension(AtomCMIS.NUM_ITEMS); numItems.setText(Integer.toString(list.size())); // Paging inks addPageLinks( objectId, feed, "versions", maxItems, skipCount, list.size(), (skipCount + maxItems) < list.size(), request); for (CmisObject one : list) { Entry entry = feed.addEntry(); IRI feedIri = new IRI(getFeedIriForEntry(one, request)); addEntryDetails(request, entry, feedIri, one); } } } catch (FilterNotValidException fe) { throw new ResponseContextException(createErrorResponse(fe, 400)); } catch (ObjectNotFoundException onfe) { throw new ResponseContextException(createErrorResponse(onfe, 404)); } catch (InvalidArgumentException iae) { throw new ResponseContextException(createErrorResponse(iae, 400)); } catch (Exception t) { throw new ResponseContextException(createErrorResponse(t, 500)); } }
private Feed createAtomObject(String spid, String contentLocation) throws Exception { PID pid = PID.getInstance(spid); Date date = new Date(1); String title = "title"; String author = "org.fcrepo.test.api.TestManagedDatastreams"; Feed feed = abdera.newFeed(); feed.setId(pid.toURI()); feed.setTitle(title); feed.setUpdated(date); feed.addAuthor(author); if (contentLocation != null && contentLocation.length() > 0) { addAtomManagedDatastream(feed, contentLocation); } return feed; }
@Test public void listCollectionsSecondPage() throws Exception { String pidString = "uuid:23425234532434"; String url = "https://localhost/services/collection/" + pidString + "/1"; IRI iri = new IRI(url); Map<?, ?> response = this.generateImmediateChildrenResponse(10); when(tripleStoreQueryService.sendSPARQL(endsWith(" 0"))).thenReturn(null); when(tripleStoreQueryService.sendSPARQL(endsWith(" 10"))).thenReturn(response); Feed feed = manager.listCollectionContents(iri, new AuthCredentials("", "", ""), config); assertEquals(feed.getEntries().size(), 10); assertEquals(feed.getLinks().size(), 1); String nextLink = feed.getLink("next").getHref().toString(); nextLink = nextLink.substring(nextLink.lastIndexOf("/") + 1); assertTrue("2".equals(nextLink)); assertTrue(pidString.equals(feed.getId().toString())); }
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); } }
OrganizationsResourceImpl(Link orgsLink) { this.orgsLink = orgsLink; orgsURI = UriBuilder.fromUri(BASE_URI.toString() + orgsLink.getHref().toString()).build(); URI uri = UriBuilder.fromUri(BASE_URI.toString() + orgsLink.getHref().toString()).build(); ClientResponse response = ClientUtil.readClientResponse(uri, getHttpClient(), MediaType.APPLICATION_ATOM_XML); PaginatedFeedEntitiesList<Organization> pgs; if (response.getStatus() == 200) { Feed feed = ClientUtil.getFeed(response); entries = feed.getEntries(); orgsLink = feed.getLink(REL_ORG); if (response.getHeaders().getFirst("Cache-Control") != null) isCacheEnabled = response.getHeaders().getFirst("Cache-Control").equals("no-cache"); String dateString = response.getHeaders().getFirst("Last-Modified"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { lastModifiedDate = format.parse(dateString); } catch (Exception ex) { } dateString = response.getHeaders().getFirst("Expires"); try { lastModifiedDate = format.parse(dateString); } catch (Exception ex) { } uri = response.getLocation(); } else { orgLink = null; } }
/** * Adds a single error element into the DAS dasextension Atom Feed at * feed::dasextension::query::errors. * * @param feed - mandatory - must contain a valid feed::dasextension Element * @param errorsError - mandatory - must contain a valid dasextension::query::errors::error * Element * @return */ private Feed addError(Feed feed, final ExtensibleElement errorsError) { if (NullChecker.isNotEmpty(feed)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { // get feed::dasextension::query::errors and add the new // error into it in the feed ExtensibleElement errors = this.getErrors(dasExt); errors.addExtension(errorsError); } } return feed; }
/** * Adds a single site element into the given DAS dasextension Atom Feed at * feed::dasextension::query::sites. * * @param feed * @param site - mandatory - must contain a valid dasextension::query::sites::site Element * @return */ private Feed addSite(Feed feed, final ExtensibleElement site) { if (NullChecker.isNotEmpty(feed)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { // get feed::dasextension::query::sites and add the new // site into it in the feed ExtensibleElement sites = this.getSites(dasExt); sites.addExtension(site); } } return feed; }
private void addMetadata(Feed feed, Item item) { SimpleDCMetadata md = this.getMetadata(item); /* not necessary ... Map<String, String> dc = md.getDublinCore(); for (String element : dc.keySet()) { String value = dc.get(element); feed.addSimpleExtension(new QName(UriRegistry.DC_NAMESPACE, element), value); } */ Map<String, String> atom = md.getAtom(); for (String element : atom.keySet()) { if ("author".equals(element)) { feed.addAuthor(atom.get(element)); } } // ensure that the feed has one author or more if (feed.getAuthors().size() == 0) { feed.addAuthor(ConfigurationManager.getProperty("dspace.name")); } }
/** * Adds a single error element into the DAS dasextension Atom Feed, i.e. adds one of the following * inside of feed::dasextension::query::errors: <error> <errorSeverity></errorSeverity> * <errorCode></errorCode> <errorValue></errorValue> <errorLocation></errorLocation> </error> * Note: The feed parameter must contain a constructed DAS dasextension Atom Feed. * * @param feed - mandatory - must contain a valid feed::dasextension Element * @param errorSeverity - optional * @param errorCode - optional * @param errorValue - optional * @param errorLocation - optional * @return */ public Feed addError( Feed feed, final String errorSeverity, final String errorCode, final String errorValue, final String errorLocation) { if (NullChecker.isNotEmpty(feed)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { // get reference to the dasextension::query::errors element in feed // -- if errors doesn't exist, this method will add it ExtensibleElement errors = this.getErrors(dasExt); // add the dasextension::query::errors::error element QName errorQname = new QName(this.dasextensionNamespace, "error"); ExtensibleElement errorsError = errors.addExtension(errorQname); if (NullChecker.isNotEmpty(errorSeverity)) { QName errorSeverityQname = new QName(this.dasextensionNamespace, "errorSeverity"); ExtensibleElement errorSeverityElement = errorsError.addExtension(errorSeverityQname); errorSeverityElement.setText(errorSeverity); } if (NullChecker.isNotEmpty(errorCode)) { QName errorCodeQname = new QName(this.dasextensionNamespace, "errorCode"); ExtensibleElement errorCodeElement = errorsError.addExtension(errorCodeQname); errorCodeElement.setText(errorCode); } if (NullChecker.isNotEmpty(errorValue)) { QName errorValueQname = new QName(this.dasextensionNamespace, "errorValue"); ExtensibleElement errorValueElement = errorsError.addExtension(errorValueQname); errorValueElement.setText(errorValue); } if (NullChecker.isNotEmpty(errorLocation)) { QName errorLocationQname = new QName(this.dasextensionNamespace, "errorLocation"); ExtensibleElement errorLocationElement = errorsError.addExtension(errorLocationQname); errorLocationElement.setText(errorLocation); } } } return feed; }
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"); }
/** * Adds the given dasextension::query::parameters Element into the given feed. Note: This method * will merge the given queryParameters with any existing query::parameters in the given feed. * * @param feed - mandatory - must contain a valid feed::dasextension Element * @param queryParameters - mandatory - must contain a valid and non-empty * dasextension::query::parameters Element. * @return */ private Feed addQueryParameters(Feed feed, final ExtensibleElement queryParameters) { if (NullChecker.isNotEmpty(feed)) { if (NullChecker.isNotEmpty(queryParameters)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { List<Element> queryParametersEntries = queryParameters.getElements(); if (NullChecker.isNotEmpty(queryParametersEntries)) { // get or create the new dasextension::path::parameters Element ExtensibleElement queryParametersFeed = this.getQueryParameters(dasExt); // add in the dasextension::path::parameters::entry Elements for (Element curQueryParameterEntry : queryParametersEntries) { queryParametersFeed.addExtension(curQueryParameterEntry); } } } } } return feed; }
@Override public String transform(final Feed feed) throws TransformerException { try { if (NullChecker.isNotEmpty(feed)) { // TODO: Cleanup - Fix this using DOM or research why XMLNS is being // added to entry baseURI String feedString = feed.toString(); feedString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + feedString; feedString = feedString.replaceAll( EscapeChars.forRegex("xmlns:xml=\"http://www.w3.org/XML/1998/namespace\""), ""); feedString = feedString.replaceAll( EscapeChars.forRegex("xmlns=\"http://www.w3.org/XML/1998/namespace\""), ""); return feedString; } return null; } catch (PatternSyntaxException ex) { throw new TransformerException(ex); } }
/** * Places the org.osehra.integration.http.uri.UriInfo uriInfo instance's query parameter values * into the DAS dasextension Atom Feed at feed::dasextension::query::parameters. Notes: The feed * parameter must contain a constructed DAS dasextension Atom Feed. This method will remove any * existing feed::dasextension::query::parameters::entry elements before adding the new entries * from uriInfo. * * @param feed -mandatory - must contain a valid feed::dasextension Element * @param uriInfo - mandatory * @return */ public Feed addQueryParameters(Feed feed, final javax.ws.rs.core.UriInfo uriInfo) { if (NullChecker.isNotEmpty(feed)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { // check for a UriInfo to input if (NullChecker.isNotEmpty(uriInfo) && !(uriInfo.getQueryParameters().isEmpty())) { // get or create reference to the dasextension::query::parameters element in feed ExtensibleElement parameters = this.getQueryParameters(dasExt); // discard any existing path dasextension::path::parameter::entry elements List<Element> queryParameterEntries = parameters.getElements(); if (NullChecker.isNotEmpty(queryParameterEntries)) { for (Element curQueryParameterEntry : queryParameterEntries) { curQueryParameterEntry.discard(); } } // add the dasextension::query::parameters::entry elements from uriInfo QName entryQname = new QName(this.dasextensionNamespace, "entry"); QName keyQname = new QName(this.dasextensionNamespace, "key"); QName valueQname = new QName(this.dasextensionNamespace, "value"); MultivaluedMap<String, String> queryParametersExt = uriInfo.getQueryParameters(); Set<Map.Entry<String, List<String>>> queryParamsEntries = queryParametersExt.entrySet(); for (Map.Entry<String, List<String>> queryParameterEntry : queryParamsEntries) { ExtensibleElement entry = parameters.addExtension(entryQname); ExtensibleElement key = entry.addExtension(keyQname); key.setText(queryParameterEntry.getKey()); for (String entryValue : queryParameterEntry.getValue()) { ExtensibleElement value = entry.addExtension(valueQname); value.setText(entryValue); } } } } } return feed; }
private Document<Feed> getFeedDocument(RequestContext context) throws ResponseContextException { Target target = context.getTarget(); String collection = target.getParameter("collection"); LOG.debug("Feed for collection:" + collection); // String priority = target.getParameter("priority"); // String deadline = target.getParameter("deadline"); // Locale preferredLocale = context.getPreferredLocale(); String user = target.getParameter("user"); String password = target.getParameter("password"); String token = target.getParameter("token"); Feed feed = createFeedBase(context); TokenClient tokenClient = Configuration.getInstance().getTokenClient(); try { if (token != null) { Property[] props = tokenClient.getTokenProperties(token); user = (String) PropertyUtils.getProperty(props, AuthenticationConstants.PROPERTY_USER).getValue(); } else if (user != null && password != null) { token = tokenClient.authenticateUser(user, password); } else throw new Exception("No credentials"); feed.setSubtitle("This is a feed for the following user:"******"Credential exception", e1); throw new ResponseContextException(500, e1); } feed.setId("IntalioFEEDID"); feed.setMustPreserveWhitespace(true); feed.setUpdated(new Date()); try { ITaskManagementService client = new RemoteTMSFactory(Configuration.getInstance().getTmsService(), token).getService(); if (collection.equalsIgnoreCase(IntalioFeeds.PROCESSES.name())) { feed.setTitle("Intalio Processes"); addTasksToFeed( context, feed, client.getAvailableTasks(PIPATask.class.getSimpleName(), null), token, user); } else if (collection.equalsIgnoreCase(IntalioFeeds.TASKS.name())) { feed.setTitle("Intalio Tasks"); addTasksToFeed( context, feed, client.getAvailableTasks( PATask.class.getSimpleName(), "T._state <> TaskState.COMPLETED"), token, user); addTasksToFeed( context, feed, client.getAvailableTasks( Notification.class.getSimpleName(), "T._state <> TaskState.COMPLETED"), token, user); } else if (collection.equalsIgnoreCase(IntalioFeeds.ALL.name())) { feed.setTitle("Full Intalio Feeds"); addTasksToFeed(context, feed, client.getTaskList(), token, user); } else throw new Exception("Invalid collection requestsed"); feed.addCategory(collection); } catch (Exception e) { LOG.error("Feed exception", e); throw new ResponseContextException(500, e); } if (LOG.isDebugEnabled()) try { feed.writeTo(System.out); } catch (IOException e) { } return feed.getDocument(); }
/** * Adds a single site element into the DAS dasextension Atom Feed. i.e. adds one of the following * inside of feed::dasextension::query::sites: <site> <id></id> <name></name> * <expectedCount></expectedCount> <retrievedCount></retrievedCount> <status></status> * <error></error> </site> Notes: The feed parameter must contain a constructed DAS dasextension * Atom Feed. An existing site element with the same site::name value as the given siteName value * will be removed before the new site element is added. * * @param feed - mandatory - must contain a valid feed::dasextension Element * @param siteName - mandatory * @param siteId - optional * @param siteHttpStatus - mandatory * @param expectedCount - optional * @param retrievedCount - optional * @param siteErrorMessage - optional * @return */ public Feed addSite( Feed feed, final String siteName, final String siteId, final int siteHttpStatus, final String expectedCount, final String retrievedCount, final String siteErrorMessage) { if (NullChecker.isNotEmpty(feed)) { // get reference to the dasextension element in feed ExtensibleElement dasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(dasExt)) { // get reference to the dasextension::query::sites element in feed ExtensibleElement sites = this.getSites(dasExt); // search for any existing site children by site::name value with // the new siteName, and if one is found, remove it List<Element> siteElements = sites.getElements(); for (Element curSiteElement : siteElements) { List<Element> siteChildElements = curSiteElement.getElements(); for (Element curSiteChildElement : siteChildElements) { if ("name".equals(curSiteChildElement.getQName().getLocalPart())) { if (siteName.equals(curSiteChildElement.getText())) { curSiteElement.discard(); } } } } // add the dasextension::query::sites::site element QName siteQname = new QName(this.dasextensionNamespace, "site"); ExtensibleElement site = sites.addExtension(siteQname); if (NullChecker.isNotEmpty(siteId)) { QName idQname = new QName(this.dasextensionNamespace, "id"); ExtensibleElement idElement = site.addExtension(idQname); idElement.setText(siteId); } QName nameQname = new QName(this.dasextensionNamespace, "name"); ExtensibleElement nameElement = site.addExtension(nameQname); nameElement.setText(siteName); if (NullChecker.isNotEmpty(expectedCount)) { QName expectedCountQname = new QName(this.dasextensionNamespace, "expectedCount"); ExtensibleElement expectedCountElement = site.addExtension(expectedCountQname); expectedCountElement.setText(expectedCount); } if (NullChecker.isNotEmpty(retrievedCount)) { QName retrievedCountQname = new QName(this.dasextensionNamespace, "retrievedCount"); ExtensibleElement retrievedCountElement = site.addExtension(retrievedCountQname); retrievedCountElement.setText(retrievedCount); } QName statusQname = new QName(this.dasextensionNamespace, "status"); ExtensibleElement statusElement = site.addExtension(statusQname); String siteStatus = new Integer(siteHttpStatus).toString(); statusElement.setText(siteStatus); if (NullChecker.isNotEmpty(siteErrorMessage)) { QName errorQname = new QName(this.dasextensionNamespace, "error"); ExtensibleElement siteErrorElement = site.addExtension(errorQname); siteErrorElement.setText(siteErrorMessage); } } } return feed; }
/** * Merge the elements in the given dasextensionToMerge Element into the feed::dasextension element * in the given feed. Note: The dasextension::path::parameters and dasextension::query::parameters * values in the given dasextensionToMerge Element will only be merged into the given feed if the * given feed does not already have these Elements. * * @param feed - mandatory - must contain a valid feed::dasextension Element * @param extensionToMerge - mandatory - must contain a valid dasextension Element * @return */ public Feed mergeDasExtension(Feed feed, final Element dasextensionToMerge) { if (NullChecker.isNotEmpty(feed)) { if (NullChecker.isNotEmpty(dasextensionToMerge)) { QName mergeExtQname = dasextensionToMerge.getQName(); String mergeExtTagName = mergeExtQname.getLocalPart(); // if dasextensionToMerge isn't a dasextension, ignore it if ("dasextension".equals(mergeExtTagName)) { ExtensibleElement feedDasExt = feed.getExtension(new QName(this.dasextensionNamespace, "dasextension")); if (NullChecker.isNotEmpty(feedDasExt)) { // feed contains an existing dasextension, so merge other dasextensionToMerge with it: // merge dasextension::path::parameters if none are already in feed boolean feedPathParametersExists = this.pathParametersExists(feedDasExt); boolean mergePathParametersExists = this.pathParametersExists((ExtensibleElement) dasextensionToMerge); if (false == feedPathParametersExists) { if (mergePathParametersExists) { ExtensibleElement mergePathParameters = this.getPathParameters((ExtensibleElement) dasextensionToMerge); feed = this.addPathParameters(feed, mergePathParameters); } } // merge dasextension::query::parameters if none are already in feed boolean feedQueryParametersExists = this.queryParametersExists(feedDasExt); boolean mergeQueryParametersExists = this.queryParametersExists((ExtensibleElement) dasextensionToMerge); if (false == feedQueryParametersExists) { if (mergeQueryParametersExists) { ExtensibleElement mergeQueryParameters = this.getQueryParameters((ExtensibleElement) dasextensionToMerge); feed = this.addQueryParameters(feed, mergeQueryParameters); } } // collect all of the current dasextension sites::site elements List<Element> siteElements = new ArrayList<Element>(); ExtensibleElement mergeSites = this.getSites((ExtensibleElement) dasextensionToMerge); if (NullChecker.isNotEmpty(mergeSites)) { siteElements.addAll(mergeSites.getElements()); } // add in the site elements into the feed's dasextension for (final Element siteElement : siteElements) { feed = this.addSite(feed, (ExtensibleElement) siteElement); } // collect all of the merge dasextension errors::error elements List<Element> errorElements = new ArrayList<Element>(); ExtensibleElement mergeErrors = this.getErrors((ExtensibleElement) dasextensionToMerge); if (NullChecker.isNotEmpty(mergeErrors)) { errorElements.addAll(mergeErrors.getElements()); } // add in the error elements into the feed's dasextension for (final Element errorElement : errorElements) { feed = this.addError(feed, (ExtensibleElement) errorElement); } } else { // feed has no existing dasextension element, so add in dasextensionToMerge feed.addExtension(dasextensionToMerge); } } } } return feed; }