javax.jcr.Binary Java Examples

The following examples show how to use javax.jcr.Binary. 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: BaseRepositoryService.java    From urule with Apache License 2.0 8 votes vote down vote up
@Override
public InputStream readFile(String path,String version) throws Exception{
	if(StringUtils.isNotBlank(version)){
		repositoryInteceptor.readFile(path+":"+version);
		return readVersionFile(path, version);
	}
	repositoryInteceptor.readFile(path);
	Node rootNode=getRootNode();
	int colonPos = path.lastIndexOf(":");
	if (colonPos > -1) {
		version = path.substring(colonPos + 1, path.length());
		path = path.substring(0, colonPos);
		return readFile(path, version);
	}
	path = processPath(path);
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	return fileBinary.getStream();
}
 
Example #2
Source File: TestBinarylessExport.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Before
@Ignore
public void setup() throws RepositoryException, PackageException, IOException {
    // test only works for Jackrabbit 2.0 or Oak with FileDataStore
    Assume.assumeTrue(!isOak() || useFileStore());

    Node binaryNode = JcrUtils.getOrCreateByPath(BINARY_NODE_PATH, "nt:unstructured", admin);

    Binary bigBin = admin.getValueFactory().createBinary(IOUtils.toInputStream(BIG_TEXT, "UTF-8"));
    Property bigProperty = binaryNode.setProperty(BIG_BINARY_PROPERTY, bigBin);
    String referenceBigBinary = ((ReferenceBinary) bigProperty.getBinary()).getReference();
    assertNotNull(referenceBigBinary);

    Binary smallBin = admin.getValueFactory().createBinary(IOUtils.toInputStream(SMALL_TEXT, "UTF-8"));
    Property smallProperty = binaryNode.setProperty(SMALL_BINARY_PROPERTY, smallBin);
    if (isOak()) {
        assertTrue(smallProperty.getBinary() instanceof ReferenceBinary);
    } else {
        assertFalse(smallProperty.getBinary() instanceof ReferenceBinary);
    }

    JcrUtils.putFile(binaryNode.getParent(), "file", "text/plain", IOUtils.toInputStream(BIG_TEXT, "UTF-8"));
    admin.save();
}
 
Example #3
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new jcr vault package.
 *
 * @param parent the parent node
 * @param pid the package id of the new package.
 * @param bin the binary containing the zip
 * @param archive the archive with the meta data
 * @return the created jcr vault package.
 * @throws RepositoryException if an repository error occurs
 * @throws IOException if an I/O error occurs
 *
 * @since 3.1
 */
@NotNull
private JcrPackage createNew(@NotNull Node parent, @NotNull PackageId pid, @NotNull Binary bin, @NotNull MemoryArchive archive)
        throws RepositoryException, IOException {
    Node node = parent.addNode(Text.getName(getInstallationPath(pid) + ".zip"), JcrConstants.NT_FILE);
    Node content = node.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    content.addMixin(JcrPackage.NT_VLT_PACKAGE);
    Node defNode = content.addNode(JcrPackage.NN_VLT_DEFINITION);
    JcrPackageDefinitionImpl def = new JcrPackageDefinitionImpl(defNode);
    def.set(JcrPackageDefinition.PN_NAME, pid.getName(), false);
    def.set(JcrPackageDefinition.PN_GROUP, pid.getGroup(), false);
    def.set(JcrPackageDefinition.PN_VERSION, pid.getVersionString(), false);
    def.touch(null, false);
    content.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
    content.setProperty(JcrConstants.JCR_MIMETYPE, JcrPackage.MIME_TYPE);
    content.setProperty(JcrConstants.JCR_DATA, bin);
    def.unwrap(archive, false);
    dispatch(PackageEvent.Type.CREATE, pid, null);
    return new JcrPackageImpl(this, node);
}
 
Example #4
Source File: JcrExporter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
public void writeFile(InputStream in, String relPath) throws IOException {
    try {
        Node content;
        Node local = getOrCreateItem(relPath, false);
        if (local.hasNode(JcrConstants.JCR_CONTENT)) {
            content = local.getNode(JcrConstants.JCR_CONTENT);
        } else {
            content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
        }
        Binary b = content.getSession().getValueFactory().createBinary(in);
        content.setProperty(JcrConstants.JCR_DATA, b);
        content.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
        if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){
            content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream");
        }
        b.dispose();
        in.close();
    } catch (RepositoryException e) {
        IOException io = new IOException("Error while writing file " + relPath);
        io.initCause(e);
        throw io;
    }
}
 
Example #5
Source File: TreeSync.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void writeNtFile(SyncResult res, Entry e) throws RepositoryException, IOException {
    Node ntFile = e.node;
    Node content;
    String action = "A";
    if (ntFile == null) {
        e.node = ntFile = e.parentNode.addNode(e.jcrName, NodeType.NT_FILE);
        content = ntFile.addNode(Node.JCR_CONTENT, NodeType.NT_RESOURCE);
    } else {
        content = ntFile.getNode(Node.JCR_CONTENT);
        action = "U";
    }
    Calendar cal = Calendar.getInstance();
    if (preserveFileDate) {
        cal.setTimeInMillis(e.file.lastModified());
    }
    InputStream in = FileUtils.openInputStream(e.file);
    Binary bin = content.getSession().getValueFactory().createBinary(in);
    content.setProperty(Property.JCR_DATA, bin);
    content.setProperty(Property.JCR_LAST_MODIFIED, cal);
    content.setProperty(Property.JCR_MIMETYPE, MimeTypes.getMimeType(e.file.getName(), MimeTypes.APPLICATION_OCTET_STREAM));
    syncLog.log("%s jcr://%s", action, ntFile.getPath());
    res.addEntry(e.getJcrPath(), e.getFsPath(), SyncResult.Operation.UPDATE_JCR);
}
 
Example #6
Source File: TreeSync.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void writeFile(SyncResult res, Entry e) throws IOException, RepositoryException {
    String action = e.file.exists() ? "U" : "A";
    Binary bin = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        bin = e.node.getProperty("jcr:content/jcr:data").getBinary();
        in = bin.getStream();
        out = FileUtils.openOutputStream(e.file);
        IOUtils.copy(in, out);
        if (preserveFileDate) {
            Calendar lastModified = e.node.getProperty("jcr:content/jcr:lastModified").getDate();
            e.file.setLastModified(lastModified.getTimeInMillis());
        }
        syncLog.log("%s file://%s", action, e.file.getAbsolutePath());
        res.addEntry(e.getJcrPath(), e.getFsPath(), SyncResult.Operation.UPDATE_FS);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (bin != null) {
            bin.dispose();
        }
    }
}
 
Example #7
Source File: ValueImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
private static int selectPropertyType(Object value) {
    return (value instanceof String) ? PropertyType.STRING :
        (value instanceof Long) ? PropertyType.LONG :
            (value instanceof Double) ? PropertyType.DOUBLE :
                (value instanceof BigDecimal) ? PropertyType.DECIMAL :
                    (value instanceof Calendar) ? PropertyType.DATE :
                        (value instanceof Boolean) ? PropertyType.BOOLEAN :
                            (value instanceof Binary) ? PropertyType.BINARY :
                                PropertyType.UNDEFINED;
}
 
Example #8
Source File: StorageUpdate11.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void convertReports() throws RepositoryException {
	
	String statement = 
			"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
			"//*[@className='ro.nextreports.server.domain.Report' and @type='Next']" + 
			"//*[fn:name()='jcr:content' and @jcr:mimeType='text/xml']";
	  
	QueryResult queryResult = getTemplate().query(statement);

	NodeIterator nodes = queryResult.getNodes();
	LOG.info("Converter 5.1 : Found " + nodes.getSize() + " report nodes");
	while (nodes.hasNext()) {
		
		Node node = nodes.nextNode();
		
		Node reportNode = node.getParent().getParent().getParent().getParent();
		String reportName = reportNode.getName();
		String reportPath = reportNode.getPath();	
		LOG.info(" * Start convert '" + reportPath + "'");						
											
		Property prop = node.getProperty("jcr:data");			
       	String xml = null;
           try {                  	
           	xml = new Converter_5_2().convertFromInputStream(prop.getBinary().getStream(), true);            	            	
           	if (xml != null) {
               	ValueFactory valueFactory = node.getSession().getValueFactory(); 
               	Binary binaryValue = valueFactory.createBinary(new ByteArrayInputStream(xml.getBytes("UTF-8")));
               	node.setProperty ("jcr:data", binaryValue);                	
               	LOG.info("\t -> OK");
               } else {
               	LOG.error("\t -> FAILED : null xml");
               }
           	            	            	
           } catch (Throwable t) {                    	            	            
           	LOG.error("\t-> FAILED : " + t.getMessage(), t);            	
           } 					
           
	}
}
 
Example #9
Source File: JcrExporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void writeFile(VaultFile file, String relPath)
        throws RepositoryException, IOException {
    Node local = getOrCreateItem(getPlatformFilePath(file, relPath), false);
    track(local.isNew() ? "A" : "U", relPath);
    Node content;
    if (local.hasNode(JcrConstants.JCR_CONTENT)) {
        content = local.getNode(JcrConstants.JCR_CONTENT);
    } else {
        content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }
    Artifact a = file.getArtifact();
    switch (a.getPreferredAccess()) {
        case NONE:
            throw new RepositoryException("Artifact has no content.");

        case SPOOL:
            // we can't support spool
        case STREAM:
            try (InputStream in = a.getInputStream()) {
                Binary b = content.getSession().getValueFactory().createBinary(in);
                content.setProperty(JcrConstants.JCR_DATA, b);
                b.dispose();
            }
            break;
    }
    Calendar now = Calendar.getInstance();
    if (a.getLastModified() >= 0) {
        now.setTimeInMillis(a.getLastModified());
    }
    content.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
    if (a.getContentType() != null) {
        content.setProperty(JcrConstants.JCR_MIMETYPE, a.getContentType());
    } else if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){
        content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream");
    }
}
 
Example #10
Source File: AggregateImpl.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void include(Node parent, Property prop, String propPath)
        throws RepositoryException {
    String relPath = propPath.substring(path.length());
    if (includes == null || !includes.contains(relPath)) {
        if (log.isDebugEnabled()) {
            log.trace("including {} -> {}", path, propPath);
        }
        // ensure that parent node is included as well
        include(parent, null);
        includes.add(mgr.cacheString(relPath));
        if (prop.getType() == PropertyType.BINARY) {
            boolean includeBinary = true;
            if (useBinaryReferences) {
                Binary bin = prop.getBinary();
                if (bin != null && bin instanceof ReferenceBinary) {
                    String binaryReference = ((ReferenceBinary) bin).getReference();

                    // do not create a separate binary file if there is a reference
                    if (binaryReference != null) {
                        includeBinary = false;
                    }
                }
            }

            if (includeBinary) {
                if (binaries == null) {
                    binaries = new LinkedList<Property>();
                }
                binaries.add(prop);
            }
        }
    }
}
 
Example #11
Source File: ValueFactoryImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public Binary createBinary(InputStream stream) throws RepositoryException {
    Binary b = new BinaryImpl(stream);
    try {
        stream.close();
    }
    catch (IOException ioe) { /* ignore */ }
    return b;
}
 
Example #12
Source File: BaseRepositoryService.java    From urule with Apache License 2.0 5 votes vote down vote up
private InputStream readVersionFile(String path, String version) throws Exception{
	path = processPath(path);
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	VersionHistory versionHistory = versionManager.getVersionHistory(fileNode.getPath());
	Version v = versionHistory.getVersion(version);
	Node fnode = v.getFrozenNode();
	Property property = fnode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	return fileBinary.getStream();
}
 
Example #13
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) {
  Script result = null;
  try {
    final Session session = resolver.adaptTo(Session.class);
    final ValueFactory valueFactory = session.getValueFactory();
    final Binary binary = valueFactory.createBinary(descriptor.getInputStream());
    final Node saveNode = session.getNode(descriptor.getPath());

    final Node fileNode, contentNode;
    if (overwrite && saveNode.hasNode(descriptor.getName())) {
      fileNode = saveNode.getNode(descriptor.getName());
      contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
    } else {
      fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE);
      contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }

    contentNode.setProperty(JcrConstants.JCR_DATA, binary);
    contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name());
    fileNode.addMixin(ScriptNode.APM_SCRIPT);
    fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule());
    removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED);
    JcrUtils.setLastModified(fileNode, Calendar.getInstance());
    session.save();
    result = scriptFinder.find(fileNode.getPath(), resolver);
  } catch (RepositoryException e) {
    LOG.error(e.getMessage(), e);
  }
  return result;
}
 
Example #14
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserPermission> loadResourceSecurityConfigs(String companyId) throws Exception{
	List<UserPermission> configs=new ArrayList<UserPermission>();
	String filePath=RESOURCE_SECURITY_CONFIG_FILE+(companyId == null ? "" : companyId);
	Node rootNode=getRootNode();
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("user-permission")) {
			continue;
		}
		UserPermission userResource=new UserPermission();
		userResource.setUsername(element.attributeValue("username"));
		userResource.setProjectConfigs(parseProjectConfigs(element));
		configs.add(userResource);
	}
	return configs;
}
 
Example #15
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<ClientConfig> loadClientConfigs(String project) throws Exception{
	if(!permissionService.isAdmin()){
		throw new NoPermissionException();
	}
	List<ClientConfig> clients=new ArrayList<ClientConfig>();
	Node rootNode=getRootNode();
	String filePath = processPath(project) + "/" + CLIENT_CONFIG_FILE;
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("item")) {
			continue;
		}
		ClientConfig client = new ClientConfig();
		client.setName(element.attributeValue("name"));
		client.setClient(element.attributeValue("client"));
		client.setProject(project);
		clients.add(client);
	}
	return clients;
}
 
Example #16
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
private void createFileNode(String path, String content,User user,boolean isFile) throws Exception{
	String createUser=user.getUsername();
	repositoryInteceptor.createFile(path,content);
	Node rootNode=getRootNode();
	path = processPath(path);
	try {
		if (rootNode.hasNode(path)) {
			throw new RuleException("File [" + path + "] already exist.");
		}
		Node fileNode = rootNode.addNode(path);
		fileNode.addMixin("mix:versionable");
		fileNode.addMixin("mix:lockable");
		Binary fileBinary = new BinaryImpl(content.getBytes());
		fileNode.setProperty(DATA, fileBinary);
		if(isFile){
			fileNode.setProperty(FILE, true);				
		}
		fileNode.setProperty(CRATE_USER, createUser);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		DateValue dateValue = new DateValue(calendar);
		fileNode.setProperty(CRATE_DATE, dateValue);
		session.save();
	} catch (Exception ex) {
		throw new RuleException(ex);
	}
}
 
Example #17
Source File: NodeWrapper.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
public Property setProperty(String name, Binary value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
    return sessionWrapper.getObjectWrapper().wrap(sessionWrapper, delegate.setProperty(name, value));
}
 
Example #18
Source File: BaseRepositoryService.java    From urule with Apache License 2.0 4 votes vote down vote up
@Override
public List<ResourcePackage> loadProjectResourcePackages(String project) throws Exception {
	Node rootNode=getRootNode();
	String filePath = processPath(project) + "/" + RES_PACKGE_FILE;
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	List<ResourcePackage> packages = new ArrayList<ResourcePackage>();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("res-package")) {
			continue;
		}
		ResourcePackage p = new ResourcePackage();
		String dateStr = element.attributeValue("create_date");
		if (dateStr != null) {
			p.setCreateDate(sd.parse(dateStr));
		}
		p.setId(element.attributeValue("id"));
		p.setName(element.attributeValue("name"));
		p.setProject(project);
		List<ResourceItem> items = new ArrayList<ResourceItem>();
		for (Object o : element.elements()) {
			if (!(o instanceof Element)) {
				continue;
			}
			Element ele = (Element) o;
			if (!ele.getName().equals("res-package-item")) {
				continue;
			}
			ResourceItem item = new ResourceItem();
			item.setName(ele.attributeValue("name"));
			item.setPackageId(p.getId());
			item.setPath(ele.attributeValue("path"));
			item.setVersion(ele.attributeValue("version"));
			items.add(item);
		}
		p.setResourceItems(items);
		packages.add(p);
	}
	return packages;
}
 
Example #19
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public JcrPackage upload(InputStream in, boolean replace)
        throws RepositoryException, IOException, PackageExistsException {

    MemoryArchive archive = new MemoryArchive(true);
    InputStreamPump pump = new InputStreamPump(in , archive);

    // this will cause the input stream to be consumed and the memory archive being initialized.
    Binary bin = session.getValueFactory().createBinary(pump);
    if (pump.getError() != null) {
        Exception error = pump.getError();
        log.error("Error while reading from input stream.", error);
        bin.dispose();
        throw new IOException("Error while reading from input stream", error);
    }

    if (archive.getJcrRoot() == null) {
        String msg = "Stream is not a content package. Missing 'jcr_root'.";
        log.error(msg);
        bin.dispose();
        throw new IOException(msg);
    }

    final MetaInf inf = archive.getMetaInf();
    PackageId pid = inf.getPackageProperties().getId();

    // invalidate pid if path is unknown
    if (pid == null) {
        pid = createRandomPid();
    }
    if (!pid.isValid()) {
        bin.dispose();
        throw new RepositoryException("Unable to create package. Illegal package name.");
    }

    // create parent node
    String path = getInstallationPath(pid) + ".zip";
    String parentPath = Text.getRelativeParent(path, 1);
    String name = Text.getName(path);
    Node parent = mkdir(parentPath, false);

    // remember installation state properties (GRANITE-2018)
    JcrPackageDefinitionImpl.State state = null;
    Calendar oldCreatedDate = null;

    if (parent.hasNode(name)) {
        try (JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name))) {
            JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
            if (oldDef != null) {
                state = oldDef.getState();
                oldCreatedDate = oldDef.getCreated();
            }
        }

        if (replace) {
            parent.getNode(name).remove();
        } else {
            throw new PackageExistsException("Package already exists: " + pid).setId(pid);
        }
    }
    JcrPackage jcrPack = null;
    try {
        jcrPack = createNew(parent, pid, bin, archive);
        JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) jcrPack.getDefinition();
        Calendar newCreateDate = def == null ? null : def.getCreated();
        // only transfer the old package state to the new state in case both packages have the same create date
        if (state != null && newCreateDate != null && oldCreatedDate != null && oldCreatedDate.compareTo(newCreateDate) == 0) {
            def.setState(state);
        }
        dispatch(PackageEvent.Type.UPLOAD, pid, null);
        return jcrPack;
    } finally {
        bin.dispose();
        if (jcrPack == null) {
            session.refresh(false);
        } else {
            session.save();
        }
    }
}
 
Example #20
Source File: DocViewProperty.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
/**
 * Sets this property on the given node
 *
 * @param node the node
 * @return {@code true} if the value was modified.
 * @throws RepositoryException if a repository error occurs
 */
public boolean apply(Node node) throws RepositoryException {
    Property prop = node.hasProperty(name) ? node.getProperty(name) : null;
    // check if multiple flags are equal
    if (prop != null && isMulti != prop.getDefinition().isMultiple()) {
        prop.remove();
        prop = null;
    }
    if (prop != null) {
        int propType = prop.getType();
        if (propType != type && (propType != PropertyType.STRING || type != PropertyType.UNDEFINED)) {
            // never compare if types differ
            prop = null;
        }
    }
    if (isMulti) {
        // todo: handle multivalue binaries and reference binaries
        Value[] vs = prop == null ? null : prop.getValues();
        if (vs != null && vs.length == values.length) {
            // quick check all values
            boolean modified = false;
            for (int i=0; i<vs.length; i++) {
                if (!vs[i].getString().equals(values[i])) {
                    modified = true;
                }
            }
            if (!modified) {
                return false;
            }
        }
        if (type == PropertyType.UNDEFINED) {
            node.setProperty(name, values);
        } else {
            node.setProperty(name, values, type);
        }
        // assume modified
        return true;
    } else {
        Value v = prop == null ? null : prop.getValue();
        if (type == PropertyType.BINARY) {
            if (isReferenceProperty) {
                ReferenceBinary ref = new SimpleReferenceBinary(values[0]);
                Binary binary = node.getSession().getValueFactory().createValue(ref).getBinary();
                if (v != null) {
                    Binary bin = v.getBinary();
                    if (bin.equals(binary)) {
                        return false;
                    }
                }
                node.setProperty(name, binary);
            }
            // the binary property is always modified (TODO: check if still correct with JCRVLT-110)
            return true;
        }
        if (v == null || !v.getString().equals(values[0])) {
            try {
                if (type == PropertyType.UNDEFINED) {
                    node.setProperty(name, values[0]);
                } else {
                    node.setProperty(name, values[0], type);
                }
            } catch (ValueFormatException e) {
                // forcing string
                node.setProperty(name, values[0], PropertyType.STRING);
            }
            return true;
        }
    }
    return false;
}
 
Example #21
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 4 votes vote down vote up
@Override
public void saveFile(String path, String content,boolean newVersion,String versionComment,User user) throws Exception{
	path=Utils.decodeURL(path); 
	if(path.indexOf(RES_PACKGE_FILE)>-1){
		if(!permissionService.projectPackageHasWritePermission(path)){
			throw new NoPermissionException();
		}
	}
	if(!permissionService.fileHasWritePermission(path)){
		throw new NoPermissionException();
	}
	
	repositoryInteceptor.saveFile(path, content);
	path = processPath(path);
	int pos=path.indexOf(":");
	if(pos!=-1){
		path=path.substring(0,pos);
	}
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	lockCheck(fileNode,user);
	versionManager.checkout(fileNode.getPath());
	Binary fileBinary = new BinaryImpl(content.getBytes("utf-8"));
	fileNode.setProperty(DATA, fileBinary);
	fileNode.setProperty(FILE, true);
	fileNode.setProperty(CRATE_USER, user.getUsername());
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(new Date());
	DateValue dateValue = new DateValue(calendar);
	fileNode.setProperty(CRATE_DATE, dateValue);
	if (newVersion && StringUtils.isNotBlank(versionComment)) {
		fileNode.setProperty(VERSION_COMMENT, versionComment);
	}
	session.save();
	if (newVersion) {
		versionManager.checkin(fileNode.getPath());
	}
}
 
Example #22
Source File: NodeImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public Property setProperty(String name, Binary value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
    return setProperty(name, new ValueImpl(value));
}
 
Example #23
Source File: PropertyWrapper.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
public void setValue(Binary value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
    delegate.setValue(value);
}
 
Example #24
Source File: ValueFactoryImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
public Binary createBinary(String s) {
    return new BinaryImpl(s.getBytes());
}
 
Example #25
Source File: PropertyWrapper.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
public Binary getBinary() throws ValueFormatException, RepositoryException {
    return delegate.getBinary();
}
 
Example #26
Source File: ValueFactoryImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public Value createValue(Binary value) {
    return new ValueImpl(PropertyType.BINARY, value);
}
 
Example #27
Source File: ValueImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public Binary getBinary() throws RepositoryException {
    if (type != PropertyType.BINARY) throw new ValueFormatException();
    return (Binary)valueObject;
}
 
Example #28
Source File: PropertyImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public Binary getBinary() throws ValueFormatException, RepositoryException {
    if (isMultiple()) throw new ValueFormatException();
    return value.getBinary();  //To change body of implemented methods use File | Settings | File Templates.
}
 
Example #29
Source File: PropertyImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public void setValue(@Nonnull Binary value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
    setValue(new ValueImpl(value));
}