Example usage for java.util Locale equals

List of usage examples for java.util Locale equals

Introduction

In this page you can find the example usage for java.util Locale equals.

Prototype

@Override
public boolean equals(Object obj) 

Source Link

Document

Returns true if this Locale is equal to another object.

Usage

From source file:org.opencms.workplace.editors.CmsEditor.java

/**
 * Builds the html String for the element language selector.<p>
 *  /* w  w  w  .j a  va2  s  . c  o  m*/
 * @param attributes optional attributes for the &lt;select&gt; tag
 * @param resourceName the name of the resource to edit
 * @param selectedLocale the currently selected Locale
 * @return the html for the element language selectbox
 */
public String buildSelectElementLanguage(String attributes, String resourceName, Locale selectedLocale) {

    // get locale names based on properties and global settings
    List locales = OpenCms.getLocaleManager().getAvailableLocales(getCms(), resourceName);
    List options = new ArrayList(locales.size());
    List selectList = new ArrayList(locales.size());
    int currentIndex = -1;

    //get the locales already used in the resource
    List contentLocales = new ArrayList();
    try {

        CmsResource res = getCms().readResource(resourceName, CmsResourceFilter.IGNORE_EXPIRATION);
        String temporaryFilename = CmsWorkplace.getTemporaryFileName(resourceName);
        if (getCms().existsResource(temporaryFilename, CmsResourceFilter.IGNORE_EXPIRATION)) {
            res = getCms().readResource(temporaryFilename, CmsResourceFilter.IGNORE_EXPIRATION);
        }
        CmsFile file = getCms().readFile(res);
        CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file);
        contentLocales = xmlContent.getLocales();
    } catch (CmsException e) {
        // to nothing here in case the resource could not be opened
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_GET_LOCALES_1, resourceName), e);
        }
    }

    for (int counter = 0; counter < locales.size(); counter++) {
        // create the list of options and values
        Locale curLocale = (Locale) locales.get(counter);
        selectList.add(curLocale.toString());
        StringBuffer buf = new StringBuffer();
        buf.append(curLocale.getDisplayName(getLocale()));
        if (!contentLocales.contains(curLocale)) {
            buf.append(EMPTY_LOCALE);
        }
        options.add(buf.toString());
        if (curLocale.equals(selectedLocale)) {
            // set the selected index of the selector
            currentIndex = counter;
        }
    }

    if (currentIndex == -1) {
        // no matching element language found, use first element language in list
        if (selectList.size() > 0) {
            currentIndex = 0;
            setParamElementlanguage((String) selectList.get(0));
        }
    }

    return buildSelect(attributes, options, selectList, currentIndex, false);
}

From source file:org.openmrs16.Concept.java

/**
 * Returns the preferred description for a locale.
 * /* ww  w.  j av  a 2 s. co  m*/
 * @param locale the language and country in which the description is used
 * @param exact true/false to return only exact locale (no default locale)
 * @return the appropriate description, or null if not found
 * @should return match on locale exactly
 * @should return match on language only
 * @should not return match on language only if exact match exists
 * @should not return language only match for exact matches
 */
public ConceptDescription getDescription(Locale locale, boolean exact) {
    log.debug("Getting ConceptDescription for locale: " + locale);

    ConceptDescription foundDescription = null;

    if (locale == null)
        locale = LocaleUtility.getDefaultLocale();

    Locale desiredLocale = locale;

    ConceptDescription defaultDescription = null;
    for (Iterator<ConceptDescription> i = getDescriptions().iterator(); i.hasNext();) {
        ConceptDescription availableDescription = i.next();
        Locale availableLocale = availableDescription.getLocale();
        if (availableLocale.equals(desiredLocale)) {
            foundDescription = availableDescription;
            break; // skip out now because we found an exact locale match
        }
        if (!exact && LocaleUtility.areCompatible(availableLocale, desiredLocale))
            foundDescription = availableDescription;
        if (availableLocale.equals(LocaleUtility.getDefaultLocale()))
            defaultDescription = availableDescription;
    }

    if (foundDescription == null) {
        // no description with the given locale was found.
        // return null if exact match desired
        if (exact) {
            log.debug("No concept description found for concept id " + conceptId + " for locale "
                    + desiredLocale.toString());
        } else {
            // returning default description locale ("en") if exact match
            // not desired
            if (defaultDescription == null)
                log.debug("No concept description found for default locale for concept id " + conceptId);
            else {
                foundDescription = defaultDescription;
            }
        }
    }
    return foundDescription;
}

From source file:me.piebridge.bible.Bible.java

public void checkLocale() {
    Locale locale = Locale.getDefault();
    collator = Collator.getInstance(Locale.getDefault());
    if (!locale.equals(lastLocale)) {
        lastLocale = locale;/*from  ww w  .  ja  v  a2 s.c om*/
        setResources();
    }
}

From source file:org.wso2.carbon.utils.i18n.ResourceBundle.java

/**
 * Construct a new RB/*from w ww . j  a  v a 2  s  .  c  om*/
 *
 * @param caller The calling object. This is used to get the package name
 *               to further construct the basename as well as to get the proper ClassLoader
 * @param name   The name of the property file without the ".properties" extension
 * @param locale  The locale
 */
public ResourceBundle(Object caller, String name, Locale locale) {
    ClassLoader cl = null;

    if (caller != null) {

        Class c;
        if (caller instanceof Class) {
            c = (Class) caller;
        } else {
            c = caller.getClass();
        }

        // Get the appropriate class loader
        cl = c.getClassLoader();

        if (name.indexOf('/') == -1) {

            // Create the full basename only if not given
            String fullName = c.getName();

            int pos = fullName.lastIndexOf('.');
            if (pos > 0) {
                name = fullName.substring(0, pos + 1).replace('.', '/') + name;
            }
        }
    } else {
        // Try the shared default properties file...
        if (name.indexOf('/') == -1) {
            name = "org/apache/axis/default-resource";
        }
    }

    Locale defaultLocale = Locale.getDefault();

    // If the locale given is the same as the default locale, ignore it
    if (locale != null && locale.equals(defaultLocale)) {
        locale = null;
    }

    // Load the properties. If no property files exist then a
    // MissingResourceException will be thrown
    loadProperties(name, cl, locale, defaultLocale);
}

From source file:org.springframework.extensions.webscripts.AbstractWebScript.java

/**
 * <p>A locale based lookup sequence is build using the supplied {@link Locale} and (if it is 
 * different) the default {@link Locale}.
 * <ol><li>Lookup <{@code}descid><{@code}language_country_variant>.properties</li>
 * <li>Lookup <{@code}descid><{@code}language_country>.properties</li>
 * <li>Lookup <{@code}descid><{@code}language>.properties</li>
 * </ol>/*from ww w.  j av a2s.  c o m*/
 * The repeat but with the default {@link Locale}. Finally lookup <descid>.properties
 * </p>
 * @param path String
 * @param locale The requested {@link Locale}.
 * @return LinkedHashSet<String>
 */
@SuppressWarnings("static-access")
private LinkedHashSet<String> buildLocalePathList(final String path, final Locale locale) {
    final LinkedHashSet<String> pathSet = new LinkedHashSet<String>();

    // Add the paths for the current locale...
    pathSet.add(path + '_' + locale.toString() + DOT_PROPS);
    if (locale.getCountry().length() != 0) {
        pathSet.add(path + '_' + locale.getLanguage() + '_' + locale.getCountry() + DOT_PROPS);
    }
    pathSet.add(path + '_' + locale.getLanguage() + DOT_PROPS);

    if (locale.equals(Locale.getDefault())) {
        // We're already using the default Locale, so don't add it's paths again.
    } else {
        // Use the default locale to add some more possible paths...
        final Locale defLocale = locale.getDefault();
        pathSet.add(path + '_' + defLocale.toString() + DOT_PROPS);
        if (defLocale.getCountry().length() != 0) {
            pathSet.add(path + '_' + defLocale.getLanguage() + '_' + defLocale.getCountry() + DOT_PROPS);
        }
        pathSet.add(path + '_' + defLocale.getLanguage() + DOT_PROPS);
    }

    // Finally add a path with no locale information...
    pathSet.add(path + DOT_PROPS);
    return pathSet;
}

From source file:org.openmrs18.Concept.java

/**
 * Gets the synonyms in the given locale. Returns a list of names from the same language, or an
 * empty list if none found./*from   w  w w . j  av  a2s  . c  o m*/
 * 
 * @param locale
 * @return Collection of ConceptNames which are synonyms for the Concept in the given locale
 */
public Collection<ConceptName> getSynonyms(Locale locale) {

    Collection<ConceptName> syns = new Vector<ConceptName>();
    for (ConceptName possibleSynonymInLoc : getSynonyms()) {
        if (locale.equals(possibleSynonymInLoc.getLocale()))
            syns.add(possibleSynonymInLoc);
    }
    log.debug("returning: " + syns);
    return syns;
}

From source file:org.ofbiz.order.shoppingcart.ShoppingCartEvents.java

/** Update the cart's UserLogin object if it isn't already set. */
public static String keepCartUpdated(HttpServletRequest request, HttpServletResponse response) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    HttpSession session = request.getSession();
    ShoppingCart cart = getCartObject(request);

    // if we just logged in set the UL
    if (cart.getUserLogin() == null) {
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        if (userLogin != null) {
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logWarning(e, module);
            }/*from  ww  w.  ja v a2s.  c om*/
        }
    }

    // same for autoUserLogin
    if (cart.getAutoUserLogin() == null) {
        GenericValue autoUserLogin = (GenericValue) session.getAttribute("autoUserLogin");
        if (autoUserLogin != null) {
            if (cart.getUserLogin() == null) {
                try {
                    cart.setAutoUserLogin(autoUserLogin, dispatcher);
                } catch (CartItemModifyException e) {
                    Debug.logWarning(e, module);
                }
            } else {
                cart.setAutoUserLogin(autoUserLogin);
            }
        }
    }

    // update the locale
    Locale locale = UtilHttp.getLocale(request);
    if (cart.getLocale() == null || !locale.equals(cart.getLocale())) {
        cart.setLocale(locale);
    }

    return "success";
}

From source file:org.opencms.ade.contenteditor.CmsContentService.java

/**
 * Reads the content definition for the given resource and locale.<p>
 *
 * @param file the resource file//from  www.  j  a  va 2  s.c o m
 * @param content the XML content
 * @param entityId the entity id
 * @param locale the content locale
 * @param newLocale if the locale content should be created as new
 * @param mainLocale the main language to copy in case the element language node does not exist yet
 * @param editedLocaleEntity the edited locale entity
 *
 * @return the content definition
 *
 * @throws CmsException if something goes wrong
 */
private CmsContentDefinition readContentDefinition(CmsFile file, CmsXmlContent content, String entityId,
        Locale locale, boolean newLocale, Locale mainLocale, CmsEntity editedLocaleEntity) throws CmsException {

    long timer = 0;
    if (LOG.isDebugEnabled()) {
        timer = System.currentTimeMillis();
    }
    CmsObject cms = getCmsObject();
    List<Locale> availableLocalesList = OpenCms.getLocaleManager().getAvailableLocales(cms, file);
    if (!availableLocalesList.contains(locale)) {
        availableLocalesList.retainAll(content.getLocales());
        List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(cms, file);
        Locale replacementLocale = OpenCms.getLocaleManager().getBestMatchingLocale(locale, defaultLocales,
                availableLocalesList);
        LOG.info("Can't edit locale " + locale + " of file " + file.getRootPath()
                + " because it is not configured as available locale. Using locale " + replacementLocale
                + " instead.");
        locale = replacementLocale;
        entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
    }

    if (CmsStringUtil.isEmptyOrWhitespaceOnly(entityId)) {
        entityId = CmsContentDefinition.uuidToEntityId(file.getStructureId(), locale.toString());
    }
    boolean performedAutoCorrection = checkAutoCorrection(cms, content);
    if (performedAutoCorrection) {
        content.initDocument();
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_TAKE_UNMARSHALING_TIME_1,
                "" + (System.currentTimeMillis() - timer)));
    }
    CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, locale);
    if (LOG.isDebugEnabled()) {
        timer = System.currentTimeMillis();
    }
    visitor.visitTypes(content.getContentDefinition(), getWorkplaceLocale(cms));
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_TAKE_VISITING_TYPES_TIME_1,
                "" + (System.currentTimeMillis() - timer)));
    }
    CmsEntity entity = null;
    Map<String, String> syncValues = new HashMap<String, String>();
    Collection<String> skipPaths = new HashSet<String>();
    evaluateSyncLocaleValues(content, syncValues, skipPaths);
    if (content.hasLocale(locale) && newLocale) {
        // a new locale is requested, so remove the present one
        content.removeLocale(locale);
    }
    if (!content.hasLocale(locale)) {
        if ((mainLocale != null) && content.hasLocale(mainLocale)) {
            content.copyLocale(mainLocale, locale);
        } else {
            content.addLocale(cms, locale);
        }
        // sync the locale values
        if (!visitor.getLocaleSynchronizations().isEmpty() && (content.getLocales().size() > 1)) {
            for (Locale contentLocale : content.getLocales()) {
                if (!contentLocale.equals(locale)) {
                    content.synchronizeLocaleIndependentValues(cms, skipPaths, contentLocale);
                }
            }
        }
    }
    Element element = content.getLocaleNode(locale);
    if (LOG.isDebugEnabled()) {
        timer = System.currentTimeMillis();
    }
    entity = readEntity(content, element, locale, entityId, "", getTypeUri(content.getContentDefinition()),
            visitor, false, editedLocaleEntity);

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_TAKE_READING_ENTITY_TIME_1,
                "" + (System.currentTimeMillis() - timer)));
    }
    List<String> contentLocales = new ArrayList<String>();
    for (Locale contentLocale : content.getLocales()) {
        contentLocales.add(contentLocale.toString());
    }
    Locale workplaceLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
    TreeMap<String, String> availableLocales = new TreeMap<String, String>();
    for (Locale availableLocale : OpenCms.getLocaleManager().getAvailableLocales(cms, file)) {
        availableLocales.put(availableLocale.toString(), availableLocale.getDisplayName(workplaceLocale));
    }
    String title = cms.readPropertyObject(file, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
    try {
        CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(cms, file.getStructureId(), locale);
        title = searchResult.getTitle();
    } catch (CmsException e) {
        LOG.warn(e.getLocalizedMessage(), e);
    }
    String typeName = OpenCms.getResourceManager().getResourceType(file.getTypeId()).getTypeName();
    boolean autoUnlock = OpenCms.getWorkplaceManager().shouldAcaciaUnlock();
    Map<String, CmsEntity> entities = new HashMap<String, CmsEntity>();
    entities.put(entityId, entity);

    return new CmsContentDefinition(entityId, entities, visitor.getAttributeConfigurations(),
            visitor.getWidgetConfigurations(), visitor.getComplexWidgetData(), visitor.getTypes(),
            visitor.getTabInfos(), locale.toString(), contentLocales, availableLocales,
            visitor.getLocaleSynchronizations(), syncValues, skipPaths, title, cms.getSitePath(file), typeName,
            performedAutoCorrection, autoUnlock, getChangeHandlerScopes(content.getContentDefinition()));
}

From source file:org.opencms.ade.contenteditor.CmsContentService.java

/**
 * Synchronizes the locale independent fields.<p>
 *
 * @param file the content file//ww  w .j a va  2s  . co m
 * @param content the XML content
 * @param skipPaths the paths to skip during locale synchronization
 * @param entities the edited entities
 * @param lastEdited the last edited locale
 *
 * @throws CmsXmlException if something goes wrong
 */
protected void synchronizeLocaleIndependentFields(CmsFile file, CmsXmlContent content,
        Collection<String> skipPaths, Collection<CmsEntity> entities, Locale lastEdited)
        throws CmsXmlException {

    CmsEntity lastEditedEntity = null;
    for (CmsEntity entity : entities) {
        if (lastEdited
                .equals(CmsLocaleManager.getLocale(CmsContentDefinition.getLocaleFromId(entity.getId())))) {
            lastEditedEntity = entity;
        } else {
            synchronizeLocaleIndependentForEntity(file, content, skipPaths, entity);
        }
    }
    if (lastEditedEntity != null) {
        // prepare the last edited last, to sync locale independent fields
        synchronizeLocaleIndependentForEntity(file, content, skipPaths, lastEditedEntity);
    }
}

From source file:org.openmrs.Concept.java

/**
 * Gets the explicitly specified short name for a locale.
 * /*from  w  ww .ja v  a 2 s  .co m*/
 * @param locale locale for which to find a short name
 * @return the short name, or null if none has been explicitly set
 */
public ConceptName getShortNameInLocale(Locale locale) {
    ConceptName bestMatch = null;
    if (locale != null && getShortNames().size() > 0) {
        for (ConceptName shortName : getShortNames()) {
            Locale nameLocale = shortName.getLocale();
            if (nameLocale.equals(locale)) {
                return shortName;
            }
            // test for partially locale match - any language matches takes precedence over country matches.
            if (OpenmrsUtil.nullSafeEquals(locale.getLanguage(), nameLocale.getLanguage())) {
                bestMatch = shortName;
            } else if (bestMatch == null && StringUtils.isNotBlank(locale.getCountry())
                    && locale.getCountry().equals(nameLocale.getCountry())) {
                bestMatch = shortName;
            }
        }
    }
    return bestMatch;
}