Java Code Examples for org.alfresco.util.Pair

The following are top voted examples for showing how to use org.alfresco.util.Pair. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: AbstractPropertyValueDAOImpl.java   View source code 6 votes vote down vote up
/**
 * Default constructor.
 * <p>
 * This sets up the DAO accessors to bypass any caching to handle the case where the caches are not
 * supplied in the setters.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public AbstractPropertyValueDAOImpl()
{
    this.propertyClassDaoCallback = new PropertyClassCallbackDAO();
    this.propertyDateValueCallback = new PropertyDateValueCallbackDAO();
    this.propertyStringValueCallback = new PropertyStringValueCallbackDAO();
    this.propertyDoubleValueCallback = new PropertyDoubleValueCallbackDAO();
    this.propertySerializableValueCallback = new PropertySerializableValueCallbackDAO();
    this.propertyValueCallback = new PropertyValueCallbackDAO();
    this.propertyCallback = new PropertyCallbackDAO();
    
    this.propertyClassCache = new EntityLookupCache<Long, Class<?>, String>(propertyClassDaoCallback);
    this.propertyDateValueCache = new EntityLookupCache<Long, Date, Date>(propertyDateValueCallback);
    this.propertyStringValueCache = new EntityLookupCache<Long, String, Pair<String, Long>>(propertyStringValueCallback);
    this.propertyDoubleValueCache = new EntityLookupCache<Long, Double, Double>(propertyDoubleValueCallback);
    this.propertySerializableValueCache = new EntityLookupCache<Long, Serializable, Serializable>(propertySerializableValueCallback);
    this.propertyValueCache = new EntityLookupCache<Long, Serializable, Serializable>(propertyValueCallback);
    this.propertyCache = new EntityLookupCache<Long, Serializable, Serializable>(propertyCallback);
    
    this.propertyUniqueContextCache = (SimpleCache<CachePucKey, PropertyUniqueContextEntity>)new NullCache();
}
 
Example 2
Project: alfresco-repository   File: DbNodeServiceImpl.java   View source code 6 votes vote down vote up
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public void removeAssociation(NodeRef sourceRef, NodeRef targetRef, QName assocTypeQName)
        throws InvalidNodeRefException
{
    // The node(s) involved may not be pending deletion
    checkPendingDelete(sourceRef);
    checkPendingDelete(targetRef);
    
    Pair<Long, NodeRef> sourceNodePair = getNodePairNotNull(sourceRef);
    Long sourceNodeId = sourceNodePair.getFirst();
    Pair<Long, NodeRef> targetNodePair = getNodePairNotNull(targetRef);
    Long targetNodeId = targetNodePair.getFirst();

    AssociationRef assocRef = new AssociationRef(sourceRef, assocTypeQName, targetRef);
    // Invoke policy behaviours
    invokeBeforeDeleteAssociation(assocRef);

    // delete it
    int assocsDeleted = nodeDAO.removeNodeAssoc(sourceNodeId, targetNodeId, assocTypeQName);
    
    if (assocsDeleted > 0)
    {
        // Invoke policy behaviours
        invokeOnDeleteAssociation(assocRef);
    }
}
 
Example 3
Project: alfresco-repository   File: PermissionServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Check that a given authentication is available on a node
 * 
 * @param authority String
 * @param aclId Long
 * @return true if a check is required
 */
boolean checkRequired(String authority, Long aclId)
{
    AccessControlList acl = aclDaoComponent.getAccessControlList(aclId);

    if (acl == null)
    {
        return false;
    }

    Set<Pair<String, PermissionReference>> denied = new HashSet<Pair<String, PermissionReference>>();

    // Check if each permission allows - the first wins.
    // We could have other voting style mechanisms here
    for (AccessControlEntry ace : acl.getEntries())
    {
        if (isGranted(ace, authority, denied))
        {
            return true;
        }
    }
    return false;
}
 
Example 4
Project: alfresco-repository   File: AuthenticationServiceImpl.java   View source code 6 votes vote down vote up
public void validate(String ticket) throws AuthenticationException
{
    String currentUser = null;
    try
    {
        String tenant = getPrevalidationTenantDomain();
        
        // clear context - to avoid MT concurrency issue (causing domain mismatch) - see also 'authenticate' above
        clearCurrentSecurityContext();
        currentUser = ticketComponent.validateTicket(ticket);
        authenticationComponent.setCurrentUser(currentUser, UserNameValidationMode.NONE);
        
        if (tenant == null)
        {
            Pair<String, String> userTenant = AuthenticationUtil.getUserTenant(currentUser);
            tenant = userTenant.getSecond();
        }
        TenantContextHolder.setTenantDomain(tenant);
    }
    catch (AuthenticationException ae)
    {
        clearCurrentSecurityContext();
        throw ae;
    }
}
 
Example 5
Project: alfresco-repository   File: ScriptAuthorityService.java   View source code 6 votes vote down vote up
/**
 * This method will tokenise a name string in order to extract first name, last name - if possible.
 * The split is simple - it's made on the first whitespace within the trimmed nameFilter String. So
 * <p/>
 * "Luke Skywalker" becomes ["Luke", "Skywalker"].
 * <p/>
 * "Jar Jar Binks" becomes ["Jar", "Jar Binks"].
 * <p/>
 * "C-3PO" becomes null.
 * 
 * @param nameFilter String
 * @return A Pair<firstName, lastName> if the String is valid, else <tt>null</tt>.
 */
private Pair<String, String> tokeniseName(String nameFilter)
{
    Pair<String, String> result = null;
    
    if (nameFilter != null)
    {
        final String trimmedNameFilter = nameFilter.trim();
        
        // We can only have a first name and a last name if we have at least 3 characters e.g. "A B".
        if (trimmedNameFilter.length() > 3)
        {
            final String[] tokens = trimmedNameFilter.split(ON_FIRST_SPACE, 2);
            if (tokens.length == 2)
            {
                result = new Pair<String, String>(tokens[0], tokens[1]);
            }
        }
    }
    
    return result;
}
 
Example 6
Project: alfresco-repository   File: NodeDAOImpl.java   View source code 6 votes vote down vote up
@Override
protected void selectChildAssocsByPropertyValue(Long parentNodeId,
        QName propertyQName, 
        NodePropertyValue nodeValue,
        ChildAssocRefQueryCallback resultsCallback)
{
    ChildPropertyEntity assocProp = new ChildPropertyEntity();
    // Parent
    assocProp.setParentNodeId(parentNodeId);
    // Property name
    Pair<Long,QName> propName = qnameDAO.getQName(propertyQName);
    if (propName == null)
    {
        resultsCallback.done();
        return;
    }
    
    // Property
    assocProp.setValue(nodeValue);
    assocProp.setPropertyQNameId(propName.getFirst());

    ChildAssocResultHandler resultHandler = new ChildAssocResultHandler(resultsCallback);
    template.select(SELECT_CHILD_ASSOCS_BY_PROPERTY_VALUE, assocProp, resultHandler);
    resultsCallback.done();
}
 
Example 7
Project: alfresco-repository   File: LDAPUserRegistry.java   View source code 6 votes vote down vote up
private Pair<String[], Set<QName>> initKeys(Map<String, String> attributeMapping,
        String... extraAttibutes)
{
    // Compile a complete array of LDAP attribute names, including operational attributes
    Set<String> attributeSet = new TreeSet<String>();
    attributeSet.addAll(Arrays.asList(extraAttibutes));
    attributeSet.add(this.modifyTimestampAttributeName);
    for (String attribute : attributeMapping.values())
    {
        if (attribute != null)
        {
            attributeSet.add(attribute);
        }
    }
    String[] attributeNames = new String[attributeSet.size()];
    attributeSet.toArray(attributeNames);

    // Create a set with the property names converted to QNames
    Set<QName> qnames = new HashSet<QName>(attributeMapping.size() * 2);
    for (String property : attributeMapping.keySet())
    {
        qnames.add(QName.createQName(property, this.namespaceService));
    }

    return new Pair<String[], Set<QName>>(attributeNames, qnames);
}
 
Example 8
Project: alfresco-repository   File: UserNameMatcherImpl.java   View source code 6 votes vote down vote up
private Pair<String, String> splitByDomain(String name, String domainSeparator)
{
    int idx = name.lastIndexOf(domainSeparator);
    if (idx != -1)
    {
        if ((idx + 1) > name.length())
        {
            return new Pair<String, String>(name.substring(0, idx), "");
        }
        else
        {
            return new Pair<String, String>(name.substring(0, idx), name.substring(idx + 1));
        }
    }

    return new Pair<String, String>(name, "");
}
 
Example 9
Project: alfresco-repository   File: RetryingTransactionHelperTest.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTimeLimit()
{
    final RetryingTransactionHelper txnHelper = new RetryingTransactionHelper();
    txnHelper.setTransactionService(transactionService);
    txnHelper.setMaxExecutionMs(3000);
    final List<Throwable> caughtExceptions = Collections.synchronizedList(new LinkedList<Throwable>());

    // Try submitting a request after a timeout
    runThreads(txnHelper, caughtExceptions, new Pair(0, 1000), new Pair(0, 5000), new Pair(4000, 1000));
    assertEquals("Expected 1 exception", 1, caughtExceptions.size());
    assertTrue("Excpected TooBusyException", caughtExceptions.get(0) instanceof TooBusyException);

    // Stay within timeout limits
    caughtExceptions.clear();
    runThreads(txnHelper, caughtExceptions, new Pair(0, 1000), new Pair(0, 2000), new Pair(0, 1000), new Pair(1000, 1000), new Pair(1000, 2000), new Pair(2000, 1000));
    if (caughtExceptions.size() > 0)
    {
        throw new RuntimeException("Unexpected exception", caughtExceptions.get(0));
    }
}
 
Example 10
Project: alfresco-repository   File: AuditDAOTest.java   View source code 6 votes vote down vote up
public void testAuditModel() throws Exception
{
    final File file = AbstractContentTransformerTest.loadQuickTestFile("pdf");
    assertNotNull(file);
    final URL url = new URL("file:" + file.getAbsolutePath());
    RetryingTransactionCallback<Pair<Long, ContentData>> callback = new RetryingTransactionCallback<Pair<Long, ContentData>>()
    {
        public Pair<Long, ContentData> execute() throws Throwable
        {
            Pair<Long, ContentData> auditModelPair = auditDAO.getOrCreateAuditModel(url);
            return auditModelPair;
        }
    };
    Pair<Long, ContentData> configPair = txnHelper.doInTransaction(callback);
    assertNotNull(configPair);
    // Now repeat.  The results should be exactly the same.
    Pair<Long, ContentData> configPairCheck = txnHelper.doInTransaction(callback);
    assertNotNull(configPairCheck);
    assertEquals(configPair, configPairCheck);
}
 
Example 11
Project: alfresco-repository   File: TransformerPropertySetter.java   View source code 6 votes vote down vote up
/**
 * Removes transformer properties from the supplied multi line propertyNames.
 * @param propertyNames which optionally include a value
 * @throws IllegalArgumentException if an unexpected line is found
 */
public int removeProperties(String propertyNames)
{
    Set<String> remove = new HashSet<String>();
    Map<String, String> transformerReferences = new HashMap<String, String>();
    Set<String> dynamicTransformerNames = new HashSet<String>();
    Properties defaultProperties = transformerProperties.getDefaultProperties();
    for (String propertyNameAndValue: extractProperties(propertyNames, false, transformerReferences, dynamicTransformerNames))
    {
        Pair<String, String> pair = splitNameAndValue(propertyNameAndValue);
        String propertyName = pair.getFirst();
        if (transformerProperties.getProperty(propertyName) == null)
        {
            throw unexpectedProperty("Does not exist", propertyName);
        }
        if (defaultProperties.getProperty(propertyName) != null)
        {
            throw unexpectedProperty("Is a deafult property so may not be removed", propertyName);
        }
        remove.add(propertyName);
    }
    transformerProperties.removeProperties(remove);
    return remove.size();
}
 
Example 12
Project: alfresco-repository   File: QNamePatch.java   View source code 6 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    // We don't need to catch the potential InvalidQNameException here as it will be caught
    // in AbstractPatch and correctly handled there
    QName qnameBefore = QName.createQName(this.qnameStringBefore);
    QName qnameAfter = QName.createQName(this.qnameStringAfter);

    Long maxNodeId = patchDAO.getMaxAdmNodeID();
    
    Pair<Long, QName> before = qnameDAO.getQName(qnameBefore);
    
    if (before != null)
    {
        for (Long i = 0L; i < maxNodeId; i+=BATCH_SIZE)
        {
            Work work = new Work(before.getFirst(), i);
            retryingTransactionHelper.doInTransaction(work, false, true);
        }
        qnameDAO.updateQName(qnameBefore, qnameAfter);
    }

    return I18NUtil.getMessage(MSG_SUCCESS, qnameBefore, qnameAfter);
}
 
Example 13
Project: alfresco-repository   File: AbstractAclCrudDAOImpl.java   View source code 6 votes vote down vote up
public Permission createPermission(PermissionReference permissionReference)
{
    ParameterCheck.mandatory("permissionReference", permissionReference);
    
    PermissionEntity entity = null;
    
    // Get the persistent ID for the QName
    Pair<Long, QName> qnamePair = qnameDAO.getOrCreateQName(permissionReference.getQName());
    if (qnamePair != null)
    {
        Long qnameId  = qnamePair.getFirst();
        entity = new PermissionEntity(qnameId, permissionReference.getName());
        
        entity.setVersion(0L);
        
        Pair<Long, PermissionEntity> entityPair = permissionEntityCache.getOrCreateByValue(entity);
        entity = entityPair.getSecond();
    }
    return entity;
}
 
Example 14
Project: alfresco-repository   File: VirtualStoreImpl.java   View source code 6 votes vote down vote up
@Override
public PagingResults<Reference> list(Reference ref, boolean actual, boolean virtual, Set<QName> searchTypeQNames,
            Set<QName> ignoreTypeQNames, Set<QName> ignoreAspectQNames, List<Pair<QName, Boolean>> sortProps,
            PagingRequest pagingRequest) throws VirtualizationException
{
    // TODO: find null string value for pattern
    return list(ref,
                actual,
                virtual,
                true,
                true,
                null,
                searchTypeQNames,
                Collections.<QName> emptySet(),
                ignoreAspectQNames,
                sortProps,
                pagingRequest);
}
 
Example 15
Project: alfresco-remote-api   File: QuickShareLinksImpl.java   View source code 5 votes vote down vote up
@Override
public Rendition getRendition(String sharedId, String renditionId)
{
    checkEnabled();
    checkValidShareId(sharedId);

    try
    {
        Pair<String, NodeRef> pair = quickShareService.getTenantNodeRefFromSharedId(sharedId);

        String networkTenantDomain = pair.getFirst();
        final NodeRef nodeRef = pair.getSecond();

        return TenantUtil.runAsSystemTenant(() ->
        {
            String nodeId = nodeRef.getId();
            Parameters params = getParamsWithCreatedStatus();
            return renditions.getRendition(nodeId, renditionId, params);

        }, networkTenantDomain);
    }
    catch (InvalidSharedIdException ex)
    {
        logger.warn("Unable to find: " + sharedId);
        throw new EntityNotFoundException(sharedId);
    }
    catch (InvalidNodeRefException inre)
    {
        logger.warn("Unable to find: " + sharedId + " [" + inre.getNodeRef() + "]");
        throw new EntityNotFoundException(sharedId);
    }
}
 
Example 16
Project: alfresco-core   File: DefaultFallbackEncryptor.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Pair<byte[], AlgorithmParameters> encryptObject(String keyAlias,
        AlgorithmParameters params, Object input)
{
    // Note: encrypt supported only for main encryptor
    Pair<byte[], AlgorithmParameters> ret = main.encryptObject(keyAlias, params, input);
    return ret;
}
 
Example 17
Project: alfresco-audit   File: ConsolidateActiveUsersAuditJob.java   View source code 5 votes vote down vote up
protected void recordTimeframes(final String userName, final Set<Pair<String, String>> timeframes)
{
    for (final Pair<String, String> timeframe : timeframes)
    {
        final String timeframeStart = timeframe.getFirst();
        final String timeframeEnd = timeframe.getSecond();

        final boolean exists = this.checkEntryExists(userName, timeframeStart, timeframeEnd);

        if (!exists)
        {
            // recording should be done using the proper user name
            AuthenticationUtil.clearCurrentSecurityContext();
            AuthenticationUtil.setRunAsUser(userName);

            final String rootPath = AuditApplication.buildPath(AuditModuleConstants.AUDIT_PRODUCER_ROOT_PATH,
                    ConsolidateActiveUsersAuditJob.class.getSimpleName());
            final Map<String, Serializable> auditMap = new HashMap<>();
            auditMap.put("userName", userName);
            auditMap.put("timeframeStart", timeframeStart);
            auditMap.put("timeframeEnd", timeframeEnd);

            LOGGER.debug("Recording 'new' active user time frame {} to {}", timeframeStart, timeframeEnd);
            this.auditComponent.recordAuditValuesWithUserFilter(rootPath, auditMap, false);

            // reset for next iteration
            AuthenticationUtil.clearCurrentSecurityContext();
            AuthenticationUtil.setRunAsUserSystem();
        }
    }
}
 
Example 18
Project: alfresco-repository   File: AbstractNodeDAOImpl.java   View source code 5 votes vote down vote up
/**
 * @return              Returns a writable copy of the cached aspects set
 */
private Set<QName> getNodeAspectsCached(Long nodeId)
{
    NodeVersionKey nodeVersionKey = getNodeNotNull(nodeId, false).getNodeVersionKey();
    Pair<NodeVersionKey, Set<QName>> cacheEntry = aspectsCache.getByKey(nodeVersionKey);
    if (cacheEntry == null)
    {
        invalidateNodeCaches(nodeId);
        throw new DataIntegrityViolationException("Invalid node ID: " + nodeId);
    }
    return new HashSet<QName>(cacheEntry.getSecond());
}
 
Example 19
Project: alfresco-repository   File: RepoRemoteService.java   View source code 5 votes vote down vote up
/**
 * Utility for getting the parent NodeRef of a relative path.
 * @param base The base node ref.
 * @param path The relative path.
 * @return A Pair with the parent node ref and the name of the child.
 */
private Pair<NodeRef, String> getParentChildRelative(NodeRef base, String path)
{
    List<String> pathList = splitPath(path);
    NodeRef parent;
    String name = null;
    if (pathList.size() == 1)
    {
        parent = base;
        name = pathList.get(0);
    }
    else
    {
        try
        {
            name = pathList.get(pathList.size() - 1);
            pathList.remove(pathList.size() - 1);
            FileInfo info = fFileFolderService.resolveNamePath(base, pathList);
            parent = info.getNodeRef();
        }
        catch (FileNotFoundException e)
        {
            throw new AlfrescoRuntimeException("Not Found: " + pathList, e);
        }
    }
    return new Pair<NodeRef, String>(parent, name);
}
 
Example 20
Project: alfresco-repository   File: DbNodeServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Gets, converts and adds the intrinsic properties to the current node's properties
 */
private Map<QName, Serializable> getPropertiesImpl(Pair<Long, NodeRef> nodePair) throws InvalidNodeRefException
{
    Long nodeId = nodePair.getFirst();
    Map<QName, Serializable> nodeProperties = nodeDAO.getNodeProperties(nodeId);
    // done
    return nodeProperties;
}
 
Example 21
Project: alfresco-repository   File: AbstractEncodingDAOImpl.java   View source code 5 votes vote down vote up
@Override
public Pair<Long, String> findByValue(String encoding)
{
    EncodingEntity entity = getEncodingEntity(encoding);
    if (entity == null)
    {
        return null;
    }
    else
    {
        return new Pair<Long, String>(entity.getId(), encoding);
    }
}
 
Example 22
Project: alfresco-repository   File: MimetypeDAOTest.java   View source code 5 votes vote down vote up
public void testCaseInsensitivity() throws Exception
{
    String mimetype = "AAA-" + GUID.generate();
    Pair<Long, String> lowercasePair = get(mimetype.toLowerCase(), true, true);
    final Long id = lowercasePair.getFirst();
    // Check that the same pair is retrievable using uppercase
    Pair<Long, String> uppercasePair = get(mimetype.toUpperCase(), true, true);
    assertNotNull(uppercasePair);
    assertEquals(
            "Upper and lowercase mimetype instance IDs were not the same",
            id, uppercasePair.getFirst());

    // Ensure that the mimetype is persisted and cached in lowercase
    assertEquals(mimetype.toLowerCase(), lowercasePair.getSecond());
    assertEquals(mimetype.toLowerCase(), uppercasePair.getSecond());

    // Check lower case values come back from update.
    String mimetypeFoobar = "APPLICATION/FOOBAR/"+GUID.generate();
    Pair<Long, String> updatedMimetype = update(mimetype, mimetypeFoobar);
    assertEquals(id, updatedMimetype.getFirst());
    assertEquals(mimetypeFoobar.toLowerCase(), updatedMimetype.getSecond());

    // Fresh retrieval - explicit check with lower and upper case for clarity.
    updatedMimetype = get(mimetypeFoobar.toUpperCase(), false, true);
    assertNotNull(updatedMimetype);
    assertEquals(id, updatedMimetype.getFirst());
    assertEquals(mimetypeFoobar.toLowerCase(), updatedMimetype.getSecond());

    updatedMimetype = get(mimetypeFoobar.toLowerCase(), false, true);
    assertNotNull(updatedMimetype);
    assertEquals(id, updatedMimetype.getFirst());
    assertEquals(mimetypeFoobar.toLowerCase(), updatedMimetype.getSecond());
}
 
Example 23
Project: alfresco-repository   File: AbstractNodeDAOImpl.java   View source code 5 votes vote down vote up
@Override
public List<Path> getPaths(Pair<Long, NodeRef> nodePair, boolean primaryOnly) throws InvalidNodeRefException
{
    // create storage for the paths - only need 1 bucket if we are looking for the primary path
    List<Path> paths = new ArrayList<Path>(primaryOnly ? 1 : 10);
    // create an empty current path to start from
    Path currentPath = new Path();
    // create storage for touched associations
    Stack<Long> assocIdStack = new Stack<Long>();
    
    // call recursive method to sort it out
    prependPaths(nodePair, null, currentPath, paths, assocIdStack, primaryOnly);
    
    // check that for the primary only case we have exactly one path
    if (primaryOnly && paths.size() != 1)
    {
        throw new RuntimeException("Node has " + paths.size() + " primary paths: " + nodePair);
    }
    
    // done
    if (loggerPaths.isDebugEnabled())
    {
        StringBuilder sb = new StringBuilder(256);
        if (primaryOnly)
        {
            sb.append("Primary paths");
        }
        else
        {
            sb.append("Paths");
        }
        sb.append(" for node ").append(nodePair);
        for (Path path : paths)
        {
            sb.append("\n").append("   ").append(path);
        }
        loggerPaths.debug(sb);
    }
    return paths;
}
 
Example 24
Project: alfresco-repository   File: EntityLookupCacheTest.java   View source code 5 votes vote down vote up
public Pair<Long, Object> findByKey(Long key)
{
    assertNotNull(key);

    String dbValue = database.get(key);
    if (dbValue == null)
    {
        return null;
    }
    // Make a value object
    TestValue value = new TestValue(dbValue);
    return new Pair<Long, Object>(key, value);
}
 
Example 25
Project: alfresco-repository   File: SolrJSONResultSet.java   View source code 5 votes vote down vote up
@Override
public List<Pair<String, Integer>> getFieldFacet(String field)
{
    List<Pair<String, Integer>> answer = fieldFacets.get(field);
    if(answer != null)
    {
        return answer;
    }
    else
    {
        return Collections.<Pair<String, Integer>>emptyList();
    }
}
 
Example 26
Project: alfresco-repository   File: DoNothingCopyBehaviourCallback.java   View source code 5 votes vote down vote up
@Override
public Pair<AssocCopySourceAction, AssocCopyTargetAction> getAssociationCopyAction(QName classQName,
        CopyDetails copyDetails, CopyAssociationDetails assocCopyDetails)
{
    return new Pair<AssocCopySourceAction, AssocCopyTargetAction>(AssocCopySourceAction.IGNORE, 
            AssocCopyTargetAction.USE_COPIED_OTHERWISE_ORIGINAL_TARGET);
}
 
Example 27
Project: alfresco-repository   File: AbstractContentDataDAOImpl.java   View source code 5 votes vote down vote up
/**
 * Looks the node up based on the NodeRef of the given node
 */
@Override
public Pair<Long, ContentUrlEntity> findByValue(ContentUrlEntity entity)
{
    String contentUrl = entity.getContentUrl();
    ContentUrlEntity ret = getContentUrlEntity(contentUrl);
    return (ret != null ? new Pair<Long, ContentUrlEntity>(ret.getId(), ret) : null);
}
 
Example 28
Project: alfresco-repository   File: VirtualFileFolderServiceExtension.java   View source code 5 votes vote down vote up
@Override
public PagingResults<FileInfo> list(NodeRef contextNodeRef, boolean files, boolean folders, Set<QName> ignoreQNames,
            List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest)
{

    return VirtualFileFolderServiceExtension.this.list(contextNodeRef,
                                                       files,
                                                       folders,
                                                       null,
                                                       ignoreQNames,
                                                       sortProps,
                                                       pagingRequest);
}
 
Example 29
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 5 votes vote down vote up
/**
 * Check that the <code>ContentData</code> is decoded and persisted correctly.
 */
public void testCreateContentDataNulls() throws Exception
{
    ContentData contentData = new ContentData(null, null, 0L, null, null);
    
    Pair<Long, ContentData> resultPair = create(contentData);
    getAndCheck(resultPair.getFirst(), contentData);
}
 
Example 30
Project: alfresco-repository   File: AbstractContentDataDAOImpl.java   View source code 5 votes vote down vote up
public Pair<Long, ContentData> findByKey(Long key)
{
    ContentDataEntity contentDataEntity = getContentDataEntity(key);
    if (contentDataEntity == null)
    {
        return null;
    }
    ContentData contentData = makeContentData(contentDataEntity);
    // Done
    return new Pair<Long, ContentData>(key, contentData);
}
 
Example 31
Project: alfresco-repository   File: AbstractAclCrudDAOImpl.java   View source code 5 votes vote down vote up
public Pair<Long, AclEntity> findByValue(AclEntity value)
{
    if ((value != null) && (value.getId() != null))
    {
        return findByKey(value.getId());
    }
    return null;
}
 
Example 32
Project: alfresco-repository   File: SOLRTrackingComponentImpl.java   View source code 5 votes vote down vote up
/**
 * Does a 'breadth first' search of ancestors, caching as it goes
 * @param nodeIds initial list of nodes to visit
 * @return all visited nodes, in no particular order
 */
private List<Long> cacheAncestors(List<Long> nodeIds)
{
    final LinkedList<Long> toVisit = new LinkedList<Long>(nodeIds);
    Set<Long> visited = new TreeSet<Long>();
    Long nodeId;
    nodeDAO.cacheNodesById(toVisit);
    Long lastCached = toVisit.peekLast();
    while ((nodeId = toVisit.pollFirst()) != null)
    {
        if (visited.add(nodeId) && (nodeDAO.getNodeIdStatus(nodeId) != null) && (false == nodeDAO.getNodeIdStatus(nodeId).isDeleted()))
        {
            nodeDAO.getParentAssocs(nodeId, null, null, null, new ChildAssocRefQueryCallback()
            {
                @Override
                public boolean preLoadNodes()
                {
                    return false;
                }

                @Override
                public boolean orderResults()
                {
                    return false;
                }

                @Override
                public boolean handle(Pair<Long, ChildAssociationRef> childAssocPair,
                        Pair<Long, NodeRef> parentNodePair, Pair<Long, NodeRef> childNodePair)
                {
                    toVisit.add(parentNodePair.getFirst());
                    return true;
                }

                @Override
                public void done()
                {
                }
            });
        }
        final boolean nodeIdEqualsLastCached = (nodeId == null && lastCached == null) ||
                                               (nodeId != null && nodeId.equals(lastCached));
        if (nodeIdEqualsLastCached && !toVisit.isEmpty())
        {
            nodeDAO.cacheNodesById(toVisit);
            lastCached = toVisit.peekLast();
        }
    }
    return new ArrayList<Long>(visited);
}
 
Example 33
Project: alfresco-repository   File: ContentDiskDriverTest.java   View source code 5 votes vote down vote up
/**
 * Searching for file object with specified name or creating new one if such object is not exist
 * 
 * @param parentRef - {@link NodeRef} of desired parent object
 * @param name - {@link String} value for name of desired file object
 * @param type - {@link QName} instance which determines type of the object. It may be cm:content, cm:folder etc (see {@link ContentModel})
 * @return {@link Pair}&lt;{@link org.alfresco.service.cmr.model.FileInfo}, {@link Boolean}> instance which contains {@link NodeRef} of newly created object and
 *         <code>true</code> value if file object with specified name was not found or {@link NodeRef} of existent file object and <code>false</code> in other case
 */
private Pair<org.alfresco.service.cmr.model.FileInfo, Boolean> getOrCreateNode(NodeRef parentRef, String name, QName type)
{
    NodeRef result = nodeService.getChildByName(parentRef, ContentModel.ASSOC_CONTAINS, name);
    Boolean created = false;
    if (null == result)
    {
        result = nodeService.getChildByName(parentRef, ContentModel.ASSOC_CHILDREN, name);
    }
    if (created = (null == result))
    {
        result = fileFolderService.create(parentRef, name, type).getNodeRef();
    }
    return new Pair<org.alfresco.service.cmr.model.FileInfo, Boolean>(fileFolderService.getFileInfo(result), created);
}
 
Example 34
Project: alfresco-repository   File: SiteMembershipComparator.java   View source code 5 votes vote down vote up
public SiteMembershipComparator(List<Pair<? extends Object, SortOrder>> sortPairs, Type comparatorType)
{
    if (sortPairs.size() < 1)
    {
        throw new IllegalArgumentException("Must provide at least one sort criterion");
    }
    this.sortPairs = sortPairs;
    this.comparatorType = comparatorType;
}
 
Example 35
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 5 votes vote down vote up
private Pair<Long, ContentData> create(final ContentData contentData)
{
    RetryingTransactionCallback<Pair<Long, ContentData>> callback = new RetryingTransactionCallback<Pair<Long, ContentData>>()
    {
        public Pair<Long, ContentData> execute() throws Throwable
        {
            Pair<Long, ContentData> contentDataPair = contentDataDAO.createContentData(contentData);
            return contentDataPair;
        }
    };
    return txnHelper.doInTransaction(callback, false, false);
}
 
Example 36
Project: alfresco-repository   File: DbNodeServiceImpl.java   View source code 5 votes vote down vote up
/**
 * When searching for <code>primaryOnly == true</code>, checks that there is exactly
 * one path.
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public List<Path> getPaths(NodeRef nodeRef, boolean primaryOnly) throws InvalidNodeRefException
{
    // get the starting node
    Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
    
    return nodeDAO.getPaths(nodePair, primaryOnly);
}
 
Example 37
Project: alfresco-repository   File: AbstractNodeDAOImpl.java   View source code 5 votes vote down vote up
@Override
public Pair<Long, StoreRef> getStore(StoreRef storeRef)
{
    Pair<StoreRef, Node> rootNodePair = rootNodesCache.getByKey(storeRef);
    if (rootNodePair == null)
    {
        return null;
    }
    else
    {
        return new Pair<Long, StoreRef>(rootNodePair.getSecond().getStore().getId(), rootNodePair.getFirst());
    }
}
 
Example 38
Project: alfresco-remote-api   File: ShareContentGet.java   View source code 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    if (! isEnabled())
    {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "QuickShare is disabled system-wide");
    }
    
    // create map of params (template vars)
    Map<String, String> params = req.getServiceMatch().getTemplateVars();
    final String sharedId = params.get("shared_id");
    if (sharedId == null)
    {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "A valid sharedId must be specified !");
    }
    
    try
    {
        Pair<String, NodeRef> pair = quickShareService.getTenantNodeRefFromSharedId(sharedId);
        final String tenantDomain = pair.getFirst();
        final NodeRef nodeRef = pair.getSecond();
        
        String siteId = siteService.getSiteShortName(nodeRef);
        
        Map<String, Object> model = new HashMap<String, Object>(3);
        model.put("sharedId", sharedId);
        model.put("nodeRef", nodeRef.toString());
        model.put("siteId", siteId);
        model.put("tenantDomain", tenantDomain);
        
        if (logger.isInfoEnabled())
        {
            logger.info("QuickShare - get shared context: "+sharedId+" ["+model+"]");
        }
        
        return model;
    }
    catch (InvalidNodeRefException inre)
    {
        logger.error("Unable to find: "+sharedId+" ["+inre.getNodeRef()+"]");
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find: "+sharedId);
    }
}
 
Example 39
Project: alfresco-repository   File: TaggingServiceImpl.java   View source code 5 votes vote down vote up
public Pair<List<String>, Integer> getPagedTags(StoreRef storeRef, String filter, int fromTag, int pageSize)
{
    ParameterCheck.mandatory("storeRef", storeRef);
    ParameterCheck.mandatory("fromTag", fromTag);
    ParameterCheck.mandatory("pageSize", pageSize);

    if (filter == null || filter.length() == 0)
    {
        return getPagedTags(storeRef, fromTag, pageSize);
    }
    else
    {
        Collection<ChildAssociationRef> rootCategories = this.categoryService.getRootCategories(storeRef, ContentModel.ASPECT_TAGGABLE, filter);

        final int totalCount = rootCategories.size();
        final int startIndex = Math.max(fromTag, 0);
        final int endIndex = Math.min(fromTag + pageSize, totalCount);
        List<String> result = new ArrayList<String>(pageSize);
        int index = 0;
        // paging for not sorted tag names
        for (ChildAssociationRef rootCategory : rootCategories)
        {
            if (startIndex > index++)
            {
                continue;
            }
            String name = (String)this.nodeService.getProperty(rootCategory.getChildRef(), ContentModel.PROP_NAME);
                result.add(name);
            if (index == endIndex)
            {
                break;
            }
        }
        return new Pair<List<String>, Integer> (result, totalCount);
    }
}
 
Example 40
Project: alfresco-repository   File: RegistryServiceImpl.java   View source code 5 votes vote down vote up
public Collection<String> getChildElements(RegistryKey key)
{
    // Get the path without creating it
    Pair<NodeRef, QName> keyPair = getPath(key, false);
    if (keyPair == null)
    {
        // Nothing at that path
        return Collections.<String>emptyList();
    }
    // Use a query to find the children
    RegexQNamePattern qnamePattern = new RegexQNamePattern(key.getNamespaceUri(), ".*");
    List<ChildAssociationRef> childAssocRefs = nodeService.getChildAssocs(
            keyPair.getFirst(),
            ContentModel.ASSOC_CHILDREN,
            qnamePattern);
    // The localname of each one of the child associations represents a path element
    Collection<String> results = new ArrayList<String>(childAssocRefs.size());
    for (ChildAssociationRef assocRef : childAssocRefs)
    {
        results.add(assocRef.getQName().getLocalName());
    }
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Retrieved child elements from registry: \n" +
                "   Key:      " + key + "\n" +
                "   Elements: " + results);
    }
    return results;
}