Java Code Examples for org.springframework.extensions.surf.util.I18NUtil#getLocale()

The following examples show how to use org.springframework.extensions.surf.util.I18NUtil#getLocale() . 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
Source File: ExporterComponentTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void before() throws Exception
{
    nodeService = (NodeService)applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName());
    exporterService = (ExporterService)applicationContext.getBean("exporterComponent");
    importerService = (ImporterService)applicationContext.getBean("importerComponent");
    fileFolderService = (FileFolderService) applicationContext.getBean("fileFolderService");
    categoryService = (CategoryService) applicationContext.getBean("categoryService");     
    transactionService = (TransactionService) applicationContext.getBean("transactionService");
    permissionService = (PermissionServiceSPI) applicationContext.getBean("permissionService");

    this.authenticationService = (MutableAuthenticationService) applicationContext.getBean("AuthenticationService");
    this.authenticationComponent = (AuthenticationComponent) applicationContext.getBean("authenticationComponent");
    this.authenticationComponent.setSystemUserAsCurrentUser();
    this.storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    contentLocaleToRestore = I18NUtil.getContentLocale();
    localeToRestore = I18NUtil.getLocale();
}
 
Example 2
Source File: AbstractLocaleDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 3
Source File: ActionDefinitionImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * REPO-2253: Community: ALF-21854 Action parameter lookup for "de_DE" falls back to "root" locale instead of "de"
 */
public void testParameterDefinitionLocaleFallback()
{
    Locale originalLocale = I18NUtil.getLocale();
    try
    {
        ActionDefinitionImpl actionDef = new ActionDefinitionImpl(NAME);
        Map<Locale, List<ParameterDefinition>> localizedParams = new HashMap<>();
        
        
        localizedParams.put(Locale.ROOT, exampleFieldList("English Label"));
        localizedParams.put(Locale.ENGLISH, exampleFieldList("English Label"));
        localizedParams.put(Locale.UK, exampleFieldList("UK-specific Label"));
        localizedParams.put(Locale.GERMAN, exampleFieldList("German Label"));
        actionDef.setLocalizedParameterDefinitions(localizedParams);

        I18NUtil.setLocale(null);
        assertEquals("English Label", actionDef.getParameterDefintion("example-field").getDisplayLabel());

        I18NUtil.setLocale(Locale.ENGLISH);
        assertEquals("English Label", actionDef.getParameterDefintion("example-field").getDisplayLabel());

        // en-GB does not need to fallback to en
        I18NUtil.setLocale(Locale.UK);
        assertEquals("UK-specific Label", actionDef.getParameterDefintion("example-field").getDisplayLabel());

        I18NUtil.setLocale(Locale.GERMAN);
        assertEquals("German Label", actionDef.getParameterDefintion("example-field").getDisplayLabel());
        
        I18NUtil.setLocale(Locale.GERMANY);
        // de-DE falls back to de
        assertEquals("German Label", actionDef.getParameterDefintion("example-field").getDisplayLabel());
    }
    finally
    {
        I18NUtil.setLocale(originalLocale);
    }
}
 
Example 4
Source File: FullNodeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void before()
{
    super.before();
    contentLocaleToRestore = I18NUtil.getContentLocale();
    localeToRestore = I18NUtil.getLocale();
    Locale.setDefault(Locale.ENGLISH);
    MLPropertyInterceptor.setMLAware(false);
}
 
Example 5
Source File: MLText.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves a default value from the set of available locales.<br/>
 * 
 * @see I18NUtil#getLocale()
 * @see #getClosestValue(Locale)
 */
public String getDefaultValue()
{
    // Shortcut so that we don't have to go and get the current locale
    if (this.size() == 0)
    {
        return null;
    }
    // There is some hope of getting a match
    Locale locale = I18NUtil.getLocale();
    return getClosestValue(locale);
}
 
Example 6
Source File: EmailHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the user's locale.
 *
 * @param userId the user id
 * @return the default locale or the user's preferred locale, if available
 */
public Locale getUserLocaleOrDefault(String userId)
{
    if (userId != null && personService.personExists(userId))
    {
        String localeString = AuthenticationUtil.runAsSystem(() -> (String) preferenceService.getPreference(userId, "locale"));
        if (localeString != null)
        {
            return I18NUtil.parseLocale(localeString);
        }
    }

    return I18NUtil.getLocale();
}
 
Example 7
Source File: LocaleDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testDefaultLocale() throws Exception
{
    RetryingTransactionCallback<Pair<Long, Locale>> callback = new RetryingTransactionCallback<Pair<Long, Locale>>()
    {
        public Pair<Long, Locale> execute() throws Throwable
        {
            // What is the thread's default locale?
            Locale defaultLocale = I18NUtil.getLocale();
            // Now make it
            Pair<Long, Locale> localePair = localeDAO.getOrCreateDefaultLocalePair();
            assertNotNull("Default locale should now exist", localePair);
            assertEquals(
                    "The default locale returned must match the current thread's default locale",
                    defaultLocale, localePair.getSecond());
            // Done
            return localePair;
        }
    };
    
    // Check that the default locale is handled properly
    txnHelper.doInTransaction(callback);
    
    // Now change the default locale
    I18NUtil.setLocale(Locale.CANADA_FRENCH);
    // Repeat
    txnHelper.doInTransaction(callback);
}
 
Example 8
Source File: MLText.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The given locale is used to search for a matching value according to:
 * <ul>
 *   <li>An exact locale match</li>
 *   <li>A match of locale ISO language codes</li>
 *   <li>The value for the locale provided in the {@link MLText#MLText(Locale, String) constructor}</li>
 *   <li>An arbitrary value</li>
 *   <li><tt>null</tt></li>
 * </ul>
 * 
 * @param locale the locale to use as the starting point of the value search
 * @return Returns a default <tt>String</tt> value or null if one isn't available.
 *      <tt>null</tt> will only be returned if there are no values associated with
 *      this instance.  With or without a match, the return value may be <tt>null</tt>,
 *      depending on the values associated with the locales.
 */
public String getClosestValue(Locale locale)
{
    if (this.size() == 0)
    {
        return null;
    }
    // Use the available keys as options
    Set<Locale> options = keySet();
    // Get a match
    Locale match = I18NUtil.getNearestLocale(locale, options);
    if (match == null)
    {
        // No close matches for the locale - go for the default locale
        locale = I18NUtil.getLocale();
        match = I18NUtil.getNearestLocale(locale, options);
        if (match == null)
        {
            // just get any locale
            match = I18NUtil.getNearestLocale(null, options);
        }
    }
    // Did we get a match
    if (match == null)
    {
        // We could find no locale matches
        return null;
    }
    else
    {
        return get(match);
    }
}
 
Example 9
Source File: MLPropertyInterceptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Locale getClosestLocale(Collection<?> collection)
{
    if (collection.size() == 0)
    {
        return null;
    }
    // Use the available keys as options
    HashSet<Locale> locales = new HashSet<Locale>();
    for(Object o : collection)
    {
        MLText mlText = (MLText)o;
        locales.addAll(mlText.keySet());
    }
    // Try the content locale
    Locale locale = I18NUtil.getContentLocale();
    Locale match = I18NUtil.getNearestLocale(locale, locales);
    if (match == null)
    {
        // Try just the content locale language
        locale = I18NUtil.getContentLocaleLang();
        match = I18NUtil.getNearestLocale(locale, locales);
        if (match == null)
        {
            // No close matches for the locale - go for the default locale
            locale = I18NUtil.getLocale();
            match = I18NUtil.getNearestLocale(locale, locales);
            if (match == null)
            {
                // just get any locale
                match = I18NUtil.getNearestLocale(null, locales);
            }
        }
    }
    return match;
}
 
Example 10
Source File: AbstractContentAccessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param contentUrl the content URL
 */
protected AbstractContentAccessor(String contentUrl)
{
    ParameterCheck.mandatoryString("contentUrl", contentUrl);
    if (contentUrl == null || contentUrl.length() == 0)
    {
        throw new IllegalArgumentException("contentUrl is invalid:" + contentUrl);
    }
    this.contentUrl = contentUrl;
    
    // the default encoding is Java's default encoding
    encoding = "UTF-8";
    // the default locale
    locale = I18NUtil.getLocale();
}
 
Example 11
Source File: FileFolderServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public NodeRef getLocalizedSibling(NodeRef nodeRef)
{
    Locale userLocale = I18NUtil.getLocale();
    
    String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
    NodeRef parentNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
    // Work out the base name we are working with
    Pair<String, String> split = getExtension(name, false);
    String base = split.getFirst();
    String ext = split.getSecond();
    
    NodeRef resultNodeRef = nodeRef;
    // Search for siblings with the same name
    Control resourceHelper = Control.getControl(Control.FORMAT_DEFAULT);
    List<Locale> candidateLocales = resourceHelper.getCandidateLocales(base, userLocale);
    for (Locale candidateLocale : candidateLocales)
    {
        String filename = resourceHelper.toBundleName(base, candidateLocale) + "." + ext;
        // Attempt to find the file
        NodeRef foundNodeRef = searchSimple(parentNodeRef, filename);
        if (foundNodeRef != null)   // TODO: Check for read permissions
        {
            resultNodeRef = foundNodeRef;
            break;
        }
    }
    // Done
    return resultNodeRef;
}
 
Example 12
Source File: SolrClientUtil.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Locale extractLocale(BasicSearchParameters searchParameters)
{
    Locale locale = I18NUtil.getLocale();
    if (searchParameters.getLocales().size() > 0)
    {
        locale = searchParameters.getLocales().get(0);
    }
    return locale;
}
 
Example 13
Source File: EMailNotificationProvider.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.notification.NotificationProvider#sendNotification(org.alfresco.service.cmr.notification.NotificationContext)
 */
@Override
public void sendNotification(NotificationContext notificationContext)
{
    Action mail = actionService.createAction(MailActionExecuter.NAME);
    
    // Set from parameter
    String from = notificationContext.getFrom();
    if (from != null && from.length() != 0)
    {
        String fromEMail = getEMailFromUser(from);
        if (fromEMail != null)
        {
            mail.setParameterValue(MailActionExecuter.PARAM_FROM, fromEMail);
        }
        else
        {
            if (logger.isWarnEnabled() == true)
            {
                logger.warn(I18NUtil.getMessage(MSG_DEFAULT_SENDER_USED, from));
            }
        }
    }
    
    // Set to parameter
    List<String> to = notificationContext.getTo();
    if (to == null || to.size() == 0)
    {
        errorEncountered(notificationContext, 
                         I18NUtil.getMessage(MSG_NO_RECIPIENTS, notificationContext.getDocument()));
        return;
    }
    else
    {
        mail.setParameterValue(MailActionExecuter.PARAM_TO_MANY, (Serializable)to);
    }        
    
    // Set subject
    String subject = notificationContext.getSubject();
    if (subject != null)
    {
        mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject);
    }

    // Note that the smart logic in MailActionExecuter should recognize any
    // preferred locale for the users in the recipient field and override this value
    // Note that the smart logic in MailActionExecuter may be broken if we send email addresses
    // instead of userIDs
    Locale userLocale = I18NUtil.getLocale();
    if (userLocale != null)
    {
        mail.setParameterValue(MailActionExecuter.PARAM_LOCALE, userLocale);
    }

    // Set body 
    String body = notificationContext.getBody();
    if (body != null && body.length() != 0)
    {
        mail.setParameterValue(MailActionExecuter.PARAM_TEXT, body);
    }
    else
    {
        // Check for template
        String template = notificationContext.getBodyTemplate();
        if (template == null)
        {
            errorEncountered(notificationContext, 
                             I18NUtil.getMessage(MSG_NO_BODY_OR_TEMPLATE, notificationContext.getDocument()));
            return;
        }
        else
        {
            if (template.indexOf(StoreRef.URI_FILLER) != -1)
            {
                template = fileFolderService.getLocalizedSibling(new NodeRef(template)).toString();
            }
            mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
            mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, 
                                   (Serializable)buildTemplateModel(notificationContext.getTemplateArgs()));
        }
    }
    
    // Set ignore failure
    mail.setParameterValue(MailActionExecuter.PARAM_IGNORE_SEND_FAILURE, Boolean.valueOf(notificationContext.isIgnoreNotificationFailure()));
    
    // Execute mail action upon document
    actionService.executeAction(mail, notificationContext.getDocument(), false, notificationContext.isAsyncNotification());       
}
 
Example 14
Source File: AlfrescoCollatableMLTextFieldType.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public FieldComparator<String> newComparator(String fieldname, int numHits, int sortPos, boolean reversed)
{
    return new MLTextSortFieldComparator(numHits, fieldname, I18NUtil.getLocale());
}
 
Example 15
Source File: DynamicCreateRepositoryLocation.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setBundleName(String bundleName)
{
       Locale bindingLocale = I18NUtil.getLocale();
       this.bundle = ResourceBundle.getBundle(bundleName, bindingLocale);
}
 
Example 16
Source File: MessageServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Locale getLocale()
{
    return I18NUtil.getLocale();
}
 
Example 17
Source File: DbNodeServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public ChildAssociationRef createNode(
        NodeRef parentRef,
        QName assocTypeQName,
        QName assocQName,
        QName nodeTypeQName,
        Map<QName, Serializable> properties)
{
    // The node(s) involved may not be pending deletion
    checkPendingDelete(parentRef);
    
    ParameterCheck.mandatory("parentRef", parentRef);
    ParameterCheck.mandatory("assocTypeQName", assocTypeQName);
    ParameterCheck.mandatory("assocQName", assocQName);
    ParameterCheck.mandatory("nodeTypeQName", nodeTypeQName);
    if(assocQName.getLocalName().length() > QName.MAX_LENGTH)
    {
        throw new IllegalArgumentException("Localname is too long. Length of " + 
             assocQName.getLocalName().length() + " exceeds the maximum of " + QName.MAX_LENGTH);
    }
    
    // Get the parent node
    Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(parentRef);
    StoreRef parentStoreRef = parentRef.getStoreRef();

    // null property map is allowed
    if (properties == null)
    {      
        properties = Collections.emptyMap();
    }
    
    // get an ID for the node
    String newUuid = generateGuid(properties);
    
    // Invoke policy behaviour
    invokeBeforeCreateNode(parentRef, assocTypeQName, assocQName, nodeTypeQName);
    
    // check the node type
    TypeDefinition nodeTypeDef = dictionaryService.getType(nodeTypeQName);
    if (nodeTypeDef == null)
    {
        throw new InvalidTypeException(nodeTypeQName);
    }
    
    // Ensure child uniqueness
    String newName = extractNameProperty(properties);
    
    // Get the thread's locale
    Locale locale = I18NUtil.getLocale();
    
    // create the node instance
    ChildAssocEntity assoc = nodeDAO.newNode(
            parentNodePair.getFirst(),
            assocTypeQName,
            assocQName,
            parentStoreRef,
            newUuid,
            nodeTypeQName,
            locale,
            newName,
            properties);
    ChildAssociationRef childAssocRef = assoc.getRef(qnameDAO);
    Pair<Long, NodeRef> childNodePair = assoc.getChildNode().getNodePair();
    
    addAspectsAndProperties(
                childNodePair,
                nodeTypeQName,
                null,
                Collections.<QName>emptySet(),
                Collections.<QName, Serializable>emptyMap(),
                Collections.<QName>emptySet(),
                properties,
                true,
                false);
    
    Map<QName, Serializable> propertiesAfter = nodeDAO.getNodeProperties(childNodePair.getFirst());
    
    // Propagate timestamps
    propagateTimeStamps(childAssocRef);

    // Invoke policy behaviour
    invokeOnCreateNode(childAssocRef);
    invokeOnCreateChildAssociation(childAssocRef, true);
    Map<QName, Serializable> propertiesBefore = PropertyMap.EMPTY_MAP;
    invokeOnUpdateProperties(
            childAssocRef.getChildRef(),
            propertiesBefore,
            propertiesAfter);
    
    // Ensure that the parent node has the required aspects
    addAspectsAndPropertiesAssoc(parentNodePair, assocTypeQName, null, null, null, null, false);
    
    // done
    return childAssocRef;
}
 
Example 18
Source File: AlfrescoCollatableTextFieldType.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public FieldComparator<String> newComparator(String fieldname, int numHits, int sortPos, boolean reversed)
{
    return new TextSortFieldComparator(numHits, fieldname, I18NUtil.getLocale());
}
 
Example 19
Source File: QueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Create a CMISQueryOptions instance with the default options other than the query and store ref. The query will be
 * run using the locale returned by I18NUtil.getLocale()
 * 
 * @param query -
 *            the query to run
 * @param storeRef -
 *            the store against which to run the query
 */
public QueryOptions(String query, StoreRef storeRef)
{
    this(query, storeRef, I18NUtil.getLocale());
}
 
Example 20
Source File: CMISQueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Create a CMISQueryOptions instance with the default options other than
 * the query and store ref. The query will be run using the locale returned
 * by I18NUtil.getLocale()
 * 
 * @param query
 *            - the query to run
 * @param storeRef
 *            - the store against which to run the query
 */
public CMISQueryOptions(String query, StoreRef storeRef)
{
    this(query, storeRef, I18NUtil.getLocale());
}