use of org.apache.sling.api.resource.PersistenceException in project sling by apache.
the class StreamingUploadOperationTest method testParts.
@Test
public void testParts() throws PersistenceException, RepositoryException, UnsupportedEncodingException {
List<Modification> changes = new ArrayList<>();
PostResponse response = new AbstractPostResponse() {
@Override
protected void doSend(HttpServletResponse response) throws IOException {
}
@Override
public void onChange(String type, String... arguments) {
}
@Override
public String getPath() {
return "/test/upload/location";
}
};
List<Part> partsList = new ArrayList<>();
partsList.add(new MockPart("test1.txt@Length", null, null, 0, new ByteArrayInputStream("8".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("test1.txt@Offset", null, null, 0, new ByteArrayInputStream("0".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("test".getBytes("UTF-8")), mapOf("Content-Length", "4")));
partsList.add(new MockPart("test1.txt@Offset", null, null, 0, new ByteArrayInputStream("4".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("part".getBytes("UTF-8")), mapOf("Content-Length", "4")));
partsList.add(new MockPart("*", "text/plain2", "test2.txt", 8, new ByteArrayInputStream("test1234".getBytes("UTF-8")), Collections.EMPTY_MAP));
partsList.add(new MockPart("badformfield2", null, null, 0, new ByteArrayInputStream("testbadformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
final Iterator<Part> partsIterator = partsList.iterator();
final Map<String, Resource> repository = new HashMap<>();
final ResourceResolver resourceResolver = new MockResourceResolver() {
@Override
public Resource getResource(String path) {
Resource resource = repository.get(path);
if (resource == null) {
if ("/test/upload/location".equals(path)) {
resource = new MockRealResource(this, path, "sling:Folder");
repository.put(path, resource);
LOG.debug("Created {} ", path);
}
}
LOG.debug("Resource {} is {} {}", path, resource, ResourceUtil.isSyntheticResource(resource));
return resource;
}
@Override
public Iterable<Resource> getChildren(Resource resource) {
List<Resource> children = new ArrayList<>();
for (Map.Entry<String, Resource> e : repository.entrySet()) {
if (isChild(resource.getPath(), e.getKey())) {
children.add(e.getValue());
}
}
return children;
}
private boolean isChild(String path, String key) {
if (key.length() > path.length() && key.startsWith(path)) {
return !key.substring(path.length() + 1).contains("/");
}
return false;
}
@Override
public Iterator<Resource> listChildren(Resource parent) {
return getChildren(parent).iterator();
}
@Override
public void delete(Resource resource) throws PersistenceException {
}
@Override
public Resource create(Resource resource, String s, Map<String, Object> map) throws PersistenceException {
Resource childResource = resource.getChild(s);
if (childResource != null) {
throw new IllegalArgumentException("Child " + s + " already exists ");
}
String resourceType = (String) map.get("sling:resourceType");
if (resourceType == null) {
resourceType = (String) map.get("jcr:primaryType");
}
if (resourceType == null) {
LOG.warn("Resource type null for {} {} ", resource, resource.getPath() + "/" + s);
}
Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, resourceType, map);
repository.put(newResource.getPath(), newResource);
LOG.debug("Created Resource {} ", newResource.getPath());
return newResource;
}
@Override
public void revert() {
}
@Override
public void commit() throws PersistenceException {
LOG.debug("Committing");
for (Map.Entry<String, Resource> e : repository.entrySet()) {
LOG.debug("Committing {} ", e.getKey());
Resource r = e.getValue();
ModifiableValueMap vm = r.adaptTo(ModifiableValueMap.class);
for (Map.Entry<String, Object> me : vm.entrySet()) {
if (me.getValue() instanceof InputStream) {
try {
String value = IOUtils.toString((InputStream) me.getValue());
LOG.debug("Converted {} {} ", me.getKey(), value);
vm.put(me.getKey(), value);
} catch (IOException e1) {
throw new PersistenceException("Failed to commit input stream", e1);
}
}
}
LOG.debug("Converted {} ", vm);
}
LOG.debug("Comittted {} ", repository);
}
@Override
public boolean hasChanges() {
return false;
}
};
SlingHttpServletRequest request = new MockSlingHttpServlet3Request(null, null, null, null, null) {
@Override
public Object getAttribute(String name) {
if ("request-parts-iterator".equals(name)) {
return partsIterator;
}
return super.getAttribute(name);
}
@Override
public ResourceResolver getResourceResolver() {
return resourceResolver;
}
};
streamedUplodOperation.doRun(request, response, changes);
{
Resource r = repository.get("/test/upload/location/test1.txt");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
}
{
Resource r = repository.get("/test/upload/location/test1.txt/jcr:content");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
Assert.assertEquals("text/plain", m.get("jcr:mimeType"));
Assert.assertEquals("testpart", m.get("jcr:data"));
}
{
Resource r = repository.get("/test/upload/location/test2.txt");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
}
{
Resource r = repository.get("/test/upload/location/test2.txt/jcr:content");
Assert.assertNotNull(r);
ValueMap m = r.adaptTo(ValueMap.class);
Assert.assertNotNull(m);
Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
Assert.assertEquals("text/plain2", m.get("jcr:mimeType"));
Assert.assertEquals("test1234", m.get("jcr:data"));
}
}
use of org.apache.sling.api.resource.PersistenceException in project sling by apache.
the class AbstractCreateOperation method generateName.
protected String generateName(SlingHttpServletRequest request, String basePath) throws PersistenceException {
// SLING-1091: If a :name parameter is supplied, the (first) value of this parameter is used unmodified as the name
// for the new node. If the name is illegally formed with respect to JCR name requirements, an exception will be
// thrown when trying to create the node. The assumption with the :name parameter is, that the caller knows what
// he (or she) is supplying and should get the exact result if possible.
RequestParameterMap parameters = request.getRequestParameterMap();
RequestParameter specialParam = parameters.getValue(SlingPostConstants.RP_NODE_NAME);
if (specialParam != null) {
if (specialParam.getString() != null && specialParam.getString().length() > 0) {
// If the path ends with a *, create a node under its parent, with
// a generated node name
basePath = basePath += "/" + specialParam.getString();
// if the resulting path already exists then report an error
if (request.getResourceResolver().getResource(basePath) != null) {
throw new PersistenceException("Collision in node names for path=" + basePath);
}
return basePath;
}
}
// no :name value was supplied, so generate a name
boolean requirePrefix = requireItemPathPrefix(request);
String generatedName = null;
if (extraNodeNameGenerators != null) {
for (NodeNameGenerator generator : extraNodeNameGenerators) {
generatedName = generator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
if (generatedName != null) {
break;
}
}
}
if (generatedName == null) {
generatedName = defaultNodeNameGenerator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
}
// If the path ends with a *, create a node under its parent, with
// a generated node name
basePath += "/" + generatedName;
basePath = ensureUniquePath(request, basePath);
return basePath;
}
use of org.apache.sling.api.resource.PersistenceException in project sling by apache.
the class AbstractCreateOperation method ensureUniquePath.
/** Generate a unique path in case the node name generator didn't */
private String ensureUniquePath(SlingHttpServletRequest request, String basePath) throws PersistenceException {
// if resulting path exists, add a suffix until it's not the case
// anymore
final ResourceResolver resolver = request.getResourceResolver();
// if resulting path exists, add a random suffix until it's not the case
// anymore
final int MAX_TRIES = 1000;
if (resolver.getResource(basePath) != null) {
for (int i = 0; i < MAX_TRIES; i++) {
final int uniqueIndex = Math.abs(randomCollisionIndex.nextInt());
String newPath = basePath + "_" + uniqueIndex;
if (resolver.getResource(newPath) == null) {
basePath = basePath + "_" + uniqueIndex;
basePath = newPath;
break;
}
}
// Give up after MAX_TRIES
if (resolver.getResource(basePath) != null) {
throw new PersistenceException("Collision in generated node names under " + basePath + ", generated path " + basePath + " already exists");
}
}
return basePath;
}
use of org.apache.sling.api.resource.PersistenceException in project sling by apache.
the class CheckinOperation method doRun.
@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
try {
Iterator<Resource> res = getApplyToResources(request);
if (res == null) {
Resource resource = request.getResource();
Node node = resource.adaptTo(Node.class);
if (node == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing source " + resource + " for checkout");
return;
}
node.getSession().getWorkspace().getVersionManager().checkin(node.getPath());
changes.add(Modification.onCheckin(resource.getPath()));
} else {
while (res.hasNext()) {
Resource resource = res.next();
Node node = resource.adaptTo(Node.class);
if (node != null) {
node.getSession().getWorkspace().getVersionManager().checkin(node.getPath());
changes.add(Modification.onCheckin(resource.getPath()));
}
}
}
} catch (final RepositoryException re) {
throw new PersistenceException(re.getMessage(), re);
}
}
use of org.apache.sling.api.resource.PersistenceException in project sling by apache.
the class RestoreOperation method doRun.
@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
try {
final String version = request.getParameter(SlingPostConstants.RP_VERSION);
if (version == null || version.length() == 0) {
throw new IllegalArgumentException("Unable to process restore. Missing version");
}
final String removeString = request.getParameter(SlingPostConstants.RP_REMOVE_EXISTING);
final boolean removeExisting = Boolean.parseBoolean(removeString);
Iterator<Resource> res = getApplyToResources(request);
if (res == null) {
Resource resource = request.getResource();
Node node = resource.adaptTo(Node.class);
if (node == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing source " + resource + " for restore");
return;
}
restore(node, version, removeExisting);
changes.add(Modification.onRestore(resource.getPath(), version));
} else {
while (res.hasNext()) {
Resource resource = res.next();
Node node = resource.adaptTo(Node.class);
if (node != null) {
restore(node, version, removeExisting);
changes.add(Modification.onRestore(resource.getPath(), version));
}
}
}
} catch (final RepositoryException re) {
throw new PersistenceException(re.getMessage(), re);
}
}
Aggregations