Java Code Examples for org.alfresco.error.AlfrescoRuntimeException

The following are top voted examples for showing how to use org.alfresco.error.AlfrescoRuntimeException. 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: AuditComponentImpl.java   View source code 6 votes vote down vote up
/**
 * @param application       the audit application object
 * @return                  Returns a copy of the set of disabled paths associated with the application
 */
@SuppressWarnings("unchecked")
private Set<String> getDisabledPaths(AuditApplication application)
{
    try
    {
        Long disabledPathsId = application.getDisabledPathsId();
        Set<String> disabledPaths = (Set<String>) propertyValueDAO.getPropertyById(disabledPathsId);
        return new HashSet<String>(disabledPaths);
    }
    catch (Throwable e)
    {
        // Might be an invalid ID, somehow
        auditModelRegistry.loadAuditModels();
        throw new AlfrescoRuntimeException("Unabled to get AuditApplication disabled paths: " + application, e);
    }
}
 
Example 2
Project: alfresco-repository   File: ImapServiceImpl.java   View source code 6 votes vote down vote up
/**
 * 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 3
Project: alfresco-core   File: MACUtils.java   View source code 6 votes vote down vote up
/**
 * Compares the expectedMAC against the MAC generated from 
 * Assumes message has been decrypted
 * @param keyAlias String
 * @param expectedMAC byte[]
 * @param macInput MACInput
 * @return boolean
 */
public boolean validateMAC(String keyAlias, byte[] expectedMAC, MACInput macInput)
{
    try
    {
        byte[] mac = generateMAC(keyAlias, macInput);

        if(logger.isDebugEnabled())
        {
            logger.debug("Validating expected MAC " + Arrays.toString(expectedMAC) + " against mac " + Arrays.toString(mac) + " for MAC input " + macInput + "...");
        }

        boolean areEqual = Arrays.equals(expectedMAC, mac);
        
        if(logger.isDebugEnabled())
        {
            logger.debug(areEqual ? "...MAC validation succeeded." : "...MAC validation failed.");
        }

        return areEqual;
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("Failed to validate MAC", e);
    }        
}
 
Example 4
Project: alfresco-repository   File: PassthruFtpAuthenticator.java   View source code 6 votes vote down vote up
/**
 * Initialize the authenticator (after properties have been set)
 * 
 * @exception InvalidConfigurationException
 */
@Override
public void initialize() throws InvalidConfigurationException
{
    super.initialize();

    // Check if the appropriate authentication component type is configured
    AuthenticationComponent authenticationComponent = getAuthenticationComponent();
    if (authenticationComponent instanceof NLTMAuthenticator
            && ((NLTMAuthenticator) authenticationComponent).getNTLMMode() == NTLMMode.MD4_PROVIDER)
        throw new AlfrescoRuntimeException(
                "Wrong authentication setup for passthru authenticator (cannot be used with Alfresco users)");

    // Create the password encryptor

    m_passwordEncryptor = new PasswordEncryptor();
}
 
Example 5
Project: alfresco-repository   File: FTPServerBean.java   View source code 6 votes vote down vote up
/**
 * 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 6
Project: alfresco-repository   File: KeyStoreKeyProviderTest.java   View source code 6 votes vote down vote up
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 7
Project: alfresco-repository   File: TopicEmailMessageHandler.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void processMessage(NodeRef nodeRef, EmailMessage message)
{
    QName nodeTypeQName = getNodeService().getType(nodeRef);
    NodeRef topicNode = null;

    if (getDictionaryService().isSubClass(nodeTypeQName, ForumModel.TYPE_TOPIC))
    {
        topicNode = nodeRef;
    }
    else if (getDictionaryService().isSubClass(nodeTypeQName, ForumModel.TYPE_POST))
    {
        topicNode = getNodeService().getPrimaryParent(nodeRef).getParentRef();
        if (topicNode == null)
        {
            throw new AlfrescoRuntimeException("A POST node has no primary parent: " + nodeRef);
        }
    }
    else
    {
        throw new AlfrescoRuntimeException("\n" +
                "Message handler " + this.getClass().getName() + " cannot handle type " + nodeTypeQName + ".\n" +
                "Check the message handler mappings.");
    }
    addPostNode(topicNode, message);
}
 
Example 8
Project: alfresco-core   File: AbstractEncryptor.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public AlgorithmParameters decodeAlgorithmParameters(byte[] encoded)
{
    try
    {
        AlgorithmParameters p = null;
        String algorithm = "DESede";
        if(getCipherProvider() != null)
        {
            p = AlgorithmParameters.getInstance(algorithm, getCipherProvider());
        }
        else
        {
            p = AlgorithmParameters.getInstance(algorithm);
        }
        p.init(encoded);
        return p;
    }
    catch(Exception e)
    {
        throw new AlfrescoRuntimeException("", e);
    }
}
 
Example 9
Project: alfresco-core   File: DefaultEncryptionUtils.java   View source code 6 votes vote down vote up
/**
 * Set the MAC on the HTTP response
 * 
 * @param response HttpServletResponse
 * @param mac byte[]
 */
protected void setMac(HttpServletResponse response, byte[] mac)
{
    if(mac == null)
    {
        throw new AlfrescoRuntimeException("Mac cannot be null");
    }

    response.setHeader(HEADER_MAC, Base64.encodeBytes(mac));    
}
 
Example 10
Project: alfresco-repository   File: NotificationServiceImpl.java   View source code 6 votes vote down vote up
/** 
 * @see org.alfresco.service.cmr.notification.NotificationService#sendNotification(java.lang.String, org.alfresco.service.cmr.notification.NotificationContext)
 */
@Override
public void sendNotification(String notificationProvider, NotificationContext notificationContext) 
{
    // Check the mandatory params
    ParameterCheck.mandatory("notificationProvider", notificationProvider);
    ParameterCheck.mandatory("notificationContext", notificationContext);
    
    // Check that the notificaiton provider exists
    if (exists(notificationProvider) == false)
    {
        throw new AlfrescoRuntimeException(I18NUtil.getMessage(MSG_NP_DOES_NOT_EXIST, notificationProvider));
    }
    
    // Get the notification provider and send notification
    NotificationProvider provider = providers.get(notificationProvider);
    provider.sendNotification(notificationContext);
}
 
Example 11
Project: alfresco-repository   File: RepoUsageComponentImpl.java   View source code 6 votes vote down vote up
/**
 * Checks that the 'System' user is active in a read-write txn.
 */
private final void checkTxnState(TxnReadState txnStateNeeded)
{
    switch (txnStateNeeded)
    {
        case TXN_READ_WRITE:
            if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_READ_WRITE)
            {
                throw AlfrescoRuntimeException.create("system.usage.err.no_txn_readwrite");
            }
            break;
        case TXN_READ_ONLY:
            if (AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_NONE)
            {
                throw AlfrescoRuntimeException.create("system.usage.err.no_txn");
            }
            break;
    }
}
 
Example 12
Project: alfresco-repository   File: MultilingualContentServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @return Returns a reference to the node that will hold all the <b>cm:mlContainer</b> nodes.
 */
private NodeRef getMLContainerRoot()
{
    NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    List<ChildAssociationRef> assocRefs = nodeService.getChildAssocs(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QNAME_ASSOC_ML_ROOT);
    if (assocRefs.size() != 1)
    {
        throw new AlfrescoRuntimeException(
                "Unable to find bootstrap location for ML Root using query: " + QNAME_ASSOC_ML_ROOT);
    }
    NodeRef mlRootNodeRef = assocRefs.get(0).getChildRef();
    // Done
    return mlRootNodeRef;
}
 
Example 13
Project: alfresco-core   File: NamedObjectRegistry.java   View source code 6 votes vote down vote up
/**
 * Optionally set a pattern to which all object names must conform
 * @param namePattern   a regular expression
 */
public void setNamePattern(String namePattern)
{
    writeLock.lock();
    try
    {
        this.namePattern = Pattern.compile(namePattern);
    }
    catch (PatternSyntaxException e)
    {
        throw new AlfrescoRuntimeException(
                "Regular expression compilation failed for property 'namePrefix': " + e.getMessage(),
                e);
    }
    finally
    {
        writeLock.unlock();
    }
}
 
Example 14
Project: alfresco-repository   File: MultiTServiceImpl.java   View source code 6 votes vote down vote up
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 15
Project: alfresco-repository   File: VersionServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Sets an optional comparator to sort a versions in descending order (eg. 2.1, 2.0, 1.1, 1.0).
 * Really only needed in a 4.1.3 system (or above) that has been upgraded from an earlier system
 * that used NON ordered sequence numbers in a cluster. Not something we really support but was
 * the subject of MNT-226.
 * @param versionComparatorClass the name of a comparator. For example
 *        "org.alfresco.repo.version.common.VersionLabelComparator".
 */
@SuppressWarnings("unchecked")
public void setVersionComparatorClass(String versionComparatorClass)
{
    if (versionComparatorClass != null && versionComparatorClass.trim().length() != 0)
    {
        try
        {
            versionComparatorDesc = (Comparator<Version>) getClass().getClassLoader().
                    loadClass(versionComparatorClass.trim()).newInstance();
        }
        catch (Exception e)
        {
            throw new AlfrescoRuntimeException(
                    "Failed to create a Comparator<Version> using the class name "+
                    versionComparatorClass, e);
        }
    }
}
 
Example 16
Project: alfresco-repository   File: XPathMetadataExtracter.java   View source code 6 votes vote down vote up
/**
 * Default constructor
 */
public XPathMetadataExtracter()
{
    super(new HashSet<String>(Arrays.asList(SUPPORTED_MIMETYPES)));
    try
    {
        DocumentBuilderFactory normalFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = normalFactory.newDocumentBuilder();
        
        DocumentBuilderFactory dtdIgnoringFactory = DocumentBuilderFactory.newInstance();
        dtdIgnoringFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dtdIgnoringFactory.setFeature("http://xml.org/sax/features/validation", false);
        dtdIgnoringDocumentBuilder = dtdIgnoringFactory.newDocumentBuilder();
        
        xpathFactory = XPathFactory.newInstance();
    }
    catch (Throwable e)
    {
        throw new AlfrescoRuntimeException("Failed to initialize XML metadata extractor", e);
    }
}
 
Example 17
Project: alfresco-repository   File: PatchServiceImpl.java   View source code 6 votes vote down vote up
public void execute()
{
    if(state != STATE.START)
    {
        throw new IllegalStateException("Patch is already being applied");
    }

    if(!patch.requiresTransaction() && AlfrescoTransactionSupport.isActualTransactionActive())
    {
        throw new AlfrescoRuntimeException("Patch " +
                patch.getId() +
                " has been configured with requiresTransaction set to false but is being called in a transaction");
    }

    setup();
    applyPatch();
    save();
}
 
Example 18
Project: alfresco-repository   File: FolderContentsParameterConstraint.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.action.ParameterConstraint#getAllowableValues()
 */
protected Map<String, String> getAllowableValuesImpl()
{
    List<NodeRef> nodeRefs = searchService.selectNodes(repository.getRootHome(), 
                this.searchPath, null, this.namespaceService, false);
    
    NodeRef rootFolder = null;
    if (nodeRefs.size() == 0)
    {
        throw new AlfrescoRuntimeException("The path '" + searchPath + "' did not return any results.");
    }
    else
    {
        rootFolder = nodeRefs.get(0);
    }
    
    Map<String, String> result = new LinkedHashMap<String, String>(23);
    buildMap(result, rootFolder);        
    return result;
}
 
Example 19
Project: alfresco-repository   File: UnserializerValidatorBootstrap.java   View source code 6 votes vote down vote up
private void validate()
{
    if (classInPath("org.apache.xalan.xsltc.trax.TemplatesImpl") && classInPath("org.springframework.core.SerializableTypeWrapper"))
    {
        throw new AlfrescoRuntimeException(
                "Bootstrap failed: both org.apache.xalan.xsltc.trax.TemplatesImpl and org.springframework.core.SerializableTypeWrapper appear at the same time in classpath ");
    }

    // Check if Java unserialize remote code execution is available and not
    // fixed on this <b>commons collections</b>
    if ((classInPath("org.apache.commons.collections.functors.InvokerTransformer")
            || classInPath("org.apache.commons.collections.functors.InstantiateFactory")
            || classInPath("org.apache.commons.collections.functors.InstantiateTransformer")
            || classInPath("org.apache.commons.collections.functors.PrototypeCloneFactory")
            || classInPath("org.apache.commons.collections.functors.PrototypeSerializationFactory")
            || classInPath("org.apache.commons.collections.functors.WhileClosure")
            || classInPath("org.apache.commons.collections.functors.CloneTransformer") || classInPath("org.apache.commons.collections.functors.ForClosure"))
            && !isCommonsCollectionsDeserializerFixed())
    {
        throw new AlfrescoRuntimeException(
                "Bootstrap failed: org.apache.commons.collections.functors.* unsafe serialization classes found in classpath.");
    }
}
 
Example 20
Project: alfresco-repository   File: AlfrescoSSLSocketFactoryTest.java   View source code 6 votes vote down vote up
@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 21
Project: alfresco-repository   File: AuthorityBridgeTableAsynchronouslyRefreshedCacheTest.java   View source code 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE)
    {
        throw new AlfrescoRuntimeException(
                "A previous tests did not clean up transaction: " +
                AlfrescoTransactionSupport.getTransactionId());
    }
    
    transactionService = (TransactionService) ctx.getBean(ServiceRegistry.TRANSACTION_SERVICE.getLocalName());
    authorityService = (AuthorityService) ctx.getBean(ServiceRegistry.AUTHORITY_SERVICE.getLocalName());
    tenantAdminService = ctx.getBean("tenantAdminService", TenantAdminService.class);
    personService = (PersonService) ctx.getBean(ServiceRegistry.PERSON_SERVICE.getLocalName());
    tenantService = (TenantService) ctx.getBean("tenantService");
    authorityBridgeTableCache = (AuthorityBridgeTableAsynchronouslyRefreshedCache) ctx.getBean("authorityBridgeTableCache");
}
 
Example 22
Project: alfresco-repository   File: PersonServiceImpl.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc} 
 */
public void deletePerson(NodeRef personRef, boolean deleteAuthentication)
{
    QName typeQName = nodeService.getType(personRef);
    if (typeQName.equals(ContentModel.TYPE_PERSON))
    {
        if (deleteAuthentication)
        {
            String userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
            deletePersonAndAuthenticationImpl(userName, personRef);
        }
        else
        {
            deletePersonImpl(personRef);
        }
    }
    else
    {
        throw new AlfrescoRuntimeException("deletePerson: invalid type of node "+personRef+" (actual="+typeQName+", expected="+ContentModel.TYPE_PERSON+")");
    }
}
 
Example 23
Project: alfresco-repository   File: UsageQuotaProtector.java   View source code 6 votes vote down vote up
/**
 * Called after a node's properties have been changed.
 * 
 * @param nodeRef reference to the updated node
 * @param before the node's properties before the change
 * @param after the node's properties after the change 
 */
public void onUpdateProperties(
        NodeRef nodeRef,
        Map<QName, Serializable> before,
        Map<QName, Serializable> after)
{    
    Long sizeCurrentBefore = (Long)before.get(ContentModel.PROP_SIZE_CURRENT);
    Long sizeCurrentAfter = (Long)after.get(ContentModel.PROP_SIZE_CURRENT); 
        
    Long sizeQuotaBefore = (Long)before.get(ContentModel.PROP_SIZE_QUOTA);
    Long sizeQuotaAfter = (Long)after.get(ContentModel.PROP_SIZE_QUOTA); 
    
    // Check for change in sizeCurrent
    if ((sizeCurrentBefore != null && !sizeCurrentBefore.equals(sizeCurrentAfter)) && (sizeCurrentBefore != null) &&
        (! (authorityService.hasAdminAuthority() || AuthenticationUtil.isRunAsUserTheSystemUser())))
    {
        throw new AlfrescoRuntimeException("Update failed: protected property 'sizeCurrent'");
    }
    
    // Check for change in sizeQuota
    if ((sizeQuotaBefore != null && !sizeQuotaBefore.equals(sizeQuotaAfter)) && (sizeQuotaBefore != null) &&
        (! (authorityService.hasAdminAuthority() || AuthenticationUtil.isRunAsUserTheSystemUser())))
    {
        throw new AlfrescoRuntimeException("Update failed: protected property 'sizeQuota'");
    }
}
 
Example 24
Project: alfresco-core   File: HttpClientFactory.java   View source code 6 votes vote down vote up
public HttpClient getHttpClient(String host, int port)
{
    HttpClient httpClient = null;

    if(secureCommsType == SecureCommsType.HTTPS)
    {
        httpClient = getHttpsClient(host, port);
    }
    else if(secureCommsType == SecureCommsType.NONE)
    {
        httpClient = getDefaultHttpClient(host, port);
    }
    else
    {
        throw new AlfrescoRuntimeException("Invalid Solr secure communications type configured in alfresco.secureComms, should be 'ssl'or 'none'");
    }

    return httpClient;
}
 
Example 25
Project: alfresco-repository   File: ScriptInvitationFactory.java   View source code 6 votes vote down vote up
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 26
Project: alfresco-repository   File: IndexInfo.java   View source code 6 votes vote down vote up
private static RandomAccessFile openFile(File file)
{
    try
    {
        if (useNIOMemoryMapping)
        {
            return new RandomAccessFile(file, "rw");
        }
        else
        {
            return new RandomAccessFile(file, "rws");
        }
    }
    catch (FileNotFoundException e)
    {
        throw new AlfrescoRuntimeException("Failed to open index info file", e);
    }
}
 
Example 27
Project: alfresco-repository   File: TemporalSourceOptionsTest.java   View source code 5 votes vote down vote up
protected void setOffsetWithExpectedFailure(String value)
{
    try
    {
        temporalSourceOptions.setOffset(value);
        fail("'" + value + "' should be invalid");
    }
    catch (AlfrescoRuntimeException e)
    {
        // expected
    }
}
 
Example 28
Project: alfresco-repository   File: AlfrescoSSLSocketFactory.java   View source code 5 votes vote down vote up
public static synchronized SocketFactory getDefault()
{
    if (context == null)
    {
        throw new AlfrescoRuntimeException("The factory was not initialized.");
    }
    return new AlfrescoSSLSocketFactory();
}
 
Example 29
Project: alfresco-repository   File: OAuth2CredentialsStoreServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @param exisitingCredentials OAuth2CredentialsInfo
 * @param remoteSystemId String
 * @param accessToken String
 * @param refreshToken String
 * @param expiresAt Date
 * @param issuedAt Date
 * @return OAuth2CredentialsInfo
 */
@Override
public OAuth2CredentialsInfo updateSharedOAuth2Credentials(
            OAuth2CredentialsInfo exisitingCredentials, String remoteSystemId,
            String accessToken, String refreshToken, Date expiresAt, Date issuedAt)
            throws NoSuchSystemException
{
    List<OAuth2CredentialsInfo> shared = listSharedOAuth2Credentials(remoteSystemId);

    for (OAuth2CredentialsInfo credential : shared)
    {
        if (credential.getNodeRef().equals(exisitingCredentials.getNodeRef()))
        {
            OAuth2CredentialsInfoImpl credentials = new OAuth2CredentialsInfoImpl(
                        exisitingCredentials.getNodeRef(),
                        exisitingCredentials.getRemoteSystemName(),
                        exisitingCredentials.getRemoteSystemContainerNodeRef());

            credentials.setOauthAccessToken(accessToken);
            credentials.setOauthRefreshToken(refreshToken);
            credentials.setOauthTokenExpiresAt(expiresAt);
            if (issuedAt != null)
            {
                credentials.setOauthTokenIssuedAt(issuedAt);
            }
            else
            {
                credentials.setOauthTokenIssuedAt(new Date());
            }

            return (OAuth2CredentialsInfo) remoteCredentialsService
                        .updateCredentials(credentials);

        }
    }

    throw new AlfrescoRuntimeException(
                "Cannot update Credentials which haven't been persisted yet!");
}
 
Example 30
Project: alfresco-repository   File: MultiTServiceImpl.java   View source code 5 votes vote down vote up
private QName getName(QName name, String tenantDomain)
{
    if (name == null)
    {
        return null;
    }

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

    return name;
}
 
Example 31
Project: alfresco-repository   File: TemporalSourceOptionsTest.java   View source code 5 votes vote down vote up
protected void setDurationWithExpectedFailure(String value)
{
    try
    {
        temporalSourceOptions.setDuration(value);
        fail("'" + value + "' should be invalid");
    }
    catch (AlfrescoRuntimeException e)
    {
        // expected
    }
}
 
Example 32
Project: alfresco-repository   File: AbstractServerConfigurationBean.java   View source code 5 votes vote down vote up
/**
 * Parse the platforms attribute returning the set of platform ids
 * 
 * @param platformStr String
 */
protected final EnumSet<Platform.Type> parsePlatformString(String platformStr)
{
    // Split the platform string and build up a set of platform types
  
    EnumSet<Platform.Type> platformTypes = EnumSet.noneOf(Platform.Type.class);
    if (platformStr == null || platformStr.length() == 0)
        return platformTypes;
  
    StringTokenizer token = new StringTokenizer(platformStr.toUpperCase(Locale.ENGLISH), ",");
    String typ = null;
  
    try
    {
        while (token.hasMoreTokens())
        {
  
            // Get the current platform type string and validate
  
            typ = token.nextToken().trim();
            Platform.Type platform = Platform.Type.valueOf(typ);
  
            if (platform != Platform.Type.Unknown)
                platformTypes.add(platform);
            else
                throw new AlfrescoRuntimeException("Invalid platform type, " + typ);
        }
    }
    catch (IllegalArgumentException ex)
    {
        throw new AlfrescoRuntimeException("Invalid platform type, " + typ);
    }
  
    // Return the platform types
  
    return platformTypes;
}
 
Example 33
Project: alfresco-repository   File: NodePropertyValue.java   View source code 5 votes vote down vote up
/**
     * 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 34
Project: alfresco-repository   File: MultiTServiceImpl.java   View source code 5 votes vote down vote up
@Override
public String getBaseName(String name, boolean forceForNonTenant)
{
    if (name == null)
    {
        return null;
    }

    String tenantDomain = getCurrentUserDomain();

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

        if ((!tenantDomain.equals(DEFAULT_DOMAIN)) && (!tenantDomain.equals(nameDomain)))
        {
            throw new AlfrescoRuntimeException("domain mismatch: expected = " + tenantDomain + ", actual = " + nameDomain);
        }

        if ((!tenantDomain.equals(DEFAULT_DOMAIN)) || (forceForNonTenant))
        {
            // remove tenant domain
            name = name.substring(idx2 + 1);
        }
    }

    return name;
}
 
Example 35
Project: alfresco-repository   File: AuditModelRegistryImpl.java   View source code 5 votes vote down vote up
/**
 * Unmarshalls the Audit model from the URL.
 * 
 * @param configUrl                     the config url
 * @return                              the audit model
 * @throws AlfrescoRuntimeException     if an IOException occurs
 */
public static Audit unmarshallModel(URL configUrl)
{
    try
    {
        // Load it
        InputStream is = new BufferedInputStream(configUrl.openStream());
        return unmarshallModel(is, configUrl.toString());
    }
    catch (IOException e)
    {
        throw new AlfrescoRuntimeException("The Audit model XML failed to load: " + configUrl, e);
    }
}
 
Example 36
Project: alfresco-repository   File: FeedCleanupJob.java   View source code 5 votes vote down vote up
/**
 * Calls the feed cleaner to do its work
 */
public void execute(JobExecutionContext context) throws JobExecutionException
{
    JobDataMap jobData = context.getJobDetail().getJobDataMap();
    // extract the feed cleaner to use
    Object feedCleanerObj = jobData.get("feedCleaner");
    if (feedCleanerObj == null || !(feedCleanerObj instanceof FeedCleaner))
    {
        throw new AlfrescoRuntimeException(
                "FeedCleanupJob data must contain valid 'feedCleaner' reference");
    }
    FeedCleaner feedCleaner = (FeedCleaner)feedCleanerObj;
    feedCleaner.execute();
}
 
Example 37
Project: alfresco-repository   File: ScriptTestUtils.java   View source code 5 votes vote down vote up
public void assertNotEquals(Object expected, Object value, String message)
{
    if (expected.equals(value) == true)
    {
        if (message == null)
        {
            message = "Expected value '" + expected + "' should not match recieved value '" + value + "'";
        }
        throw new AlfrescoRuntimeException(message);
    }
}
 
Example 38
Project: alfresco-repository   File: DatePropertyValueComparator.java   View source code 5 votes vote down vote up
private Date getDate(Serializable value) 
{
    if(value instanceof Date)
    {
        return (Date) value;
    } 
    else if(value instanceof String)
    {
        return ISO8601DateFormat.parse((String) value);
    } 
    throw new AlfrescoRuntimeException("Parameter 'compareValue' must be of type java.util.Date!");
}
 
Example 39
Project: alfresco-repository   File: SolrBackupJob.java   View source code 5 votes vote down vote up
/**
 * Calls the cleaner to do its work
 */
public void execute(JobExecutionContext context) throws JobExecutionException
{
    JobDataMap jobData = context.getJobDetail().getJobDataMap();
    // extract the SOLR backup client to use
    Object solrBackupClientObj = jobData.get("solrBackupClient");
    if (solrBackupClientObj == null || !(solrBackupClientObj instanceof SolrBackupClient))
    {
        throw new AlfrescoRuntimeException(
                "SolrBackupJob data must contain valid 'solrBackupClient' reference");
    }
    SolrBackupClient solrBackupClient = (SolrBackupClient) solrBackupClientObj;
    solrBackupClient.execute();
}
 
Example 40
Project: alfresco-repository   File: DictionaryRepositoryBootstrap.java   View source code 5 votes vote down vote up
/**
 * Loads a model (and its dependents) if it does not exist in the list of loaded models.
 * 
 * @param modelMap          a map of the models to be loaded
 * @param loadedModels      the list of models already loaded
 * @param model             the model to try and load
 */
private void loadModel(Map<String, DynamicModelInfo> modelMap, List<String> loadedModels, M2Model model, RepositoryLocation modelLocation)
{
    String modelName = model.getName();
    if (loadedModels.contains(modelName) == false)
    {
        for (M2Namespace importNamespace : model.getImports())
        {
            DynamicModelInfo entry = modelMap.get(importNamespace.getUri());
            if (entry != null)
            {
                RepositoryLocation importedLocation = entry.location;
                M2Model importedModel = entry.model;
                
                // Ensure that the imported model is loaded first
                loadModel(modelMap, loadedModels, importedModel, importedLocation);
            }
            // else we can assume that the imported model is already loaded, if this not the case then
            //      an error will be raised during compilation
        }
        
        try
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Loading model: " + modelName
                        + " (from ["+ modelLocation.getStoreRef() + "]"+ modelLocation.getPath() + ")");
            }

            dictionaryDAO.putModel(model);

            loadedModels.add(modelName);
        }
        catch (AlfrescoRuntimeException e)
        {
            // note: skip with warning - to allow server to start, and hence allow the possibility of fixing the broken model(s)
            logger.warn("Failed to load model '" + modelName + "' : " + e);
        }
    }
}