Example #1
0
  @Override
  public InputStream getFileAsStream(
      long companyId, long repositoryId, String fileName, String versionLabel)
      throws PortalException, SystemException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Node contentNode =
          getFileContentNode(session, companyId, repositoryId, fileName, versionLabel);

      Property property = contentNode.getProperty(JCRConstants.JCR_DATA);

      Value value = property.getValue();

      Binary binary = value.getBinary();

      if ((session instanceof Map)) {
        Map<String, Binary> mapSession = (Map<String, Binary>) session;

        mapSession.put(fileName, binary);
      }

      return binary.getStream();
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
  private void persistBinaryContent(JcrRepository repository)
      throws RepositoryException, IOException {
    assertNotNull(repository);

    long minimumBinarySize =
        repository.getConfiguration().getBinaryStorage().getMinimumBinarySizeInBytes();
    long binarySize = minimumBinarySize + 1;

    Session session = repository.login();
    InputStream binaryValueStream = null;
    try {
      byte[] content = new byte[(int) binarySize];
      new Random().nextBytes(content);
      JCR_TOOLS.uploadFile(session, "folder/file", new ByteArrayInputStream(content));
      session.save();

      Node nodeWithBinaryContent = session.getNode("/folder/file/jcr:content");
      Binary binaryValue = nodeWithBinaryContent.getProperty("jcr:data").getBinary();
      binaryValueStream = binaryValue.getStream();
      byte[] retrievedContent = IoUtil.readBytes(binaryValueStream);
      assertArrayEquals(content, retrievedContent);
    } finally {
      if (binaryValueStream != null) {
        binaryValueStream.close();
      }
      session.logout();
    }
  }
Example #3
0
  @Override
  public boolean execute(Property inputProperty, Node outputNode, Context context)
      throws Exception {
    Binary binaryValue = inputProperty.getBinary();
    CheckArg.isNotNull(binaryValue, "binary");

    if (!outputNode.isNew()) {
      outputNode = outputNode.addNode(XmlLexicon.DOCUMENT);
    }

    XmlSequencerHandler sequencingHandler = new XmlSequencerHandler(outputNode, scoping);
    // Create the reader ...
    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(sequencingHandler);
    reader.setErrorHandler(sequencingHandler);
    // Ensure handler acting as entity resolver 2
    reader.setProperty(DECL_HANDLER_FEATURE, sequencingHandler);
    // Ensure handler acting as lexical handler
    reader.setProperty(LEXICAL_HANDLER_FEATURE, sequencingHandler);
    // Ensure handler acting as entity resolver 2
    setFeature(reader, ENTITY_RESOLVER_2_FEATURE, true);
    // Prevent loading of external DTDs
    setFeature(reader, LOAD_EXTERNAL_DTDS_FEATURE, false);
    // Prevent the resolving of DTD entities into fully-qualified URIS
    setFeature(reader, RESOLVE_DTD_URIS_FEATURE, false);
    // Parse XML document
    try (InputStream stream = binaryValue.getStream()) {
      reader.parse(new InputSource(stream));
    }
    return true;
  }
  @Override
  public long setContent(
      Node parentNode,
      String resourceName,
      InputStream newContent,
      String contentType,
      String characterEncoding)
      throws RepositoryException, IOException {
    Node contentNode;
    if (parentNode.hasNode(CONTENT_NODE_NAME)) {
      contentNode = parentNode.getNode(CONTENT_NODE_NAME);
    } else {
      contentNode = parentNode.addNode(CONTENT_NODE_NAME, newContentPrimaryType);
    }

    // contentNode.setProperty(MIME_TYPE_PROP_NAME, contentType != null ? contentType :
    // "application/octet-stream");
    contentNode.setProperty(
        ENCODING_PROP_NAME, characterEncoding != null ? characterEncoding : "UTF-8");
    Binary binary = parentNode.getSession().getValueFactory().createBinary(newContent);
    contentNode.setProperty(DATA_PROP_NAME, binary);
    contentNode.setProperty(MODIFIED_PROP_NAME, Calendar.getInstance());

    // Copy the content to the property, THEN re-read the content from the Binary value to avoid
    // discaring the first
    // bytes of the stream
    if (contentType == null) {
      contentType = mimeTypeDetector.mimeTypeOf(resourceName, binary.getStream());
    }

    return contentNode.getProperty(DATA_PROP_NAME).getLength();
  }
Example #5
0
 protected void assertCanObtainValue(Value value, int expectedType) throws Exception {
   switch (expectedType) {
     case PropertyType.BINARY:
       Binary binary = value.getBinary();
       try {
         InputStream stream = binary.getStream();
         assertThat(stream, is(notNullValue()));
         try {
           stream.read();
         } finally {
           stream.close();
         }
       } finally {
         binary.dispose();
       }
       break;
     case PropertyType.BOOLEAN:
       assertThat(value.getBoolean() || !value.getBoolean(), is(true));
       break;
     case PropertyType.DATE:
       Calendar cal = value.getDate();
       assertThat(cal, is(notNullValue()));
       break;
     case PropertyType.DOUBLE:
       double doubleValue = value.getDouble();
       assertThat(doubleValue < 0.0d || doubleValue >= -1.0d, is(true));
       break;
     case PropertyType.LONG:
       long longValue = value.getLong();
       assertThat(longValue < 0L || longValue >= 0L, is(true));
       break;
     case PropertyType.NAME:
       context.getValueFactories().getNameFactory().create(value.getString());
       break;
     case PropertyType.PATH:
       context.getValueFactories().getPathFactory().create(value.getString());
       break;
     case PropertyType.REFERENCE:
       UUID uuid = context.getValueFactories().getUuidFactory().create(value.getString());
       assertThat(uuid, is(notNullValue()));
       break;
     case PropertyType.STRING:
       value.getString();
       break;
   }
 }
  /**
   * Fires the appropriate SAX events on the content handler to build the XML elements for the
   * value.
   *
   * @param value the value to be exported
   * @param contentHandler the SAX content handler for which SAX events will be invoked as the XML
   *     document is created.
   * @param propertyType the {@link PropertyType} for the given value
   * @param skipBinary if <code>true</code>, indicates that binary properties should not be exported
   * @param isModified true if the property is modified; any modified binary properties will not be
   *     purged
   * @throws SAXException if an exception occurs during generation of the XML document
   * @throws RepositoryException if an exception occurs accessing the content repository
   */
  private void emitValue(
      Value value,
      ContentHandler contentHandler,
      int propertyType,
      boolean skipBinary,
      boolean isModified)
      throws RepositoryException, SAXException {

    if (PropertyType.BINARY == propertyType) {
      startElement(contentHandler, JcrSvLexicon.VALUE, null);

      // Per section 6.5 of the 1.0.1 spec, we need to emit one empty-value tag for each value if
      // the property is
      // multi-valued and skipBinary is true
      if (!skipBinary) {
        byte[] bytes = new byte[BASE_64_BUFFER_SIZE];
        int len;

        Binary binary = value.getBinary();
        try {
          InputStream stream = new Base64.InputStream(binary.getStream(), Base64.ENCODE);
          while (-1 != (len = stream.read(bytes))) {
            contentHandler.characters(new String(bytes, 0, len).toCharArray(), 0, len);
          }
        } catch (IOException ioe) {
          throw new RepositoryException(ioe);
        } finally {
          try {
            binary.dispose();
          } finally {
            if (!isModified) {
              if (binary instanceof org.modeshape.graph.property.Binary) {
                ((org.modeshape.graph.property.Binary) binary).purge();
              }
            }
          }
        }
      }
      endElement(contentHandler, JcrSvLexicon.VALUE);
    } else {
      emitValue(value.getString(), contentHandler);
    }
  }
  @FixFor("MODE-1308")
  @Test
  public void shouldAllowAnyBinaryImplementation() throws Exception {
    Node node = rootNode.addNode("nodeWithBinaryProperty", "nt:unstructured");
    final String stringValue = "This is the string stringValue";
    Binary binaryValue =
        new Binary() {
          public InputStream getStream() throws RepositoryException {
            return new ByteArrayInputStream(stringValue.getBytes());
          }

          public int read(byte[] b, long position) throws IOException, RepositoryException {
            byte[] content = stringValue.getBytes();
            int length =
                b.length + position < content.length ? b.length : (int) (content.length - position);
            System.arraycopy(content, (int) position, b, 0, length);
            return length;
          }

          public long getSize() throws RepositoryException {
            return stringValue.getBytes().length;
          }

          public void dispose() {}
        };
    node.setProperty("binProp", binaryValue);
    Binary nodeValue = node.getProperty("binProp").getBinary();
    assertNotNull(nodeValue);
    assertEquals(stringValue.getBytes().length, nodeValue.getSize());
    byte[] buffer = new byte[100];
    int available;
    InputStream inputStream = nodeValue.getStream();
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    while ((available = inputStream.read(buffer)) != -1) {
      byteOut.write(buffer, 0, available);
    }
    assertArrayEquals(stringValue.getBytes(), byteOut.toByteArray());
  }
Example #8
0
 private File createFile(Node node) throws RepositoryException {
   if (node.hasProperty("jcr:content/jcr:data")) {
     Property data = node.getProperty("jcr:content/jcr:data");
     Binary binary = data.getBinary();
     OutputStream out = null;
     InputStream in = null;
     try {
       File result = new File(fontsDir, node.getName());
       result.createNewFile();
       result.deleteOnExit();
       in = binary.getStream();
       out = new FileOutputStream(result);
       IOUtils.copy(in, out);
       return result;
     } catch (IOException e) {
       logger.error("Failed exporting FOP font data.", e);
     } finally {
       IOUtils.closeQuietly(in);
       IOUtils.closeQuietly(out);
       binary.dispose();
     }
   }
   return null;
 }
  @Test
  public void testRuleExecution() throws RepositoryException, RuleExecutionException {
    String path = "/test/ruleset";

    Mockito.when(request.getResourceResolver()).thenReturn(resourceResolver);
    Mockito.when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    Mockito.when(session.getUserID()).thenReturn("ieb");

    Mockito.when(resourceResolver.getResource(path)).thenReturn(ruleSet);
    Mockito.when(ruleSet.getResourceType()).thenReturn(RuleConstants.SAKAI_RULE_SET);
    Mockito.when(ruleSet.adaptTo(Node.class)).thenReturn(ruleSetNode);
    Mockito.when(context.getBundleContext()).thenReturn(bundleContext);

    Mockito.when(ruleSetNode.getPath()).thenReturn(path);
    Mockito.when(ruleSetNode.getNodes()).thenReturn(nodeIterator);

    // specify the rule processor
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(true);
    Mockito.when(ruleSetNode.getProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(preprocessorProperty);
    Mockito.when(preprocessorProperty.getString()).thenReturn("message-test-preprocessor");

    // when the service referece is invoked we need to give it out processor
    Mockito.when(reference.getProperty(RuleConstants.PROCESSOR_NAME))
        .thenReturn("message-test-preprocessor");

    RuleExecutionPreProcessor messageRuleExcutionPreProcessor =
        new MesageRuleExcutionPreProcessor();
    Mockito.when(bundleContext.getService(reference)).thenReturn(messageRuleExcutionPreProcessor);

    // turn on debug for this rule execution, just needs the property to exist.
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_DEBUG))
        .thenReturn(true, true, false);

    Mockito.when(nodeIterator.hasNext()).thenReturn(true, false, true, false);
    Mockito.when(nodeIterator.nextNode()).thenReturn(packageNode, packageNode);
    Mockito.when(packageNode.getPrimaryNodeType()).thenReturn(packageNodeType);
    Mockito.when(packageNodeType.getName()).thenReturn(NodeType.NT_FILE);

    Mockito.when(packageNode.getPath()).thenReturn(path + "/package1");

    Mockito.when(packageNode.getNode(Node.JCR_CONTENT)).thenReturn(packageFileNode);

    Mockito.when(packageFileNode.getProperty(Property.JCR_LAST_MODIFIED)).thenReturn(property);
    Calendar lastModified = GregorianCalendar.getInstance();
    lastModified.setTimeInMillis(System.currentTimeMillis());
    Calendar lastModifiedLater = GregorianCalendar.getInstance();
    lastModifiedLater.setTimeInMillis(System.currentTimeMillis() + 20000);
    Mockito.when(property.getDate()).thenReturn(lastModified, lastModified, lastModifiedLater);

    Mockito.when(packageFileNode.getProperty(Property.JCR_DATA)).thenReturn(packageFileBody);

    Mockito.when(packageFileBody.getBinary()).thenReturn(binary);

    Mockito.when(binary.getStream())
        .thenAnswer(
            new Answer<InputStream>() {

              public InputStream answer(InvocationOnMock invocation) throws Throwable {
                return this.getClass()
                    .getResourceAsStream(
                        "/SLING-INF/content/var/rules/org.sakaiproject.nakamura.rules/org.sakaiproject.nakamura.rules.example/0.7-SNAPSHOT/org.sakaiproject.nakamura.rules.example-0.7-SNAPSHOT.pkg");
              }
            });

    RuleExecutionServiceImpl res = new RuleExecutionServiceImpl();
    res.activate(context);
    res.bindProcessor(reference);
    Map<String, Object> result =
        res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a second time to use the cache.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a third time time to reload.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    res.deactivate(context);
  }