Java Code Examples for org.alfresco.error.AlfrescoRuntimeException

The following examples show how to use org.alfresco.error.AlfrescoRuntimeException. 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
@Override
public void checkDomain(String name)
{
    if (name == null)
    {
        return;
    }

    String nameDomain = null;

    int idx1 = name.indexOf(SEPARATOR);
    if (idx1 == 0)
    {
        int idx2 = name.indexOf(SEPARATOR, 1);
        nameDomain = name.substring(1, idx2);
    }

    String tenantDomain = getCurrentUserDomain();

    if (((nameDomain == null) && (!tenantDomain.equals(DEFAULT_DOMAIN))) || ((nameDomain != null) && (!nameDomain.equals(tenantDomain))))
    {
        throw new AlfrescoRuntimeException("domain mismatch: expected = " + tenantDomain + ", actual = " + nameDomain);
    }
}
 
Example 2
@Test
public void testConfiguration() throws Exception
{
    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    // try to use the factory without initialization
    try
    {
        AlfrescoSSLSocketFactory.getDefault();
        fail("An AlfrescoRuntimeException should be thrown as the factory is not initialized.");
    }
    catch (AlfrescoRuntimeException are)
    {
        // Expected
    }

    // initialize and get an instance of AlfrescoSSLSocketFactory
    AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(ks);
    AlfrescoSSLSocketFactory.getDefault();
}
 
Example 3
/**
 * Updates the thumbnails content
 */
public void update()
{
    List<ChildAssociationRef> parentRefs = services.getNodeService().getParentAssocs(nodeRef, RenditionModel.ASSOC_RENDITION, RegexQNamePattern.MATCH_ALL);
    // There should in fact only ever be one parent association of type rendition on any rendition node.
    if (parentRefs.size() != 1)
    {
        StringBuilder msg = new StringBuilder();
        msg.append("Node ")
            .append(nodeRef)
            .append(" has ")
            .append(parentRefs.size())
            .append(" rendition parents. Unable to update.");
        if (logger.isWarnEnabled())
        {
            logger.warn(msg.toString());
        }
        throw new AlfrescoRuntimeException(msg.toString());
    }
    
    String name = parentRefs.get(0).getQName().getLocalName();
    
    ThumbnailDefinition def = services.getThumbnailService().getThumbnailRegistry().getThumbnailDefinition(name);
    services.getThumbnailService().updateThumbnail(this.nodeRef, def.getTransformationOptions());
}
 
Example 4
public ScriptInvitation<?> toScriptInvitation(Invitation invitation)
{
    if(invitation instanceof NominatedInvitation)
    {
        return new ScriptNominatedInvitation((NominatedInvitation) invitation, invitationService);
    }

    if(invitation instanceof ModeratedInvitation)
    {
        String userName = invitation.getInviteeUserName();
        NodeRef person = personService.getPerson(userName);
        Map<QName, Serializable> properties = nodeService.getProperties(person);
        String firstName = (String) properties.get(ContentModel.PROP_FIRSTNAME);
        String lastName = (String) properties.get(ContentModel.PROP_LASTNAME);
        String email = (String) properties.get(ContentModel.PROP_EMAIL);
        return new ScriptModeratedInvitation(
                    (ModeratedInvitation) invitation,
                    invitationService,
                    email,
                    firstName,
                    lastName);
    }
    throw new AlfrescoRuntimeException("Unknown invitation type.");
}
 
Example 5
/**
 * Get the certificate chain for the CA certificate
 * 
 * @param trustedKs
 * @return
 */
private Certificate[] getCaCertChain(KeyStore trustedKs) 
{
	Certificate[] caCertChain = null;
	String certAlias = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_CERT_ALIAS);
	
	try
	{
		caCertChain = trustedKs.getCertificateChain(certAlias);
	}
	catch(KeyStoreException kse)
	{
		throw new AlfrescoRuntimeException(kse.getMessage());
	}
	
	return caCertChain;
}
 
Example 6
/**
   * Method that does the work of importing a filesystem using the BatchProcessor.
   * 
   * @param bulkImportParameters  The bulk import parameters to apply to this bulk import.
   * @param nodeImporter          The node importer implementation that will import each node.
   * @param lockToken             The lock token to use during the bulk import.
   */
  @Override
  protected void bulkImportImpl(final BulkImportParameters bulkImportParameters, final NodeImporter nodeImporter, final String lockToken)
  {
      super.bulkImportImpl(bulkImportParameters, nodeImporter, lockToken);

  	final File sourceFolder = nodeImporter.getSourceFolder();
      final int batchSize = getBatchSize(bulkImportParameters);
      final int loggingInterval = getLoggingInterval(bulkImportParameters);
  	final StripingFilesystemTracker tracker = new StripingFilesystemTracker(directoryAnalyser, bulkImportParameters.getTarget(), sourceFolder, batchSize);
      final BatchProcessor<ImportableItem> batchProcessor = getBatchProcessor(bulkImportParameters, tracker.getWorkProvider(), loggingInterval);
      final BatchProcessor.BatchProcessWorker<ImportableItem> worker = getWorker(bulkImportParameters, lockToken, nodeImporter, tracker);

do
{
	batchProcessor.process(worker, true);
	if(batchProcessor.getLastError() != null)
	{
		throw new AlfrescoRuntimeException(batchProcessor.getLastError());
	}
}
while(tracker.moreLevels());
  }
 
Example 7
public void testAliasWithIncorrectPassword_One() throws Exception
    {
        try
        {
        	getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "password_fail"));	
        	
//            new KeystoreKeyProvider(
//                    FILE_ONE,
//                    getKeyStoreLoader(),
//                    "SunJCE",
//                    "JCEKS",
//                    Collections.singletonMap(ALIAS_ONE, "password_fail"));
            fail("Expect to fail because password is incorrect");
        }
        catch (AlfrescoRuntimeException e)
        {
            // Expected
            assertTrue(e.getCause() instanceof UnrecoverableKeyException);
        }
    }
 
Example 8
public void setTemplateProfileDir(String templateProfileDir)
{
    if (templateProfileDir == null || templateProfileDir.trim().length() == 0)
    {
        this.templateProfileDir = null;
    }
    else
    {
        File tmp = new File(templateProfileDir);
        if (!tmp.isDirectory())
        {
            throw new AlfrescoRuntimeException("OpenOffice template profile directory "+templateProfileDir+" does not exist.");
        }
        this.templateProfileDir = tmp;
    }
}
 
Example 9
/**
 * Loads filename constraint from dictionary
 */
@Override
public void afterPropertiesSet() throws Exception
{
    PropertyCheck.mandatory(this, "dictionaryService", dictionaryService);

    QName qNameConstraint = QName.createQName(namespaceURI, constraintLocalName);
    ConstraintDefinition constraintDef = dictionaryService.getConstraint(qNameConstraint);
    if (constraintDef == null)
    {
        throw new AlfrescoRuntimeException("Constraint definition does not exist: " + qNameConstraint);
    }
    nameConstraint = constraintDef.getConstraint();
    if (nameConstraint == null)
    {
        throw new AlfrescoRuntimeException("Constraint does not exist: " + qNameConstraint);
    }
}
 
Example 10
/**
 * This method is run as System within a single transaction on startup.
 */
public void startup()
{
    bindBehaviour();
                    
    // Get NodeRefs for folders to ignore
    this.ignoreExtractionFolders = new HashSet<NodeRef>(ignoreExtractionFoldersBeans.length * 2);

    for (RepositoryFolderConfigBean ignoreExtractionFoldersBean : ignoreExtractionFoldersBeans)
    {
        NodeRef nodeRef = ignoreExtractionFoldersBean.getFolderPath(namespaceService, nodeService, searchService,
                fileFolderService);

        if (!ignoreExtractionFolders.add(nodeRef))
        {
            // It was already in the set
            throw new AlfrescoRuntimeException("The folder extraction path has been referenced already: \n"
                    + "   Folder: " + ignoreExtractionFoldersBean);
        }
    }
    
    // Locate or create IMAP home
    imapHomeNodeRef = imapHomeConfigBean.getOrCreateFolderPath(namespaceService, nodeService, searchService, fileFolderService);        
}
 
Example 11
/**
 * Builds a new Request object, using HttpClient method descriptions
 */
public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method)
{
    // Get the method name
    String methodName;
    try
    {
        HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url);
        methodName = httpMethod.getName();
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("Error identifying method name", e);
    }
    
    // Build and return
    return buildRequest(url, methodName);
}
 
Example 12
private void checkCyclic(List<AuthorityBridgeLink> links)
{
    Map<String, Set<String>> parentsToChildren = new HashMap<String, Set<String>>();
    for (AuthorityBridgeLink link : links)
    {
        addToMap(parentsToChildren, link.getParentName(), link.getChildName());
    }
    
    Map<String, Set<String>> removed = new HashMap<String, Set<String>>();
    for (String parent : parentsToChildren.keySet())
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Start checking from '" + parent + "'");
        }
        Set<String> authorities = new HashSet<String>();
        authorities.add(parent);
        doCheck(parent, parentsToChildren, authorities, removed);
    }
    if (!removed.isEmpty())
    {
        fixCyclic(removed);
        throw new AlfrescoRuntimeException("Cyclic links were detected and removed.");
    }
}
 
Example 13
@Test
public void testFolderMissing() throws Exception
{
    try
    {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        fileFolderLoader.createFiles(
                sharedHomePath + "/Missing",
                0, 256, 1024L, 1024L, Long.MAX_VALUE, false,
                10, 256L);
        fail("Folder does not exist");
    }
    catch (AlfrescoRuntimeException e)
    {
        // Expected
        assertTrue(e.getCause() instanceof FileNotFoundException);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example 14
/**
 * Set the URL pseudo file name
 * 
 * @param urlFileName String
 */
public final void setURLFileName(String urlFileName)
{
    m_urlFileName = urlFileName;

    // URL file name must end with .url
    if (urlFileName != null)
    {
        if (!urlFileName.endsWith(".url"))
            throw new AlfrescoRuntimeException("URL link file must end with .url, " + urlFileName);
    }
}
 
Example 15
public Pair<Long, AuthorityEntity> findByValue(AuthorityEntity value)
{
    if ((value == null) || (value.getAuthority() == null))
    {
        throw new AlfrescoRuntimeException("Unexpected: AuthorityEntity / name must not be null");
    }
    return convertEntityToPair(getAuthorityEntity(value.getAuthority()));
}
 
Example 16
/**
     * Stores the value in the correct slot based on the type of persistence requested.
     * No conversion is done.
     * 
     * @param persistedType the value type
     * @param value the value - it may only be null if the persisted type is {@code ValueType#NULL}
     */
    public void setPersistedValue(ValueType persistedType, Serializable value)
    {
        switch (persistedType)
        {
            case NULL:
                if (value != null)
                {
                    throw new AlfrescoRuntimeException("Value must be null for persisted type: " + persistedType);
                }
                break;
            case BOOLEAN:
                this.booleanValue = (Boolean) value;
                break;
            case LONG:
                this.longValue = (Long) value;
                break;
            case FLOAT:
                this.floatValue = (Float) value;
                break;
            case DOUBLE:
                this.doubleValue = (Double) value;
                break;
            case STRING:
                this.stringValue = (String) value;
                break;
            case SERIALIZABLE:
                this.serializableValue = cloneSerializable(value);
                break;
//            case ENCRYPTED_STRING:
//                this.serializableValue = encrypt(value);
//                break;
            default:
                throw new AlfrescoRuntimeException("Unrecognised value type: " + persistedType);
        }
        // we store the type that we persisted as
        this.persistedType = persistedType;
    }
 
Example 17
protected void setOffsetWithExpectedFailure(String value)
{
    try
    {
        temporalSourceOptions.setOffset(value);
        fail("'" + value + "' should be invalid");
    }
    catch (AlfrescoRuntimeException e)
    {
        // expected
    }
}
 
Example 18
private void initTenant(String tenantDomain, String contentRoot, String dbUrl)
{
    validateTenantName(tenantDomain);
    
    if (existsTenant(tenantDomain))
    {
        throw new AlfrescoRuntimeException("Tenant already exists: " + tenantDomain);
    }
    
    if (contentRoot == null)
    {
        contentRoot = tenantFileContentStore.getRootLocation();
    }
    else
    {
        if (! isTenantRoutingContentStore(tenantFileContentStore))
        {
            // eg. ALF-14121 - MT will not work with replicating-content-services-context.sample
            throw new AlfrescoRuntimeException("MT: cannot initialse tenant - TenantRoutingContentStore is not configured AND tenant is not using co-mingled content store (ie. default root location)");
        }
        
        File tenantRootDir = new File(contentRoot);
        if ((tenantRootDir.exists()) && (tenantRootDir.list().length != 0))
        {
            logger.warn("Tenant root directory is not empty: " + contentRoot);
        }
    }
    
    // init - need to enable tenant (including tenant service) before stores bootstrap
    TenantEntity tenantEntity = new TenantEntity(tenantDomain);
    tenantEntity.setEnabled(true);
    tenantEntity.setContentRoot(contentRoot);
    tenantEntity.setDbUrl(dbUrl);
    
    tenantAdminDAO.createTenant(tenantEntity);
}
 
Example 19
/**
 * Ensures that required properties have been set
 */
public void afterPropertiesSet() throws Exception
{
    if (transformers == null || transformers.size() == 0)
    {
        throw new AlfrescoRuntimeException("At least one inner transformer must be supplied: " + this);
    }
    if (getMimetypeService() == null)
    {
        throw new AlfrescoRuntimeException("'mimetypeService' is a required property");
    }
}
 
Example 20
public byte[] generateMAC(String keyAlias, MACInput macInput)
{
    try
    {
        InputStream fullMessage = macInput.getMACInput();

        if(logger.isDebugEnabled())
        {
            logger.debug("Generating MAC for " + macInput + "...");
        }

        Mac mac = getMac(keyAlias);

        byte[] buf = new byte[1024];
        int len;
        while((len = fullMessage.read(buf, 0, 1024)) != -1)
        {
            mac.update(buf, 0, len);
        }
        byte[] newMAC = mac.doFinal();

        if(logger.isDebugEnabled())
        {
            logger.debug("...done. MAC is " + Arrays.toString(newMAC));
        }

        return newMAC;
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("Failed to generate MAC", e);
    }
}
 
Example 21
public void setSecureComms(String type)
{
	try
	{
		this.secureComms = SecureCommsType.getType(type);
	}
	catch(IllegalArgumentException e)
	{
		throw new AlfrescoRuntimeException("", e);
	}
}
 
Example 22
protected void setDurationWithExpectedFailure(String value)
{
    try
    {
        temporalSourceOptions.setDuration(value);
        fail("'" + value + "' should be invalid");
    }
    catch (AlfrescoRuntimeException e)
    {
        // expected
    }
}
 
Example 23
public DecryptingReadableByteChannel(final ReadableByteChannel delegateChannel, final Key key)
{
    this.delegateChannel = delegateChannel;

    try
    {
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        if (cipher.getBlockSize() == 0)
        {
            cipher.init(Cipher.DECRYPT_MODE, key);
            this.cipher = cipher;
        }
        else
        {
            cipher = Cipher.getInstance(key.getAlgorithm() + "/CBC/PKCS5Padding");

            final byte[] iv = new byte[cipher.getBlockSize()];
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            this.cipher = cipher;
        }
    }
    catch (final NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException e)
    {
        LOGGER.error("Error initializing cipher for key {}", key, e);
        throw new AlfrescoRuntimeException("Error initialising cipher", e);
    }
}
 
Example 24
public Pair<Long, PermissionEntity> findByValue(PermissionEntity value)
{
    if ((value == null) || (value.getName() == null) || (value.getTypeQNameId() == null))
    {
        throw new AlfrescoRuntimeException("Unexpected: PermissionEntity / name / qnameId must not be null");
    }
    return convertEntityToPair(getPermissionEntity(value.getTypeQNameId(), value.getName()));
}
 
Example 25
@Override
protected NodeRef getBaseTemplate()
{
    List<NodeRef> refs = searchService.selectNodes(
        repository.getRootHome(), 
        XPATHS[currentIndex], 
        null, 
        namespaceService, 
        false);
    if (refs.size() != 1)
    {
        throw new AlfrescoRuntimeException(I18NUtil.getMessage("patch.addDutchEmailTemplatesPatch.error"));
    }
    return refs.get(0);
}
 
Example 26
/**
 * Start the FTP server components
 * 
 * @exception SocketException If a network error occurs
 * @exception IOException If an I/O error occurs
 */
public final void startServer() throws SocketException, IOException
{
    try
    {
        // Create the FTP server, if enabled
        
        m_ftpConfig = (FTPConfigSection) filesysConfig.getConfigSection( FTPConfigSection.SectionName);
        
        if (m_ftpConfig != null)
        {
            // Create the FTP server
            
            ftpServer = new FTPServer(filesysConfig);
            filesysConfig.addServer(ftpServer);
        }


        // Start the server
        if(ftpServer != null)
        {
            // Start the FTP server
            if (logger.isInfoEnabled())
                logger.info("Starting server " + ftpServer.getProtocolName() + " ...");

            ftpServer.startServer();
        }
    }
    catch (Throwable e)
    {
    	ftpServer = null;
        throw new AlfrescoRuntimeException("Failed to start FTP Server", e);
    }
    // success
}
 
Example 27
public OutputStream getOutputStream() throws IOException
{
    if (outputStream == null)
    {
        if (outputWriter != null)
        {
            throw new AlfrescoRuntimeException("Already buffering output writer");
        }
        outputStream = streamFactory.createOutputStream();
    }
    return outputStream;
}
 
Example 28
protected String getName(String name, String tenantDomain, boolean checkTenantEnabled)
{
    ParameterCheck.mandatory("tenantDomain", tenantDomain);

    if (name == null)
    {
        return null;
    }

    if (checkTenantEnabled)
    {
        checkTenantEnabled(tenantDomain);
    }

    int idx1 = name.indexOf(SEPARATOR);
    if (idx1 != 0)
    {
        // no domain, so add it as a prefix (between two domain separators)
        name = SEPARATOR + tenantDomain + SEPARATOR + name;
    }
    else
    {
        int idx2 = name.indexOf(SEPARATOR, 1);
        String nameDomain = name.substring(1, idx2);
        if (!tenantDomain.equalsIgnoreCase(nameDomain))
        {
            throw new AlfrescoRuntimeException("domain mismatch: expected = " + tenantDomain + ", actual = " + nameDomain);
        }
    }

    return name;
}
 
Example 29
/**
 * {@inheritDoc}
 */
@Override
public TrustManager[] createTrustManagers()
{
    KeyInfoManager keyInfoManager = null;

    try
    {
        keyInfoManager = getKeyInfoManager(getKeyStoreParameters());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        logger.debug("Initializing trust managers");
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(ks);
        return tmfactory.getTrustManagers();
    }
    catch(Throwable e)
    {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    }
    finally
    {
        if(keyInfoManager != null)
        {
            keyInfoManager.clear();
        }
    }
}
 
Example 30
/**
 * @see org.alfresco.repo.template.BaseTemplateMap#get(java.lang.Object)
 */
public Object get(Object key)
{
    String search = null;
    
    if (key != null && key.toString().length() != 0)
    {
        // read the Saved Search XML on the specified node - and get the Lucene search from it
        try
        {
            NodeRef ref = new NodeRef(key.toString());
            
            ContentReader content = services.getContentService().getReader(ref, ContentModel.PROP_CONTENT);
            if (content != null && content.exists())
            {
                // get the root element
                SAXReader reader = new SAXReader();
                Document document = reader.read(new StringReader(content.getContentString()));
                Element rootElement = document.getRootElement();
                
                Element queryElement = rootElement.element(ELEMENT_QUERY);
                if (queryElement != null)
                {
                    search = queryElement.getText();
                }
            }
        }
        catch (Throwable err)
        {
            throw new AlfrescoRuntimeException("Failed to find or load saved Search: " + key, err);
        }
    }
    
    // execute the search
    return query(search);
}