Java Code Examples for org.alfresco.util.ParameterCheck

The following examples show how to use org.alfresco.util.ParameterCheck. 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 check out the related API usage on the sidebar.
Example 1
@Override
public void execute(final JobExecutionContext jobExecutionContext) throws JobExecutionException
{
    final JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
    final HBBaseDataCollector collector = (HBBaseDataCollector) dataMap.get(COLLECTOR_KEY);
    final HBDataSenderService hbDataSenderService = (HBDataSenderService) dataMap.get(DATA_SENDER_SERVICE_KEY);

    ParameterCheck.mandatory( COLLECTOR_KEY, collector);
    ParameterCheck.mandatory( DATA_SENDER_SERVICE_KEY, hbDataSenderService);

    try
    {
        List<HBData> data = collector.collectData();
        hbDataSenderService.sendData(data);

        if (logger.isDebugEnabled())
        {
            logger.debug("Finished collector job. ID:" + collector.getCollectorId());
        }
    }
    catch (final Exception e)
    {
        // Log the error but don't rethrow, collector errors are non fatal
        logger.error("Heartbeat failed to collect data for collector ID: " + collector.getCollectorId(), e);
    }
}
 
Example 2
@Override
public NodeRef getModelNodeRef(String modelName)
{
    ParameterCheck.mandatoryString("modelName", modelName);

    StringBuilder builder = new StringBuilder(120);
    builder.append(repoModelsLocation.getPath()).append("//.[@cm:name='").append(modelName).append("' and ")
                .append(RepoAdminServiceImpl.defaultSubtypeOfDictionaryModel).append(']');

    List<NodeRef> nodeRefs = searchService.selectNodes(getRootNode(), builder.toString(), null, namespaceDAO, false);

    if (nodeRefs.size() == 0)
    {
        return null;
    }
    else if (nodeRefs.size() > 1)
    {
        // unexpected: should not find multiple nodes with same name
        throw new CustomModelException(MSG_MULTIPLE_MODELS, new Object[] { modelName });
    }

    return nodeRefs.get(0);
}
 
Example 3
/**
 * Constructor with all available arguments.
 * 
 * @param dbPrefixes String[]
 * @param directory File
 * @param fileNameTemplate String
 * @param dbToXMLFactory DbToXMLFactory
 * @param defaultSchemaName String
 */
public MultiFileDumper(String[] dbPrefixes, File directory, String fileNameTemplate, DbToXMLFactory dbToXMLFactory, String defaultSchemaName)
{
    ParameterCheck.mandatory("dbPrefixes", dbPrefixes);
    ParameterCheck.mandatory("directory", directory);
    ParameterCheck.mandatory("fileNameTemplate", fileNameTemplate);
    ParameterCheck.mandatory("dbToXMLFactory", dbToXMLFactory);
    if (dbPrefixes.length == 0)
    {
        throw new IllegalArgumentException("At least one database object prefix is required.");
    }
    
    this.dbPrefixes = dbPrefixes;
    this.directory = directory;
    this.fileNameTemplate = fileNameTemplate;
    this.dbToXMLFactory = dbToXMLFactory;
    this.defaultSchemaName = defaultSchemaName;
}
 
Example 4
protected CompressingContentWriter(final String contentUrl, final ContentContext context, final ContentStore temporaryContentStore,
        final ContentWriter backingWriter, final String compressionType, final Collection<String> mimetypesToCompress)
{
    super(backingWriter.getContentUrl() != null ? backingWriter.getContentUrl() : context.getContentUrl(),
            context.getExistingContentReader());

    ParameterCheck.mandatory("context", context);
    ParameterCheck.mandatory("temporaryContentStore", temporaryContentStore);
    ParameterCheck.mandatory("backingWriter", backingWriter);

    this.context = context;
    this.temporaryContentStore = temporaryContentStore;
    this.backingWriter = backingWriter;

    this.compressionType = compressionType;
    this.mimetypesToCompress = mimetypesToCompress;

    // we are the first real listener (DoGuessingOnCloseListener always is first)
    super.addListener(this);

    final ContentContext temporaryContext = new ContentContext(context.getExistingContentReader(), null);
    this.temporaryWriter = this.temporaryContentStore.getWriter(temporaryContext);
}
 
Example 5
@Override
public boolean isNamespaceUriExists(String modelNamespaceUri)
{
    ParameterCheck.mandatoryString("modelNamespaceUri", modelNamespaceUri);

    Collection<String> uris = namespaceDAO.getURIs();
    if (uris.contains(modelNamespaceUri))
    {
        return true;
    }

    for (CompiledModel model : getAllCustomM2Models(false))
    {
        if (modelNamespaceUri.equals(getModelNamespaceUriPrefix(model.getM2Model()).getFirst()))
        {
            return true;
        }
    }
    return false;
}
 
Example 6
/**
 * Construct
 * 
 * @param authorization String
 */
public Authorization(String authorization)
{
    ParameterCheck.mandatoryString("authorization", authorization);
    if (authorization.length() == 0)
    {
        throw new IllegalArgumentException("authorization does not consist of username and password");
    }

    int idx = authorization.indexOf(':');

    if (idx == -1)
    {
        setUser(null, authorization);
    }
    else
    {
        setUser(authorization.substring(0, idx), authorization.substring(idx + 1));
    }
}
 
Example 7
/**
 * Does the password match?
 * @param rawPassword  mandatory password
 * @param encodedPassword mandatory hashed version
 * @param salt optional salt
 * @param encodingChain mandatory encoding chain
 * @return true if they match
 */
public boolean matchesPassword(String rawPassword, String encodedPassword, Object salt, List<String> encodingChain)
{
    ParameterCheck.mandatoryString("rawPassword", rawPassword);
    ParameterCheck.mandatoryString("encodedPassword", encodedPassword);
    ParameterCheck.mandatoryCollection("encodingChain", encodingChain);
    if (encodingChain.size() > 1)
    {
        String lastEncoder = encodingChain.get(encodingChain.size() - 1);
        String encoded = encodePassword(rawPassword,salt, encodingChain.subList(0,encodingChain.size()-1));
        return matches(lastEncoder,encoded,encodedPassword,salt);
    }

    if (encodingChain.size() == 1)
    {
        return matches(encodingChain.get(0), rawPassword, encodedPassword, salt);
    }
    return false;
}
 
Example 8
@Override
public void afterPropertiesSet() throws Exception {
    ParameterCheck.mandatory("authenticationContextManager", authenticationContextManager);

    //Attempt to get RepositoryAuthenticationDao from the subsystem
    for(String contextName : authenticationContextManager.getInstanceIds())
    {
        ApplicationContext ctx = authenticationContextManager.getApplicationContext(contextName);
        try
        {
            authenticationDao = (RepositoryAuthenticationDao)
                    ctx.getBean(RepositoryAuthenticationDao.class);
        } catch(NoSuchBeanDefinitionException e) {}
    }

}
 
Example 9
protected void notifyUser(NodeRef personNodeRef, String subjectText,  Object[] subjectParams, Map<String, Object> model, String templateNodeRef)
  {
      ParameterCheck.mandatory("personNodeRef", personNodeRef);

Map<QName, Serializable> personProps = nodeService.getProperties(personNodeRef);
String emailAddress = (String)personProps.get(ContentModel.PROP_EMAIL);
String userName = (String)personProps.get(ContentModel.PROP_USERNAME);
      Locale locale = emailHelper.getUserLocaleOrDefault(userName);

      Action mail = actionService.createAction(MailActionExecuter.NAME);
      
      mail.setParameterValue(MailActionExecuter.PARAM_TO, emailAddress);
      mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subjectText);
      mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT_PARAMS, subjectParams);
      mail.setParameterValue(MailActionExecuter.PARAM_LOCALE, locale);

      //mail.setParameterValue(MailActionExecuter.PARAM_TEXT, buildMailText(emailTemplateRef, model));
      mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, templateNodeRef);
      mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable)model);
      
      actionService.executeAction(mail, null);
  }
 
Example 10
public String getDomainUser(String baseUsername, String tenantDomain)
{
    ParameterCheck.mandatory("baseUsername", baseUsername);

    if ((tenantDomain == null) || (tenantDomain.equals(DEFAULT_DOMAIN)))
    {
        return baseUsername;
    }
    else
    {
        if (baseUsername.contains(SEPARATOR))
        {
            throw new AlfrescoRuntimeException("Invalid base username: " + baseUsername);
        }

        if (tenantDomain.contains(SEPARATOR))
        {
            throw new AlfrescoRuntimeException("Invalid tenant domain: " + tenantDomain);
        }

        tenantDomain = getTenantDomain(tenantDomain);
        return baseUsername + SEPARATOR + tenantDomain;
    }
}
 
Example 11
@Auditable(parameters = {"contextNodeRef", "files", "folders", "ignoreQNames", "sortProps", "pagingRequest"})
@Override
@Extend(traitAPI = FileFolderServiceTrait.class, extensionAPI = FileFolderServiceExtension.class)
public PagingResults<FileInfo> list(NodeRef contextNodeRef,
                                  boolean files,
                                  boolean folders,
                                  Set<QName> ignoreQNames,
                                  List<Pair<QName, Boolean>> sortProps,
                                  PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("contextNodeRef", contextNodeRef);
    ParameterCheck.mandatory("pagingRequest", pagingRequest);
    
    Pair<Set<QName>,Set<QName>> pair = buildSearchTypesAndIgnoreAspects(files, folders, ignoreQNames);
    Set<QName> searchTypeQNames = pair.getFirst();
    Set<QName> ignoreAspectQNames = pair.getSecond();
    
    // execute query
    final CannedQueryResults<NodeRef> results = listImpl(contextNodeRef, null, searchTypeQNames, ignoreAspectQNames, sortProps, pagingRequest);
    return getPagingResults(pagingRequest, results);
}
 
Example 12
@Override
public void getContentUrlsOrphaned(
        final ContentUrlHandler contentUrlHandler,
        final Long maxOrphanTimeExclusive,
        final int maxResults)
{
    ParameterCheck.mandatory("maxOrphanTimeExclusive", maxOrphanTimeExclusive);
    
    ContentUrlOrphanQuery query = new ContentUrlOrphanQuery();
    query.setMaxOrphanTimeExclusive(maxOrphanTimeExclusive);
    List<ContentUrlEntity> results = template.selectList(SELECT_CONTENT_URLS_ORPHANED, 
                                                                                  query, 
                                                                                  new RowBounds(0, maxResults));
    // Pass the result to the callback
    for (ContentUrlEntity result : results)
    {
        contentUrlHandler.handle(
                result.getId(),
                result.getContentUrl(),
                result.getOrphanTime());
    }
}
 
Example 13
@Override
public NodeRef searchSimple(NodeRef contextNodeRef, String name)
{
    ParameterCheck.mandatory("name", name);
    ParameterCheck.mandatory("contextNodeRef", contextNodeRef);
    
    NodeRef childNodeRef = nodeService.getChildByName(contextNodeRef, ContentModel.ASSOC_CONTAINS, name);
    if (logger.isTraceEnabled())
    {
        logger.trace(
                "Simple name search results: \n" +
                "   parent: " + contextNodeRef + "\n" +
                "   name: " + name + "\n" +
                "   result: " + childNodeRef);
    }
    return childNodeRef;
}
 
Example 14
private void afterPropertiesSet_setupRouteContentProperties()
{
    if (this.routeContentPropertyNames != null && !this.routeContentPropertyNames.isEmpty())
    {
        this.routeContentPropertyQNames = new HashSet<>();
        for (final String routePropertyName : this.routeContentPropertyNames)
        {
            final QName routePropertyQName = QName.resolveToQName(this.namespaceService, routePropertyName);
            ParameterCheck.mandatory("routePropertyQName", routePropertyQName);

            final PropertyDefinition contentPropertyDefinition = this.dictionaryService.getProperty(routePropertyQName);
            if (contentPropertyDefinition == null
                    || !DataTypeDefinition.CONTENT.equals(contentPropertyDefinition.getDataType().getName()))
            {
                throw new IllegalStateException(routePropertyName + " is not a valid content model property of type d:content");
            }
            this.routeContentPropertyQNames.add(routePropertyQName);
        }
    }
}
 
Example 15
/**
 * Sets the Range Parameters object on search parameters
 * @param sp SearchParameters
 * @param rangeParams RangeParameters
 */
public void fromRange(SearchParameters sp, List<RangeParameters> ranges)
{
    if(ranges != null && !ranges.isEmpty())
    {
        for(RangeParameters rangeParams : ranges)
        {
            ParameterCheck.mandatory("ranges", rangeParams);
            ParameterCheck.mandatory("field", rangeParams.getField());
            ParameterCheck.mandatory("start", rangeParams.getStart());
            ParameterCheck.mandatory("end", rangeParams.getEnd());
            ParameterCheck.mandatory("gap", rangeParams.getGap());
        }
        sp.setRanges(ranges);
    }
    
}
 
Example 16
/**
 * @return String
 */
public static String getMultiTenantDomainName(String name)
{
    // Check that all the passed values are not null
    ParameterCheck.mandatory("name", name);

    int idx1 = name.indexOf(SEPARATOR);
    if (idx1 == 0)
    {
        int idx2 = name.indexOf(SEPARATOR, 1);
        if (idx2 != -1)
        {
            return name.substring(1, idx2);
        }
    }
    return DEFAULT_DOMAIN;
}
 
Example 17
protected EncryptingContentWriterFacade(final ContentWriter delegate, final ContentContext context, final Key key,
        final ContentReader existingContentReader)
{
    super(delegate, existingContentReader);

    ParameterCheck.mandatory("context", context);
    ParameterCheck.mandatory("key", key);

    this.addListener(() -> {
        EncryptingContentWriterFacade.this.completedWrite = true;

        if (EncryptingContentWriterFacade.this.guessMimetype)
        {
            EncryptingContentWriterFacade.this.guessMimetype(EncryptingContentWriterFacade.this.guessFileName);
        }

        if (EncryptingContentWriterFacade.this.guessEncoding)
        {
            EncryptingContentWriterFacade.this.guessEncoding();
        }
    });

    this.context = context;
    this.key = key;
}
 
Example 18
@Override
public boolean isTenantName(String name)
{
    ParameterCheck.mandatory("name", name);

    int idx1 = name.indexOf(SEPARATOR);
    if (idx1 == 0)
    {
        int idx2 = name.indexOf(SEPARATOR, 1);
        if (idx2 != -1)
        {
            return true;
        }
    }

    return false;
}
 
Example 19
@Override
public ModelDefinition getCustomModelByUri(String namespaceUri)
{
    ParameterCheck.mandatoryString("namespaceUri", namespaceUri);
    CompiledModel compiledModel = getModelByUri(namespaceUri);

    if (compiledModel != null)
    {
        return compiledModel.getModelDefinition();
    }
    return null;
}
 
Example 20
/**
 * Returns compiled custom model and whether the model is active or not as a {@code Pair} object
 *
 * @param modelName the name of the custom model to retrieve
 * @return the {@code Pair<CompiledModel, Boolean>} (or null, if it doesn't exist)
 */
protected Pair<CompiledModel, Boolean> getCustomCompiledModel(String modelName)
{
    ParameterCheck.mandatoryString("modelName", modelName);

    final NodeRef modelNodeRef = getModelNodeRef(modelName);

    if (modelNodeRef == null || !nodeService.exists(modelNodeRef))
    {
        return null;
    }

    M2Model model = null;
    final boolean isActive = Boolean.TRUE.equals(nodeService.getProperty(modelNodeRef, ContentModel.PROP_MODEL_ACTIVE));
    if (isActive)
    {
        QName modelQName = (QName) nodeService.getProperty(modelNodeRef, ContentModel.PROP_MODEL_NAME);
        if (modelQName == null)
        {
            return null;
        }
        try
        {
            CompiledModel compiledModel = dictionaryDAO.getCompiledModel(modelQName);
            model = compiledModel.getM2Model();
        }
        catch (Exception e)
        {
            throw new CustomModelException(MSG_RETRIEVE_MODEL, new Object[] { modelName }, e);
        }
    }
    else
    {
        model = getM2Model(modelNodeRef);
    }

    Pair<CompiledModel, Boolean> result = (model == null) ? null : new Pair<>(compileModel(model), isActive);

    return result;
}
 
Example 21
@Override
public AspectDefinition getCustomAspect(QName name)
{
    ParameterCheck.mandatory("name", name);

    CompiledModel compiledModel = getModelByUri(name.getNamespaceURI());
    if (compiledModel != null)
    {
        return compiledModel.getAspect(name);
    }

    return null;
}
 
Example 22
@Override
public PagingResults<AspectDefinition> getAllCustomAspects(PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("pagingRequest", pagingRequest);

    List<AspectDefinition> result = new ArrayList<>();
    List<CompiledModel> list = getAllCustomM2Models(false);
    for (CompiledModel model : list)
    {
        result.addAll(model.getAspects());
    }
    return wrapResult(pagingRequest, result);
}
 
Example 23
@Override
public TypeDefinition getCustomType(QName name)
{
    ParameterCheck.mandatory("name", name);

    CompiledModel compiledModel = getModelByUri(name.getNamespaceURI());
    if (compiledModel != null)
    {
        return compiledModel.getType(name);
    }

    return null;
}
 
Example 24
/**
 * Extracts informational path elements ("prefixes") contained in a content URL.
 *
 * @param contentUrl
 *            the content URL from which to extract prefixes
 * @return the list of extracted prefixes
 */
public static List<String> extractPrefixes(final String contentUrl)
{
    ParameterCheck.mandatoryString("contentUrl", contentUrl);

    final StringBuilder builder = new StringBuilder(contentUrl);
    final int separatorIdx = builder.indexOf(ContentStore.PROTOCOL_DELIMITER);
    final int endOfFirstPathFragment = builder.indexOf("/", separatorIdx + ContentStore.PROTOCOL_DELIMITER.length());

    final List<String> prefixes = new ArrayList<>();
    if (endOfFirstPathFragment != -1)
    {
        final String firstPathFragment = builder.substring(separatorIdx + ContentStore.PROTOCOL_DELIMITER.length(),
                endOfFirstPathFragment);
        final Matcher matcher = PREFIX_DESCRIPTOR_PATTERN.matcher(firstPathFragment);

        if (matcher.matches())
        {
            final int prefixCount = Integer.parseInt(matcher.group(1));

            // find end of last prefix fragment
            int endOfPreviousPathFragment = endOfFirstPathFragment;
            for (int i = 0; i < prefixCount; i++)
            {
                final int nextSlash = builder.indexOf("/", endOfPreviousPathFragment + 1);
                final String prefix = builder.substring(endOfPreviousPathFragment + 1, nextSlash);
                endOfPreviousPathFragment = nextSlash;

                if (endOfPreviousPathFragment == -1)
                {
                    throw new IllegalArgumentException("contentUrl prefix descriptor contains incorrect count of prefix fragments");
                }
                prefixes.add(prefix);
            }
        }
    }

    return prefixes;
}
 
Example 25
public static String getTenantDomain(String name)
{
    ParameterCheck.mandatory("name", name);
    
    int idx1 = name.indexOf(TenantService.SEPARATOR);
    if (idx1 == 0)
    {
        int idx2 = name.indexOf(TenantService.SEPARATOR, 1);
        if (idx2 != -1)
        {
            return name.substring(1, idx2);
        }
    }
    return TenantService.DEFAULT_DOMAIN;
}
 
Example 26
@Override
public void afterPropertiesSet() throws Exception
{
    ParameterCheck.mandatory("jobLockService", jobLockService);
    ParameterCheck.mandatory("transactionService", transactionService);
    ParameterCheck.mandatory("authenticationDao", authenticationDao);
    ParameterCheck.mandatory("compositePasswordEncoder", passwordEncoder);
    ParameterCheck.mandatory("nodeDAO", nodeDAO);
    ParameterCheck.mandatory("patchDAO", patchDAO);
    ParameterCheck.mandatory("qnameDAO", qnameDAO);
    ParameterCheck.mandatory("behaviourFilter", behaviourFilter);
}
 
Example 27
@Override
public void requestReset(String userId, String clientName)
{
    ParameterCheck.mandatoryString("userId", userId);
    ParameterCheck.mandatoryString("clientName", clientName);

    String userEmail = validateUserAndGetEmail(userId);

    // Get the (latest) workflow definition for reset-password.
    WorkflowDefinition wfDefinition = workflowService.getDefinitionByName(WorkflowModelResetPassword.WORKFLOW_DEFINITION_NAME);

    // create workflow properties
    Map<QName, Serializable> props = new HashMap<>(7);
    props.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, I18NUtil.getMessage(WORKFLOW_DESCRIPTION_KEY));
    props.put(WorkflowModelResetPassword.WF_PROP_USERNAME, userId);
    props.put(WorkflowModelResetPassword.WF_PROP_USER_EMAIL, userEmail);
    props.put(WorkflowModelResetPassword.WF_PROP_CLIENT_NAME, clientName);
    props.put(WorkflowModel.ASSOC_PACKAGE, workflowService.createPackage(null));

    String guid = GUID.generate();
    props.put(WorkflowModelResetPassword.WF_PROP_KEY, guid);
    props.put(WorkflowModelResetPassword.WF_PROP_TIMER_END, timerEnd);

    // start the workflow
    WorkflowPath path = workflowService.startWorkflow(wfDefinition.getId(), props);
    if (path.isActive())
    {
        WorkflowTask startTask = workflowService.getStartTask(path.getInstance().getId());
        workflowService.endTask(startTask.getId(), null);
    }
}
 
Example 28
@Override
public ClientApp getClientAppConfig(String clientName)
{
    ParameterCheck.mandatoryString("clientName", clientName);

    ClientApp clientApp = clientAppConfig.getClient(clientName);
    if (clientApp == null)
    {
        throw new ClientAppNotFoundException("Client was not found [" + clientName + "]");
    }
    return clientApp;
}
 
Example 29
@Override
public void performResetPassword(DelegateExecution execution)
{
    // This method chooses to take a rather indirect route to access the password value.
    // This is for security reasons. We do not want to store the password in the Activiti DB.

    // We can get the username from the execution (process scope).
    final String userName = (String) execution.getVariable(WorkflowModelResetPassword.WF_PROP_USERNAME_ACTIVITI);

    // But we cannot get the password from the execution as we have intentionally not stored the password there.
    // Instead we recover the password from the specific task in which it was set.
    List<Task> activitiTasks = activitiTaskService.createTaskQuery().taskDefinitionKey(WorkflowModelResetPassword.TASK_RESET_PASSWORD)
                .processInstanceId(execution.getProcessInstanceId()).list();
    if (activitiTasks.size() != 1)
    {
        throw new ResetPasswordWorkflowException("Unexpected count of task instances: " + activitiTasks.size());
    }
    Task activitiTask = activitiTasks.get(0);
    String activitiTaskId = activitiTask.getId();
    final String password = (String) activitiTaskService.getVariable(activitiTaskId, WorkflowModelResetPassword.WF_PROP_PASSWORD_ACTIVITI);

    if (LOGGER.isDebugEnabled())
    {
        LOGGER.debug("Retrieved new password from task " + activitiTaskId);
    }

    ParameterCheck.mandatoryString(WorkflowModelResetPassword.WF_PROP_USERNAME_ACTIVITI, userName);
    ParameterCheck.mandatoryString(WorkflowModelResetPassword.WF_PROP_PASSWORD_ACTIVITI, password);

    if (LOGGER.isDebugEnabled())
    {
        LOGGER.debug("Changing password for " + userName);
        // Don't LOG the password. :)
    }

    this.authenticationService.setAuthentication(userName, password.toCharArray());
}
 
Example 30
/**
 * {@inheritDoc}
 */
@Override
public ContentReader getReader(final String contentUrl)
{
    ParameterCheck.mandatoryString("contentUrl", contentUrl);

    final Pair<String, String> urlParts = this.getContentUrlParts(contentUrl);
    final String protocol = urlParts.getFirst();
    final String effectiveContentUrl = this.checkAndAdjustInboundContentUrl(contentUrl,
            EqualsHelper.nullSafeEquals(StoreConstants.WILDCARD_PROTOCOL, protocol));

    final ContentReader reader = super.getReader(effectiveContentUrl);
    return reader;
}