org.apache.sling.api.resource.PersistenceException Java Examples

The following examples show how to use org.apache.sling.api.resource.PersistenceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Submit comment as ham to the Akismet servers.
 *
 * If a comment gets checked and incorrectly is reported as spam, this will
 * submit it back to the servers as ham to correct a false positive.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if submission was successful.
 */
public boolean submitHam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.SUBMIT_HAM, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, false);
            properties.put(PublickConstants.COMMENT_PROPERTY_DISPLAY, true);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #2
Source File: MapOfChildResourcesInjectorTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void roundtripEmpytTest() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    BeanWithMappedChildren source = new BeanWithMappedChildren();
    jcrPersist.persist("/test/empty-bean", source, rr);

    Resource targetResource = rr.getResource("/test/empty-bean");
    assertNotNull("Bean should have been persisted");

    Resource personRes = rr.getResource("/test/empty-bean/people");
    assertNull("Person should not have persisted in repository", personRes);

    BeanWithMappedChildren target = targetResource.adaptTo(BeanWithMappedChildren.class);
    assertNotNull("Bean should deserialize", target);

    assertEquals("Should have 0 children", 0, target.people.size());
}
 
Example #3
Source File: MapOfChildResourcesInjectorTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void roundtripTest() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    BeanWithMappedChildren source = new BeanWithMappedChildren();
    source.addPerson("joe", "schmoe");
    source.addPerson("john", "doe");
    source.addPerson("bob", "smith");
    jcrPersist.persist("/test/bean", source, rr);

    Resource targetResource = rr.getResource("/test/bean");
    assertNotNull("Bean should have been persisted");

    Resource personRes = rr.getResource("/test/bean/people/smith-bob");
    assertNotNull("Person should have persisted in repository", personRes);

    BeanWithMappedChildren target = targetResource.adaptTo(BeanWithMappedChildren.class);
    assertNotNull("Bean should deserialize", target);

    assertEquals("Should have 3 children", 3, target.people.size());
}
 
Example #4
Source File: MapOfChildResourcesInjectorTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void roundtripTestDirectChildren() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    BeanWithDirectMappedChildren source = new BeanWithDirectMappedChildren();
    source.addPerson("joe", "schmoe");
    source.addPerson("john", "doe");
    source.addPerson("bob", "smith");
    jcrPersist.persist("/test/bean", source, rr);

    Resource targetResource = rr.getResource("/test/bean");
    assertNotNull("Bean should have been persisted");

    Resource personRes = rr.getResource("/test/bean/smith-bob");
    assertNotNull("Person should have persisted in repository", personRes);

    BeanWithDirectMappedChildren target = targetResource.adaptTo(BeanWithDirectMappedChildren.class);
    assertNotNull("Bean should deserialize", target);

    assertEquals("Should have 3 children", 3, target.people.size());
}
 
Example #5
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
private static void deleteOrphanNodes(ResourceResolver resourceResolver, final String collectionRoot, Set<String> childNodes) {
    // Delete any children that are not in the list
    Resource collectionParent = resourceResolver.getResource(collectionRoot);
    if (collectionParent != null) {
        StreamSupport
                .stream(resourceResolver.getChildren(collectionParent).spliterator(), false)
                .filter(r -> !childNodes.contains(r.getPath()))
                .forEach(r -> {
                    try {
                        resourceResolver.delete(r);
                    } catch (PersistenceException ex) {
                        LOGGER.error("Unable to remove stale resource at " + r.getPath(), ex);
                    }
                });
    }
}
 
Example #6
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
private void persistCollection(final String collectionRoot, final Collection collection, ResourceResolver resourceResolver) throws PersistenceException, RepositoryException, IllegalArgumentException, IllegalAccessException {
    // now for each child in the collection - create a new node
    Set<String> childNodes = new HashSet<>();
    if (collection != null) {
        for (Object childObject : collection) {
            String childName = null;
            String childPath = getJcrPath(childObject);

            if (childPath != null) {
                childName = extractNodeNameFromPath(childPath);
            } else {
                childName = UUID.randomUUID().toString();
            }

            childPath = collectionRoot + "/" + childName;
            childNodes.add(childPath);
            persist(childPath, childObject, resourceResolver, true);
        }
    }
    deleteOrphanNodes(resourceResolver, collectionRoot, childNodes);
}
 
Example #7
Source File: MvStoreResourceProvider.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public Resource create(ResolveContext<MvSession> ctx, String path, Map<String, Object> properties)
        throws PersistenceException {
    LOG.info("CREATE  {} ", path);
    MVMap<String, Object> oldProps = store.openMap(path);
    if (oldProps.isEmpty()) {
        String parent = parentPath(path);
        MVMap<String, String[]> parentResource = store.openMap(CHILDREN);
        String[] children = parentResource.getOrDefault(parent, new String[] {});
        String[] newChildren = Arrays.copyOf(children, children.length + 1);
        newChildren[children.length] = path;
        parentResource.put(parent, newChildren);
    }
    MvValueMap data = new MvValueMap(oldProps, binaryStore);
    data.putAll(properties);
    store.commit();
    return new MvResource(ctx.getResourceResolver(), path, data);
}
 
Example #8
Source File: MvStoreResourceProvider.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public void delete(ResolveContext<MvSession> ctx, Resource resource) throws PersistenceException {
    LOG.info("DELETE  {} ", resource.getName());
    if (!(resource instanceof MvResource)) {
        throw new PersistenceException("can not delete resource of type" + resource.getClass());
    }
    MVMap<String, String[]> parentResource = store.openMap(CHILDREN);
    String parentPath = parentPath(resource.getPath());
    String[] childNames = parentResource.get(parentPath);
    String[] newChildren = new String[childNames.length - 1];
    int newIndex = 0;
    for (int index = 0; index < childNames.length; ++index) {
        if (!childNames[index].equals(resource.getName())) {
            newChildren[newIndex++] = childNames[index];
        }
    }
    parentResource.put(parentPath, newChildren);
    Deque<String> resourceToDelete = new LinkedList<>();
    resourceToDelete.add(resource.getPath());
    deleteDescendents(parentResource, resourceToDelete);
}
 
Example #9
Source File: AbstractLauncher.java    From APM with Apache License 2.0 6 votes vote down vote up
void processScript(Script script, ResourceResolver resolver, LauncherType launcherType)
    throws PersistenceException {

  final String scriptPath = script.getPath();
  try {
    if (!script.isValid()) {
      getScriptManager().process(script, ExecutionMode.VALIDATION, resolver);
    }
    if (script.isValid()) {
      final ExecutionResult result = getScriptManager().process(script, ExecutionMode.AUTOMATIC_RUN, resolver);
      logStatus(scriptPath, result.isSuccess(), launcherType);
    } else {
      logger.warn("{} launcher cannot execute script which is not valid: {}", launcherType.toString(), scriptPath);
    }
  } catch (RepositoryException e) {
    logger.error("Script cannot be processed because of repository error: {}", scriptPath, e);
  }
}
 
Example #10
Source File: ScriptRunnerJobConsumer.java    From APM with Apache License 2.0 6 votes vote down vote up
@Override
public JobResult process(final Job job) {
  LOG.info("Script runner job consumer started");
  final String id = job.getId();
  final ExecutionMode mode = getMode(job);
  final String userId = getUserId(job);
  return resolveDefault(resolverFactory, userId, (ResolveCallback<JobResult>) resolver -> {
    JobResult result = JobResult.FAILED;
    final Script script = getScript(job, resolver);
    if (script != null && mode != null) {
      try {
        ExecutionResult executionResult = scriptManager.process(script, mode, resolver);
        String summaryPath = getSummaryPath(script, mode);
        jobResultsCache.put(id, ExecutionSummary.finished(executionResult, summaryPath));
        result = JobResult.OK;
      } catch (RepositoryException | PersistenceException e) {
        LOG.error("Script manager failed to process script", e);
        result = JobResult.FAILED;
      }
    }
    return result;
  }, JobResult.FAILED);
}
 
Example #11
Source File: ScriptManagerImpl.java    From APM with Apache License 2.0 6 votes vote down vote up
@Override
public Progress process(Script script, final ExecutionMode mode, final Map<String, String> customDefinitions,
    ResourceResolver resolver) throws RepositoryException, PersistenceException {
  Progress progress;
  try {
    progress = execute(script, mode, customDefinitions, resolver);

  } catch (ExecutionException e) {
    progress = new ProgressImpl(resolver.getUserID());
    progress.addEntry(Status.ERROR, e.getMessage());
  }

  updateScriptProperties(script, mode, progress.isSuccess());
  versionService.updateVersionIfNeeded(resolver, script);
  saveHistory(script, mode, progress);
  eventManager.trigger(Event.AFTER_EXECUTE, script, mode, progress);

  return progress;
}
 
Example #12
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#setRating(org.apache.sling.api.resource.Resource, java.lang.String, int)
 */
@Override
public void setRating(final Resource resource, final String userId, final double rating)
throws PersistenceException {
    final String ratingsPath = getRatingsResourcePath(resource) ;

    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RESOURCETYPE_RATINGS);
    final Resource ratingsResource = ResourceUtil.getOrCreateResource(resource.getResourceResolver(),
            ratingsPath, props, null, true);

    final Resource ratingRsrc = resource.getResourceResolver().getResource(ratingsResource, userId);
    if ( ratingRsrc == null ) {
        props.clear();
        props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RatingsUtil.RESOURCETYPE_RATING);
        props.put(RatingsUtil.PROPERTY_RATING, String.valueOf(rating));

        resource.getResourceResolver().create(ratingsResource, userId, props);
    } else {
        final ModifiableValueMap mvm = ratingRsrc.adaptTo(ModifiableValueMap.class);
        mvm.put(RatingsUtil.PROPERTY_RATING, String.valueOf(rating));
    }
    resource.getResourceResolver().commit();
}
 
Example #13
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Submit comment as spam to the Akismet servers.
 *
 * If a comment gets checked and incorrectly is reported as ham, this will
 * submit it back to the servers as spam to help make the world a better
 * place.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if submission was successful.
 */
public boolean submitSpam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.SUBMIT_SPAM, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, true);
            properties.put(PublickConstants.COMMENT_PROPERTY_DISPLAY, false);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #14
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Check comment against Akismet servers.
 *
 * Be aware that this method returns whether the submission is spam or not.
 * A false response means that the submission was successful and that the
 * comment is not spam. This behavior is inline with Akismet's behavior.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if comment is spam, false if comment is valid.
 */
public boolean isSpam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.CHECK_COMMENT, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, true);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #15
Source File: HistoryImpl.java    From APM with Apache License 2.0 6 votes vote down vote up
private HistoryEntry createHistoryEntry(ResourceResolver resolver, Script script, ExecutionMode mode,
    HistoryEntryWriter historyEntryWriter, boolean remote) {
  try {
    Session session = resolver.adaptTo(Session.class);

    Node scriptHistoryNode = createScriptHistoryNode(script, session);
    Node historyEntryNode = createHistoryEntryNode(scriptHistoryNode, script, mode, remote);
    historyEntryNode.setProperty(HistoryEntryImpl.SCRIPT_CONTENT_PATH, versionService.getVersionPath(script));
    writeProperties(resolver, historyEntryNode, historyEntryWriter);

    session.save();
    resolver.commit();
    return resolver.getResource(historyEntryNode.getPath()).adaptTo(HistoryEntryImpl.class);
  } catch (PersistenceException | RepositoryException e) {
    LOG.error("Issues with saving to repository while logging script execution", e);
    return null;
  }
}
 
Example #16
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
/**
 * Test named map children with map<String, Object>
 *
 */
public void testMapChildrenWithStringKeys() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    // Create some values in the Map<String, Object> data structure
    MappedChildren bean = new MappedChildren();
    MappedChildren.Child child1 = new MappedChildren.Child();
    bean.stringKeys.put("one", child1);
    MappedChildren.Child child2 = new MappedChildren.Child();
    bean.stringKeys.put("two", child2);
    MappedChildren.Child child3 = new MappedChildren.Child();
    bean.stringKeys.put("three", child3);
    child1.name = "one";
    child1.testValue = "Test Value 1";
    child2.name = "two";
    child2.testValue = "Test Value 2";
    child3.name = "three";
    child3.testValue = "Test Value 3";

    // Attempt to save the data structure
    jcrPersist.persist("/test/path", bean, rr);

    // Confirm the children were saved in the expected places using the map key as the node name
    Resource r1 = rr.getResource("/test/path/stringKeys/one");
    assertNotNull("/test/path/stringKeys/one should not be null", r1);
    Resource r2 = rr.getResource("/test/path/stringKeys/two");
    assertNotNull("/test/path/stringKeys/two should not be null", r2);
    Resource r3 = rr.getResource("/test/path/stringKeys/three");
    assertNotNull("/test/path/stringKeys/three should not be null", r3);
}
 
Example #17
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private <K, V> void persistMap(final String collectionRoot, final Map<K, V> collection, ResourceResolver resourceResolver) throws PersistenceException, RepositoryException, IllegalArgumentException, IllegalAccessException {
    // now for each child in the collection - create a new node
    Set<String> childNodes = new HashSet<>();
    if (collection != null) {
        for (Map.Entry<K, V> childObject : collection.entrySet()) {
            String childName = String.valueOf(childObject.getKey());
            String childPath = collectionRoot + "/" + childName;
            childNodes.add(childPath);
            persist(childPath, childObject.getValue(), resourceResolver, true);
        }
    }
    deleteOrphanNodes(resourceResolver, collectionRoot, childNodes);
}
 
Example #18
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void persistField(@NotNull Resource resource, @NotNull Object instance, Field field, boolean deepPersist) {
    try {
        // read the existing resource map
        ModifiableValueMap values = resource.adaptTo(ModifiableValueMap.class);
        String nodePath = resource.getPath();

        // find the type of field
        final Class<?> fieldType = field.getType();
        final String fieldName = ReflectionUtils.getFieldName(field);

        // set accessible
        field.setAccessible(true);

        // handle the value as primitive first
        if (ReflectionUtils.isPrimitiveFieldType(fieldType) || ReflectionUtils.isCollectionOfPrimitiveType(field)) {

            Object value = ReflectionUtils.getStorableValue(field.get(instance));

            // remove the attribute that is null, or remove in case it changes type
            values.remove(fieldName);
            if (value != null) {
                values.put(fieldName, value);
            }
        } else if (deepPersist) {
            boolean directDescendents = field.getAnnotation(DirectDescendants.class) != null;
            persistComplexValue(field.get(instance), directDescendents, fieldName, resource);
        }
    } catch (IllegalAccessException | RepositoryException | PersistenceException ex) {
        LOGGER.error("Error when persisting content to " + resource.getPath(), ex);
    }
}
 
Example #19
Source File: ProductBindingCreatorTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateBindingWhenConfigurationIsCreated() throws WCMException, PersistenceException {
    Assert.assertNotNull(context.resourceResolver().getResource("/conf/testing/settings/cloudconfigs"));

    ResourceChange change = new ResourceChange(ResourceChange.ChangeType.ADDED, "/conf/testing/settings/cloudconfigs/commerce", false);

    creator.onChange(ImmutableList.of(change));

    Assert.assertNotNull(context.resourceResolver().getResource("/var/commerce/products/testing-english"));

    // Test that the cq:catalogPath property was added to the configuration
    Resource config = context.resourceResolver().getResource("/conf/testing/settings/cloudconfigs/commerce/jcr:content");
    Assert.assertEquals("/var/commerce/products/testing-english", config.getValueMap().get("cq:catalogPath"));
}
 
Example #20
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm that content is written to correct path indicated by either path
 * field, path getter, or path annotation.Also asserts that path annotation
 * takes precedence over any field or getter method.
 *
 * @throws javax.jcr.RepositoryException
 * @throws org.apache.sling.api.resource.PersistenceException
 * @throws java.lang.IllegalAccessException
 */
@Test
public void testPersistBeanPath() throws RepositoryException, PersistenceException, IllegalAccessException {
    BeanWithPathGetter bean1 = new BeanWithPathGetter();
    jcrPersist.persist(bean1, rr, false);
    Resource res = rr.getResource(bean1.getPath());
    assertNotNull("Resource not created at expected path", res);
    assertEquals("Expected property not found", bean1.prop1, res.getValueMap().get("prop1", "missing"));

    BeanWithPathField bean2 = new BeanWithPathField();
    jcrPersist.persist(bean2, rr, false);
    res = rr.getResource(bean2.path + "/jcr:content");
    assertNotNull("Resource not created at expected path", res);
    assertEquals("Expected property not found", bean2.prop1, res.getValueMap().get("prop1", "missing"));

    BeanWithAnnotatedPathField bean3 = new BeanWithAnnotatedPathField();
    jcrPersist.persist(bean3, rr);
    res = rr.getResource(bean3.correctPath);
    assertNotNull("Resource not created at expected path", res);
    assertEquals("Expected property not found", bean3.prop1, res.getValueMap().get("prop1", "missing"));

    BeanWithAnnotatedPathGetter bean4 = new BeanWithAnnotatedPathGetter();
    jcrPersist.persist(bean4, rr, true);
    res = rr.getResource(bean4.getCorrectPath());
    assertNotNull("Resource not created at expected path", res);
    assertEquals("Expected property not found", bean4.prop1, res.getValueMap().get("prop1", "missing"));
}
 
Example #21
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm that content is persisted at provided path even if it has a path
 * annotation or path getter, etc.
 *
 * @throws javax.jcr.RepositoryException
 * @throws org.apache.sling.api.resource.PersistenceException
 * @throws java.lang.IllegalAccessException
 */
@Test
public void testPersistProvidedPath() throws RepositoryException, PersistenceException, IllegalAccessException {
    String testPath = "/manual/path";
    BeanWithAnnotatedPathField bean = new BeanWithAnnotatedPathField();
    jcrPersist.persist(testPath, bean, rr, false);
    Resource res = rr.getResource(bean.correctPath);
    assertNull("Should not have stored content here", res);
    res = rr.getResource(testPath);
    assertNotNull("Resource not created at expected path", res);
    assertEquals("Expected property not found", bean.prop1, res.getValueMap().get("prop1", "missing"));
}
 
Example #22
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexObjectGraph() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    // First create a bean with a complex structure and various object types buried in it
    ComplexBean sourceBean = new ComplexBean();
    sourceBean.name = "Complex-bean-test";
    sourceBean.arrayOfStrings = new String[]{"Value 1", "Value 2", "Value 3"};
    sourceBean.listOfStrings = Arrays.asList(sourceBean.arrayOfStrings);
    sourceBean.level2.name = "Complex-bean-level2";
    ComplexBean.Level3Bean l31 = new ComplexBean.Level3Bean();
    l31.value1 = "L3-1";
    l31.value2 = 123;
    l31.valueList = new String[]{"L31a", "L31b", "L31c", "L31d"};
    ComplexBean.Level3Bean l32 = new ComplexBean.Level3Bean();
    l32.value1 = "L3-2";
    l32.value2 = 456;
    l32.valueList = new String[]{"L32a", "L32b", "L32c", "L32d"};
    l32.path = "/test/complex-beans/Complex-bean-test/level2/level3/child-2";
    sourceBean.level2.level3.add(l31);
    sourceBean.level2.level3.add(l32);

    // Persist the bean
    jcrPersist.persist(sourceBean.getPath(), sourceBean, rr);

    // Now retrieve that object from the repository
    rr.refresh();
    Resource createdResource = rr.getResource(sourceBean.getPath());
    ComplexBean targetBean = createdResource.adaptTo(ComplexBean.class);

    assertNotNull(targetBean);
    assertNotEquals(sourceBean, targetBean);
    assertTrue("Expecing children of object to have been deserialized", targetBean.level2.level3 != null && targetBean.level2.level3.size() > 0);
    targetBean.level2.level3.get(0).path = l31.path;
    assertThat(targetBean).isEqualToComparingFieldByFieldRecursively(sourceBean);
}
 
Example #23
Source File: HistoryAutocleanService.java    From APM with Apache License 2.0 5 votes vote down vote up
private void deleteItem(ResourceResolver resolver, Resource resource) {
  try {
    log.info("Deleting: {}", resource.getPath());
    resolver.delete(resource);
  } catch (PersistenceException e) {
    throw new RuntimeException(e);
  }
}
 
Example #24
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public Script save(String fileName, InputStream input, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) throws RepositoryException, PersistenceException {

  FileDescriptor fileDescriptor = FileDescriptor.createFileDescriptor(fileName, getSavePath(), input);

  validate(Collections.singletonList(fileDescriptor));

  Script script = saveScript(fileDescriptor, launchMetadata, overwrite, resolver);
  scriptManager.process(script, ExecutionMode.VALIDATION, resolver);
  scriptManager.getEventManager().trigger(Event.AFTER_SAVE, script);
  return script;
}
 
Example #25
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
/**
 * Test named map children with map<String, Object>
 *
 */
public void testMapChildrenWithEnumerationKeys() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    // Do same thing except using enumKeys map on the bean object
    // e.g. --> bean.enumKeys.put(MappedChildren.KEYS.ONE, child1);

    // Create some values in the Map<String, Object> data structure
    MappedChildren bean = new MappedChildren();
    MappedChildren.Child child1 = new MappedChildren.Child();
    bean.enumKeys.put(MappedChildren.KEYS.ONE, child1);
    MappedChildren.Child child2 = new MappedChildren.Child();
    bean.enumKeys.put(MappedChildren.KEYS.TWO, child2);
    MappedChildren.Child child3 = new MappedChildren.Child();
    bean.enumKeys.put(MappedChildren.KEYS.THREE, child3);
    child1.name = "one";
    child1.testValue = "Test Value 1";
    child2.name = "two";
    child2.testValue = "Test Value 2";
    child3.name = "three";
    child3.testValue = "Test Value 3";

    // Attempt to save the data structure
    jcrPersist.persist("/test/path", bean, rr);

    // Confirm the children were saved in the expected places using the map key as the node name
    Resource r1 = rr.getResource("/test/path/enumKeys/ONE");
    assertNotNull(r1);
    Resource r2 = rr.getResource("/test/path/enumKeys/TWO");
    assertNotNull(r2);
    Resource r3 = rr.getResource("/test/path/enumKeys/THREE");
    assertNotNull(r3);
}
 
Example #26
Source File: ResourceResolverImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(Resource resource) throws PersistenceException {
    try {
        session.removeItem(resource.getPath());
    }
    catch (RepositoryException e) {
        throw new PersistenceException("Could not delete " + resource.getPath(), e);
    }
}
 
Example #27
Source File: ScriptManagerImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private void updateScriptProperties(final Script script, final ExecutionMode mode, final boolean success)
    throws PersistenceException {

  final MutableScriptWrapper mutableScriptWrapper = new MutableScriptWrapper(script);

  if (Arrays.asList(ExecutionMode.RUN, ExecutionMode.AUTOMATIC_RUN).contains(mode)) {
    mutableScriptWrapper.setExecuted(true);
  }

  if (ExecutionMode.VALIDATION.equals(mode)) {
    mutableScriptWrapper.setValid(success);
  }
}
 
Example #28
Source File: AbstractLauncher.java    From APM with Apache License 2.0 5 votes vote down vote up
void processScripts(List<Script> scripts, ResourceResolver resolver, LauncherType launcherType)
    throws PersistenceException {

  if (!scripts.isEmpty()) {
    logger.info("Launcher will try to run following scripts: {}", scripts.size());
    logger.info(MessagingUtils.describeScripts(scripts));
    for (Script script : scripts) {
      processScript(script, resolver, launcherType);
    }
  }
}
 
Example #29
Source File: ReplicatedScriptLauncher.java    From APM with Apache License 2.0 5 votes vote down vote up
private JobResult runReplicated(ResourceResolver resolver, Script script) {
  JobResult result = JobResult.FAILED;

  if (LaunchMode.ON_DEMAND.equals(script.getLaunchMode()) && script.isPublishRun()) {
    try {
      processScript(script, resolver, LauncherType.REPLICATED);
      result = JobResult.OK;
    } catch (PersistenceException e) {
      logger.error(e.getMessage(), e);
    }
  }
  return result;
}
 
Example #30
Source File: ScriptModel.java    From APM with Apache License 2.0 5 votes vote down vote up
private void setProperty(String name, Object value) throws PersistenceException {
  ModifiableValueMap vm = resource.adaptTo(ModifiableValueMap.class);
  ResourceMixinUtil.addMixin(vm, ScriptNode.APM_SCRIPT);
  vm.put(name, convertValue(value));

  resource.getResourceResolver().commit();
}