Java Code Examples for org.alfresco.util.Pair

The following examples show how to use org.alfresco.util.Pair. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private CannedQueryResults<NodeRef> executeGetPeopleQuery(
        final PagingRequest pagingRequest,
        final String pattern,
        final List<QName> filterProps,
        final boolean includeAdministrators,
        final List<Pair<QName, Boolean>> sortProps)
{
    GetPeopleCannedQueryFactory getPeopleCannedQueryFactory = (GetPeopleCannedQueryFactory) cannedQueryRegistry.getNamedObject(CANNED_QUERY_PEOPLE_LIST);
    final GetPeopleCannedQuery cq = (GetPeopleCannedQuery) getPeopleCannedQueryFactory
            .getCannedQuery(
                    personService.getPeopleContainer(),
                    pattern,
                    filterProps,
                    null,
                    null,
                    includeAdministrators,
                    sortProps,
                    pagingRequest);

    return transactionService.getRetryingTransactionHelper().doInTransaction(cq::execute, true);
}
 
Example 2
private VisitedNode(
        Long id,
        NodeRef nodeRef,
        QName type,
        Long aclId,
        Pair<Long, ChildAssociationRef> primaryParentAssocPair)
{
    this.id = id;
    this.nodeRef = nodeRef;
    this.nodeType = type;
    this.aclId = aclId;
    this.primaryParentAssocPair = primaryParentAssocPair;
    this.secondaryParentAssocs = new ArrayList<Pair<Long,ChildAssociationRef>>(17);
    this.secondaryChildAssocs = new ArrayList<Pair<Long,ChildAssociationRef>>(17);
    this.targetAssocs = new ArrayList<Pair<Long,AssociationRef>>();
    this.sourceAssocs = new ArrayList<Pair<Long,AssociationRef>>();
}
 
Example 3
/**
 * 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 4
public Pair<Long, String> getMimetype(Long id)
{
    // Check the cache
    String mimetype = (String) mimetypeEntityCache.get(id);
    if (mimetype != null)
    {
        return new Pair<Long, String>(id, mimetype);
    }
    // Get it from the DB
    MimetypeEntity mimetypeEntity = getMimetypeEntity(id);
    if (mimetypeEntity == null)
    {
        throw new AlfrescoRuntimeException("The MimetypeEntity ID " + id + " doesn't exist.");
    }
    mimetype = mimetypeEntity.getMimetype();
    // Cache it
    mimetypeEntityCache.put(mimetype, id);
    mimetypeEntityCache.put(id, mimetype);
    // Done
    return new Pair<Long, String>(id, mimetype);
}
 
Example 5
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 6
/**
 * Get a report from a nodeId with the associated txId and the indexing status
 *
 * Synchronous execution
 *
 * @param params Query Request with following parameters:
 * - nodeId, mandatory: the number of the node to build the report
 * - core, The name of the SOLR Core or "null" to get the report for every core
 * @return Response including the action result:
 * - report: An Object with the report details
 * - error: When mandatory parameters are not set, an error node is returned
 *
 * @throws JSONException
 */
private NamedList<Object> actionNODEREPORTS(SolrParams params) throws JSONException
{

    NamedList<Object> report = new SimpleOrderedMap<>();

    if (params.get(ARG_NODEID) == null)
    {
        report.add(ACTION_STATUS_ERROR, "No " + ARG_NODEID +" parameter set.");
        return report;
    }

    Long nodeid = Long.valueOf(params.get(ARG_NODEID));
    String requestedCoreName = coreName(params);

    coreNames().stream()
            .filter(coreName -> requestedCoreName == null || coreName.equals(requestedCoreName))
            .filter(trackerRegistry::hasTrackersForCore)
            .map(coreName -> new Pair<>(coreName, coreStatePublisher(coreName)))
            .filter(coreNameAndPublisher -> coreNameAndPublisher.getSecond() != null)
            .forEach(coreNameAndPublisher ->
                    report.add(
                            coreNameAndPublisher.getFirst(),
                            buildNodeReport(coreNameAndPublisher.getSecond(), nodeid)));
    return report;
}
 
Example 7
public Query getCMISQuery(CMISQueryMode mode, Pair<SearchParameters, Boolean> searchParametersAndFilter, SolrQueryRequest req, org.alfresco.repo.search.impl.querymodel.Query queryModelQuery, CmisVersion cmisVersion, String alternativeDictionary) throws ParseException
{
    SearchParameters searchParameters = searchParametersAndFilter.getFirst();
    Boolean isFilter = searchParametersAndFilter.getSecond();

    CmisFunctionEvaluationContext functionContext = getCMISFunctionEvaluationContext(mode, cmisVersion, alternativeDictionary);

    Set<String> selectorGroup = queryModelQuery.getSource().getSelectorGroups(functionContext).get(0);

    LuceneQueryBuilderContext<Query, Sort, ParseException> luceneContext = getLuceneQueryBuilderContext(searchParameters, req, alternativeDictionary, FTSQueryParser.RerankPhase.SINGLE_PASS);
    @SuppressWarnings("unchecked")
    LuceneQueryBuilder<Query, Sort, ParseException> builder = (LuceneQueryBuilder<Query, Sort, ParseException>) queryModelQuery;
    org.apache.lucene.search.Query luceneQuery = builder.buildQuery(selectorGroup, luceneContext, functionContext);

    return new ContextAwareQuery(luceneQuery, Boolean.TRUE.equals(isFilter) ? null : searchParameters);
}
 
Example 8
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 9
/**
 * Inspect a resource to find operations on it.
 * @param api Api
 * @param entityPath String
 * @param metainfo resource metadata
 */
public static void inspectOperations(Api api, Class<?> resource, final String entityPath, List<ResourceMetadata> metainfo)
{
    Map<String,Pair<ResourceOperation,Method>> operations = findOperations(entityPath, resource);
    if (operations != null && !operations.isEmpty())
    {
        for (Entry<String, Pair<ResourceOperation, Method>> opera : operations.entrySet())
        {
            Method annotatedMethod = opera.getValue().getSecond();
            final boolean isNoAuthRequired = isNoAuth(annotatedMethod);

            if (isDeleted(annotatedMethod))
            {
                metainfo.add(new OperationResourceMetaData(opera.getKey(), api, new HashSet(Arrays.asList(opera.getValue().getFirst())), isNoAuthRequired));
            }
            else
            {
                metainfo.add(new OperationResourceMetaData(opera.getKey(), Arrays.asList(opera.getValue().getFirst()), api, annotatedMethod, isNoAuthRequired));
            }
        }
    }
}
 
Example 10
@Override
  protected List<SiteMembership> queryAndFilter(CannedQueryParameters parameters)
  {
      SiteMembersCannedQueryParams paramBean = (SiteMembersCannedQueryParams)parameters.getParameterBean();
      
      String siteShortName = paramBean.getShortName();
      boolean collapseGroups = paramBean.isCollapseGroups();

CannedQuerySortDetails sortDetails = parameters.getSortDetails();
List<Pair<? extends Object, SortOrder>> sortPairs = sortDetails.getSortPairs();

  	final CQSiteMembersCallback callback = new CQSiteMembersCallback(siteShortName, sortPairs);
  	siteService.listMembers(siteShortName, null, null, collapseGroups, callback);
  	callback.done();

      return callback.getSiteMembers();
  }
 
Example 11
public Map<ACLType, Integer> patchAcls()
{
    CounterSet result = new CounterSet();
    List<Pair<Long, StoreRef>> stores = nodeDAO.getStores();

    for (Pair<Long, StoreRef> pair : stores)
    {
        CounterSet update;
        Long rootNodeId = nodeDAO.getRootNode(pair.getSecond()).getFirst();
        update = fixOldDmAcls(rootNodeId, nodeDAO.getNodeAclId(rootNodeId), (Long)null, true);
        result.add(update);
    }

    HashMap<ACLType, Integer> toReturn = new HashMap<ACLType, Integer>();
    toReturn.put(ACLType.DEFINING, Integer.valueOf(result.get(ACLType.DEFINING).getCounter()));
    toReturn.put(ACLType.FIXED, Integer.valueOf(result.get(ACLType.FIXED).getCounter()));
    toReturn.put(ACLType.GLOBAL, Integer.valueOf(result.get(ACLType.GLOBAL).getCounter()));
    toReturn.put(ACLType.LAYERED, Integer.valueOf(result.get(ACLType.LAYERED).getCounter()));
    toReturn.put(ACLType.OLD, Integer.valueOf(result.get(ACLType.OLD).getCounter()));
    toReturn.put(ACLType.SHARED, Integer.valueOf(result.get(ACLType.SHARED).getCounter()));
    return toReturn;
}
 
Example 12
/**
 * Defers to the typed service
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public StoreRef createStore(String protocol, String identifier)
{
    StoreRef storeRef = new StoreRef(protocol, identifier);
    
    // invoke policies
    invokeBeforeCreateStore(ContentModel.TYPE_STOREROOT, storeRef);
    
    // create a new one
    Pair<Long, NodeRef> rootNodePair = nodeDAO.newStore(storeRef);
    NodeRef rootNodeRef = rootNodePair.getSecond();
    
    // invoke policies
    invokeOnCreateStore(rootNodeRef);
    
    // Done
    return storeRef;
}
 
Example 13
@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 qnameType = QName.createQName(this.qnameStringType);
    QName qnameAspect = QName.createQName(this.qnameStringAspect);

    Long maxNodeId = patchDAO.getMaxAdmNodeID();
    
    Pair<Long, QName> type = qnameDAO.getQName(qnameType);
    Pair<Long, QName> aspect = qnameDAO.getQName(qnameAspect);
    
    if (type != null && aspect != null)
    {
        for (Long i = 0L; i < maxNodeId; i+=BATCH_SIZE)
        {
            Work work = new Work(type, aspect, i);
            retryingTransactionHelper.doInTransaction(work, false, true);
        }
    }

    return I18NUtil.getMessage(MSG_SUCCESS, qnameAspect, qnameType);
}
 
Example 14
@Override
protected AuditApplicationEntity getAuditApplicationByName(String appName)
{
    // Resolve the name as a property ID
    Pair<Long, Serializable> appNamePair = propertyValueDAO.getPropertyValue(appName);
    if (appNamePair == null)
    {
        // There will be no results
        return null;
    }
    
    Map<String, Object> params = new HashMap<String, Object>(11);
    params.put("id", appNamePair.getFirst());
    AuditApplicationEntity entity = template.selectOne(
            SELECT_APPLICATION_BY_NAME_ID,
            params);
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Searched for audit application '" + appName + "' and found: " + entity);
    }
    return entity;
}
 
Example 15
public void testBasicBytes_WithKey()
{
    byte[] bytes = new byte[] {11, 12, 13};

    Pair<byte[], AlgorithmParameters> encryptedPair = encryptor.encrypt("mykey1", null, bytes);
    byte[] decrypted = encryptor.decrypt(
            "mykey1",
            encryptedPair.getSecond(),
            encryptedPair.getFirst());
    assertTrue("Encryption round trip failed. ", Arrays.equals(bytes, decrypted));
}
 
Example 16
/**
 * Walk a hierachy
 */
public void walkHierarchy(Pair<Long, NodeRef> nodePair, Pair<Long, ChildAssociationRef> parentAssocPair)
{
    Long nodeId = nodePair.getFirst();
    NodeRef nodeRef = nodePair.getSecond();
    QName nodeType = nodeDAO.getNodeType(nodeId);
    Long nodeAclId = nodeDAO.getNodeAclId(nodeId);
    // Record the first node (parent)
    VisitedNode visitedNode = new VisitedNode(nodeId, nodeRef, nodeType, nodeAclId, parentAssocPair);
    nodesVisitedById.put(nodeId, visitedNode);
    nodesVisitedByNodeRef.put(nodeRef, visitedNode);
    // Now walk
    walkNode(nodeId);
}
 
Example 17
public List<Tag> addTags(String nodeId, final List<Tag> tags)
{
        NodeRef nodeRef = nodes.validateNode(nodeId);
		if(!typeConstraint.matches(nodeRef))
		{
			throw new UnsupportedResourceOperationException("Cannot tag this node");
		}

        List<String> tagValues = new AbstractList<String>()
           {
               @Override
               public String get(int arg0)
               {
               	String tag = tags.get(arg0).getTag();
                   return tag;
               }
   
               @Override
               public int size()
               {
                   return tags.size();
               }
           };
           try
           {
	        List<Pair<String, NodeRef>> tagNodeRefs = taggingService.addTags(nodeRef, tagValues);
	        List<Tag> ret = new ArrayList<Tag>(tags.size());
	        for(Pair<String, NodeRef> pair : tagNodeRefs)
	        {
	        	ret.add(new Tag(pair.getSecond(), pair.getFirst()));
	        }
	        return ret;
           }
           catch(IllegalArgumentException e)
           {
           	throw new InvalidArgumentException(e.getMessage());
           }
}
 
Example 18
public RandomRoutingContentStore(ContentStore ... stores)
{
    this.stores = new ArrayList<ContentStore>(5);
    for (ContentStore store : stores)
    {
        this.stores.add(store);
    }
    SimpleCache<Pair<String,String>, ContentStore> cache = new DefaultSimpleCache<Pair<String,String>, ContentStore>(11, getClass().getName());
    super.setStoresCache(cache);
}
 
Example 19
private Long getNodeIdNotNull(NodeRef nodeRef)
{
    Pair<Long, NodeRef> nodePair = nodeDAO.getNodePair(nodeRef);
    if (nodePair == null)
    {
        throw new InvalidNodeRefException(nodeRef);
    }
    return nodePair.getFirst();
}
 
Example 20
public CollectionWithPagingInfo<Preference> getPreferences(String personId, Paging paging)
{
	personId = people.validatePerson(personId);

	PagingResults<Pair<String, Serializable>> preferences = preferenceService.getPagedPreferences(personId, null, Util.getPagingRequest(paging));
	List<Preference> ret = new ArrayList<Preference>(preferences.getPage().size());
	for(Pair<String, Serializable> prefEntity : preferences.getPage())
	{
		Preference pref = new Preference(prefEntity.getFirst(), prefEntity.getSecond());
		ret.add(pref);
	}

       return CollectionWithPagingInfo.asPaged(paging, ret, preferences.hasMoreItems(), preferences.getTotalResultCount().getFirst());
}
 
Example 21
@Test
public void canUnlock()
{
    davLockService.unlock(nodeRef1);
    
    // NodeRef should have been unlocked.
    Mockito.verify(lockService).unlock(nodeRef1);
    // Node should have been removed from the list in the user's session.
    Mockito.verify(sessionList).remove(new Pair<String, NodeRef>("some_user_name", nodeRef1));
}
 
Example 22
/**
 * Returns the qualified name of the following format
 * <code>prefix:localName</code>, as a pair of (prefix, localName)
 * 
 * @param prefixedQName the prefixed name. E.g. <code>prefix:localName</code>
 * @return {@link Pair} of (prefix, localName)
 */
private Pair<String, String> splitPrefixedQName(String prefixedQName)
{
    // index 0 => prefix and index 1 => local name
    String[] prefixLocalName = QName.splitPrefixedQName(prefixedQName);

    if (NamespaceService.DEFAULT_PREFIX.equals(prefixLocalName[0]))
    {
        throw new InvalidArgumentException("cmm.rest_api.prefixed_qname_invalid_format", new Object[] { prefixedQName });
    }

    return new Pair<String, String>(prefixLocalName[0], prefixLocalName[1]);
}
 
Example 23
/**
 * Find or create the locale pair
 * 
 * @param locale                the locale to get or <tt>null</tt> to indicate the
 *                              {@link LocaleEntity#DEFAULT_LOCALE_SUBSTITUTE default locale}.
 * @return                      Returns the locale pair (ID, Locale), never <tt>null
 */
private Pair<Long, Locale> getOrCreateLocalePairImpl(Locale locale)
{
    // Null means look for the default
    final String localeStr;
    if (locale == null)
    {
        localeStr = LocaleEntity.DEFAULT_LOCALE_SUBSTITUTE;
        locale = I18NUtil.getLocale();
    }
    else
    {
        localeStr = DefaultTypeConverter.INSTANCE.convert(String.class, locale);
    }
    
    if (localeStr == null)
    {
        throw new IllegalArgumentException("Cannot look up entity by null locale.");
    }
    
    Pair<Long, String> entityPair = localeEntityCache.getOrCreateByValue(localeStr);
    if (entityPair == null)
    {
        throw new RuntimeException("Locale should have been created.");
    }
    return new Pair<Long, Locale>(entityPair.getFirst(), locale);
}
 
Example 24
@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(() ->
        {
            Parameters params = getParamsWithCreatedStatus();
            return renditions.getRendition(nodeRef, 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 25
private Pair<Long, Locale> getLocale(final Locale locale, boolean expectSuccess)
{
    RetryingTransactionCallback<Pair<Long, Locale>> callback = new RetryingTransactionCallback<Pair<Long, Locale>>()
    {
        public Pair<Long, Locale> execute() throws Throwable
        {
            Pair<Long, Locale> localePair = localeDAO.getOrCreateLocalePair(locale);
            return localePair;
        }
    };
    try
    {
        return txnHelper.doInTransaction(callback, false);
    }
    catch (Throwable e)
    {
        if (expectSuccess)
        {
            // oops
            throw new RuntimeException("Expected to get locale '" + locale + "'.", e);
        }
        else
        {
            return null;
        }
    }
}
 
Example 26
/**
 * 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 27
public void testCreateNamespaceEmpty() throws Exception
{
    // Create a namespace
    String uri = "";
    Pair<Long, String> namespacePair = getNamespace(uri, true, true);
    // Check that it can be retrieved
    Pair<Long, String> namespacePairCheck = getNamespace(namespacePair.getSecond(), false, true);
    assertEquals("Namespace ID changed", namespacePair.getFirst(), namespacePairCheck.getFirst());
}
 
Example 28
public void testUpdate() throws Exception
{
    ContentData contentData = getContentData();
    Pair<Long, ContentData> resultPair = create(contentData);
    Long id = resultPair.getFirst();
    // Update
    contentData = ContentData.setMimetype(contentData, "TEXT/HTML"); // Note the upper case mimetype
    contentData = ContentData.setEncoding(contentData, "UTF-16");
    // Don't update the content itself
    update(id, contentData);
    // Check
    Pair<Long, ContentData> result = getAndCheck(id, contentData);
    // Check the mimetype has been lowercased
    assertEquals("text/html", result.getSecond().getMimetype());
}
 
Example 29
@Override
public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException
{
    if (method instanceof PostMethod)
    {
        // encrypt body
        Pair<byte[], AlgorithmParameters> encrypted = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, message);
        setRequestAlgorithmParameters(method, encrypted.getSecond());

        ((PostMethod) method).setRequestEntity(new ByteArrayRequestEntity(encrypted.getFirst(), "application/octet-stream"));
    }

    long requestTimestamp = System.currentTimeMillis();

    // add MAC header
    byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress()));

    if (logger.isDebugEnabled())
    {
        logger.debug("Setting MAC " + mac + " on HTTP request " + method.getPath());
        logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath());
    }

    if (overrideMAC)
    {
        mac[0] += (byte) 1;
    }
    setRequestMac(method, mac);

    if (overrideTimestamp)
    {
        requestTimestamp += 60000;
    }
    // prevent replays
    setRequestTimestamp(method, requestTimestamp);
}
 
Example 30
public void testContentUrl_FetchingOrphansWithLimit() throws Exception
{
    // Orphan some content
    for (int i = 0; i < 5; i++)
    {
        ContentData contentData = getContentData();
        Pair<Long, ContentData> resultPair = create(contentData);
        getAndCheck(resultPair.getFirst(), contentData);
        delete(resultPair.getFirst());
    }
    final int[] count = new int[] {0}; 
    
    // Iterate over all orphaned content URLs and ensure that we hit the one we just orphaned
    ContentUrlHandler handler = new ContentUrlHandler()
    {
        public void handle(Long id, String contentUrl, Long orphanTime)
        {
            // Check
            if (id == null || contentUrl == null || orphanTime == null)
            {
                fail("Invalid orphan data returned to handler: " + id + "-" + contentUrl + "-" + orphanTime);
            }
            count[0]++;
        }
    };
    contentDataDAO.getContentUrlsOrphaned(handler, Long.MAX_VALUE, 5);
    assertEquals("Expected exactly 5 results callbacks", 5, count[0]);
}
 
Example 31
public Pair<Long, String> getNamespace(String namespaceUri)
{
    if (namespaceUri == null)
    {
        throw new IllegalArgumentException("Namespace URI cannot be null");
    }
    Pair<Long, String> entityPair = namespaceCache.getByValue(namespaceUri);
    return entityPair;
}
 
Example 32
/**
 * @param nodeId            the key node ID
 */
public Pair<Long, Node> findByKey(Long nodeId)
{
    NodeEntity node = selectNodeById(nodeId);
    if (node != null)
    {
        // Lock it to prevent 'accidental' modification
        node.lock();
        return new Pair<Long, Node>(nodeId, node);
    }
    else
    {
        return null;
    }
}
 
Example 33
private void assertPropDeleted(Pair<Long, ?> value)
{
    if (value != null)
    {
        String msg = String.format("Property value [%s=%s] should have been deleted by cleanup script.",
                    value.getSecond().getClass().getSimpleName(), value.getSecond());
        fail(msg);
    }
}
 
Example 34
public void testGetNodeIdsIntervalForType() throws Exception
{
    // Different calls with equivalent parameters should return the same values
    Pair<Long, Long> interval1 = getNodeIdsInterval(0L, System.currentTimeMillis());
    Pair<Long, Long> interval2 = getNodeIdsInterval(null, System.currentTimeMillis());
    Pair<Long, Long> interval3 = getNodeIdsInterval(null, null);
    
    assertEquals(interval1.getFirst(), interval2.getFirst());
    assertEquals(interval2.getFirst(), interval3.getFirst());
    
    assertEquals(interval1.getSecond(), interval2.getSecond());
    assertEquals(interval2.getSecond(), interval3.getSecond());
}
 
Example 35
public void testCreateQName() throws Exception
{
    // Create a qname
    QName qname = QName.createQName(getName(), GUID.generate());
    Pair<Long, QName> qnamePair = getQName(qname, true, true);
    // Check that it can be retrieved
    Pair<Long, QName> qnamePairCheck = getQName(qnamePair.getSecond(), false, true);
    assertEquals("QName ID changed", qnamePair.getFirst(), qnamePairCheck.getFirst());
    // Check the duplicate checking
    getQName(qname, true, false);
}
 
Example 36
public void testDeleteByKey() throws Exception
{
    TestValue valueOne = new TestValue(getName() + "-ONE");
    Pair<Long, Object> entityPairOne = entityLookupCacheA.getOrCreateByValue(valueOne);
    assertNotNull(entityPairOne);
    Long id = entityPairOne.getFirst();
    assertEquals(valueOne.val, database.get(id));
    assertEquals(2, cache.getKeys().size());
    
    // Delete
    int deleteCount = entityLookupCacheA.deleteByKey(id);
    assertEquals("Delete count was incorrect.", 1, deleteCount);
    assertNull(database.get(id));
    assertEquals(0, cache.getKeys().size());
}
 
Example 37
/**
 * Get a report from a txId with detailed information related with the Transaction
 *
 * Synchronous execution
 *
 * @param params Query Request with following parameters:
 * - txId, mandatory, the number of the Transaction to build the report
 * - core, The name of the SOLR Core or "null" to get the report for every core
 * @return Response including the action result:
 * - report: an Object with the details of the report
 * - error: When mandatory parameters are not set, an error node is returned
 *
 * @throws JSONException
 */
private NamedList<Object> actionTXREPORT(SolrParams params) throws JSONException
{
    NamedList<Object> report = new SimpleOrderedMap<>();

    if (params.get(ARG_TXID) == null)
    {
        report.add(ACTION_STATUS_ERROR, "No " + ARG_TXID + " parameter set.");
        return report;
    }

    Long txid = Long.valueOf(params.get(ARG_TXID));
    String requestedCoreName = coreName(params);

    coreNames().stream()
            .filter(coreName -> requestedCoreName == null || coreName.equals(requestedCoreName))
            .map(coreName -> new Pair<>(coreName, trackerRegistry.getTrackerForCore(coreName, MetadataTracker.class)))
            .filter(coreNameAndMetadataTracker -> coreNameAndMetadataTracker.getSecond() != null)
            .forEach(coreNameAndMetadataTracker ->
                    report.add(
                            coreNameAndMetadataTracker.getFirst(),
                            buildTxReport(
                                    trackerRegistry,
                                    informationServers.get(coreNameAndMetadataTracker.getFirst()),
                                    coreNameAndMetadataTracker.getFirst(),
                                    coreNameAndMetadataTracker.getSecond(),
                                    txid)));

    if (report.size() == 0)
    {
        addAlertMessage(report);
    }
    return report;

}
 
Example 38
/**
 * Helper method that returns the same result type as {@link #check(Log)} given a local checkCommand.
 */
public static Pair<Boolean,String> check(RuntimeExec checkCommand)
{
    ExecutionResult result = checkCommand.execute();
    Boolean success = result.getSuccess();
    String output = success ? result.getStdOut().trim() : result.toString();
    return new Pair<>(success, output);
}
 
Example 39
private Long getQNameId(QName sortPropQName)
{
    if (sortPropQName.equals(SORT_QNAME_CONTENT_SIZE) || sortPropQName.equals(SORT_QNAME_CONTENT_MIMETYPE))
    {
        sortPropQName = ContentModel.PROP_CONTENT;
    }
    
    Pair<Long, QName> qnamePair = qnameDAO.getQName(sortPropQName);
    return (qnamePair == null ? null : qnamePair.getFirst());
}
 
Example 40
@Override
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public NodeRef getNodeRef(Long nodeId)
{
    Pair<Long, NodeRef> nodePair = nodeDAO.getNodePair(nodeId);
    return nodePair == null ? null : nodePair.getSecond();
}