use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.
the class MockedResource method adaptTo.
@SuppressWarnings("unchecked")
@Override
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
if (type.equals(Node.class)) {
try {
return (AdapterType) getSession().getNode(getPath());
} catch (Exception e) {
logger.error("Exception occurred: " + e, e);
throw new RuntimeException("Exception occurred: " + e, e);
}
} else if (type.equals(ValueMap.class)) {
try {
Session session = getSession();
Node node = session.getNode(getPath());
HashMap<String, Object> map = new HashMap<String, Object>();
PropertyIterator properties = node.getProperties();
while (properties.hasNext()) {
Property p = properties.nextProperty();
if (p.getType() == PropertyType.BOOLEAN) {
map.put(p.getName(), p.getBoolean());
} else if (p.getType() == PropertyType.STRING) {
map.put(p.getName(), p.getString());
} else if (p.getType() == PropertyType.DATE) {
map.put(p.getName(), p.getDate().getTime());
} else if (p.getType() == PropertyType.NAME) {
map.put(p.getName(), p.getName());
} else if (p.getType() == PropertyType.LONG) {
map.put(p.getName(), p.getLong());
} else {
throw new RuntimeException("Unsupported property type: " + p.getType());
}
}
ValueMap valueMap = new ValueMapDecorator(map);
return (AdapterType) valueMap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else if (type.equals(ModifiableValueMap.class)) {
return (AdapterType) new ModifiableValueMap() {
public Collection<Object> values() {
throw new UnsupportedOperationException();
}
public int size() {
throw new UnsupportedOperationException();
}
public Object remove(Object arg0) {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
final Property p = node.getProperty(String.valueOf(arg0));
if (p != null) {
p.remove();
}
// the return value is never used
return null;
} catch (PathNotFoundException pnfe) {
// perfectly fine
return null;
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
public void putAll(Map<? extends String, ? extends Object> arg0) {
throw new UnsupportedOperationException();
}
public Object put(String arg0, Object arg1) {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
Object result = null;
if (node.hasProperty(arg0)) {
final Property previous = node.getProperty(arg0);
if (previous == null) {
// null
} else if (previous.getType() == PropertyType.STRING) {
result = previous.getString();
} else if (previous.getType() == PropertyType.DATE) {
result = previous.getDate();
} else if (previous.getType() == PropertyType.BOOLEAN) {
result = previous.getBoolean();
} else {
throw new UnsupportedOperationException();
}
}
if (arg1 instanceof String) {
node.setProperty(arg0, (String) arg1);
} else if (arg1 instanceof Calendar) {
node.setProperty(arg0, (Calendar) arg1);
} else if (arg1 instanceof Boolean) {
node.setProperty(arg0, (Boolean) arg1);
} else if (arg1 instanceof Date) {
final Calendar c = Calendar.getInstance();
c.setTime((Date) arg1);
node.setProperty(arg0, c);
} else if (arg1 instanceof Number) {
Number n = (Number) arg1;
node.setProperty(arg0, n.longValue());
} else {
throw new UnsupportedOperationException();
}
return result;
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
public Set<String> keySet() {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
final PropertyIterator pi = node.getProperties();
final Set<String> result = new HashSet<String>();
while (pi.hasNext()) {
final Property p = pi.nextProperty();
result.add(p.getName());
}
return result;
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public Object get(Object arg0) {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
final String key = String.valueOf(arg0);
if (node.hasProperty(key)) {
return node.getProperty(key);
} else {
return null;
}
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
}
public Set<Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException();
}
public boolean containsValue(Object arg0) {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object arg0) {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
return node.hasProperty(String.valueOf(arg0));
} catch (RepositoryException re) {
throw new RuntimeException(re);
}
}
public void clear() {
throw new UnsupportedOperationException();
}
public <T> T get(String name, T defaultValue) {
throw new UnsupportedOperationException();
}
public <T> T get(String name, Class<T> type) {
Session session = getSession();
try {
final Node node = session.getNode(getPath());
if (node == null) {
return null;
}
if (!node.hasProperty(name)) {
return null;
}
Property p = node.getProperty(name);
if (p == null) {
return null;
}
if (type.equals(Calendar.class)) {
return (T) p.getDate();
} else if (type.equals(String.class)) {
return (T) p.getString();
} else {
throw new UnsupportedOperationException();
}
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
};
} else {
return super.adaptTo(type);
}
}
use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.
the class VotingHandler method promote.
/**
* Promote a particular voting to be the new established view
*/
private void promote(final ResourceResolver resourceResolver, final Resource winningVoteResource) throws PersistenceException {
Resource previousViewsResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getPreviousViewPath());
final Resource establishedViewsResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getEstablishedViewPath());
final Resource ongoingVotingsResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getOngoingVotingsPath());
if (logger.isDebugEnabled()) {
logger.debug("promote: previousViewsResource=" + previousViewsResource.getPath());
logger.debug("promote: establishedViewsResource=" + establishedViewsResource.getPath());
logger.debug("promote: ongoingVotingsResource=" + ongoingVotingsResource.getPath());
logger.debug("promote: winningVoteResource=" + winningVoteResource.getPath());
}
// step 1: remove any nodes under previousViews
final Iterator<Resource> it1 = previousViewsResource.getChildren().iterator();
try {
while (it1.hasNext()) {
Resource previousView = it1.next();
resourceResolver.delete(previousView);
}
} catch (PersistenceException e) {
// if we cannot delete, apply workaround suggested in SLING-3785
logger.error("promote: Could not delete a previous view - trying move next: " + e, e);
ResourceHelper.moveResource(previousViewsResource, config.getPreviousViewPath() + "_trash_" + UUID.randomUUID().toString());
logger.info("promote: recreating the previousviews node");
previousViewsResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getPreviousViewPath());
}
// step 2: retire the existing established view.
// Note that there must always only be one. But if there's more, retire
// them all now.
final Iterator<Resource> it = establishedViewsResource.getChildren().iterator();
boolean first = true;
while (it.hasNext()) {
Resource retiredView = it.next();
if (first) {
first = !first;
if (logger.isDebugEnabled()) {
logger.debug("promote: moving the old established view to previous views: " + retiredView.getPath());
}
ResourceHelper.moveResource(retiredView, previousViewsResource.getPath() + "/" + retiredView.getName());
} else {
if (logger.isDebugEnabled()) {
logger.debug("promote: retiring an erroneously additionally established node " + retiredView.getPath());
}
resourceResolver.delete(retiredView);
}
}
// step 3: move the winning vote resource under the
// establishedViewsResource
// 3a: set the leaderid
final Iterator<Resource> it2 = winningVoteResource.getChild("members").getChildren().iterator();
String leaderElectionId = null;
String leaderid = null;
int membersCount = 0;
while (it2.hasNext()) {
Resource aMember = it2.next();
membersCount++;
String leid = aMember.adaptTo(ValueMap.class).get("leaderElectionId", String.class);
if (leaderElectionId == null || (leid != null && leid.compareTo(leaderElectionId) < 0)) {
leaderElectionId = leid;
leaderid = aMember.getName();
}
}
if (logger.isDebugEnabled()) {
logger.debug("promote: leader is " + leaderid + " - with leaderElectionId=" + leaderElectionId);
}
ModifiableValueMap winningVoteMap = winningVoteResource.adaptTo(ModifiableValueMap.class);
winningVoteMap.put("leaderId", leaderid);
winningVoteMap.put("leaderElectionId", leaderElectionId);
winningVoteMap.put("promotedAt", Calendar.getInstance());
winningVoteMap.put("promotedBy", slingId);
// 3b: move the result under /established
final String newEstablishedViewPath = establishedViewsResource.getPath() + "/" + winningVoteResource.getName();
logger.info("promote: promoting to new established node (#members: " + membersCount + ", path: " + newEstablishedViewPath + ")");
ResourceHelper.moveResource(winningVoteResource, newEstablishedViewPath);
// step 4: delete all ongoing votings...
final Iterable<Resource> ongoingVotingsChildren = ongoingVotingsResource.getChildren();
if (ongoingVotingsChildren != null) {
Iterator<Resource> it4 = ongoingVotingsChildren.iterator();
while (it4.hasNext()) {
Resource anOngoingVoting = it4.next();
logger.info("promote: deleting ongoing voting: " + anOngoingVoting.getName());
resourceResolver.delete(anOngoingVoting);
}
}
// step 5: make sure there are no duplicate ongoingVotings nodes
// created. if so, cleanup
final Iterator<Resource> it5 = ongoingVotingsResource.getParent().getChildren().iterator();
while (it5.hasNext()) {
Resource resource = it5.next();
if (!resource.getPath().startsWith(config.getOngoingVotingsPath())) {
continue;
}
if (resource.getPath().equals(config.getOngoingVotingsPath())) {
// then it's [0] so to speak .. which we're not cleaning up
continue;
}
logger.warn("promote: cleaning up a duplicate ongoingVotingPath: " + resource.getPath());
resourceResolver.delete(resource);
}
logger.debug("promote: done with promotiong. saving.");
resourceResolver.commit();
logger.info("promote: promotion done (#members: " + membersCount + ", path: " + newEstablishedViewPath + ")");
}
use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.
the class JcrModifiableValueMapTest method testStreams.
public void testStreams() throws Exception {
final ModifiableValueMap pvm = new JcrModifiableValueMap(this.rootNode, getHelperData());
InputStream stream = new ByteArrayInputStream(TEST_BYTE_ARRAY);
pvm.put("binary", stream);
getSession().save();
final ModifiableValueMap modifiableValueMap2 = new JcrModifiableValueMap(this.rootNode, getHelperData());
assertTrue("The read stream is not what we wrote.", IOUtils.toString(modifiableValueMap2.get("binary", InputStream.class)).equals(TEST_BYTE_ARRAY_TO_STRING));
}
use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.
the class JcrModifiableValueMapTest method testExceptions.
public void testExceptions() throws Exception {
this.rootNode.getSession().refresh(false);
final ModifiableValueMap pvm = new JcrModifiableValueMap(this.rootNode, getHelperData());
try {
pvm.put(null, "something");
fail("Put with null key");
} catch (NullPointerException iae) {
}
try {
pvm.put("something", null);
fail("Put with null value");
} catch (NullPointerException iae) {
}
try {
pvm.put("something", pvm);
fail("Put with non serializable");
} catch (IllegalArgumentException iae) {
}
}
use of org.apache.sling.api.resource.ModifiableValueMap in project sling by apache.
the class JcrModifiableValueMapTest method testNamesReverse.
public void testNamesReverse() throws Exception {
this.rootNode.getSession().refresh(false);
final Node testNode = this.rootNode.addNode("nameTest" + System.currentTimeMillis());
testNode.getSession().save();
final ModifiableValueMap pvm = new JcrModifiableValueMap(testNode, getHelperData());
pvm.put(TEST_PATH, VALUE);
pvm.put(PROP1, VALUE1);
pvm.put(PROP2, VALUE2);
pvm.put(PROP3, VALUE3);
getSession().save();
// read with property map
final ValueMap vm = new JcrModifiableValueMap(testNode, getHelperData());
assertEquals(VALUE, vm.get(TEST_PATH));
assertEquals(VALUE1, vm.get(PROP1));
assertEquals(VALUE2, vm.get(PROP2));
assertEquals(VALUE3, vm.get(PROP3));
// read properties
assertEquals(VALUE, testNode.getProperty(TEST_PATH).getString());
assertEquals(VALUE1, testNode.getProperty(PROP1).getString());
assertEquals(VALUE2, testNode.getProperty(PROP2).getString());
assertEquals(VALUE3, testNode.getProperty(PROP3).getString());
}
Aggregations