Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:org.hyperic.hq.ui.taglib.MetricDisplayTag.java

public int doEndTag() throws JspException {
    Locale userLocale = TagUtils.getInstance().getUserLocale(pageContext, locale);

    if (unitIsSet) {
        setUnitVal(getUnit());//w  w  w .ja  va 2 s.co  m
    }

    if (defaultKeyIsSet) {
        setDefaultKeyVal(getDefaultKey());
    }

    // if the metric value is empty, converting to a Double will
    // give a value of 0.0. this makes it impossible for us to
    // distinguish further down the line whether the metric was
    // actually collected with a value of 0.0 or whether it was
    // not collected at all. therefore, we'll let metricVal be
    // null if the metric was not collected, and we'll check for
    // null later when handling the not-avail case.
    // PR: 7588
    String mval = getMetric();

    if (mval != null && !mval.equals("")) {
        setMetricVal(new Double(mval));
    }

    StringBuffer sb = new StringBuffer("<span");

    if (spanIsSet && getSpan().length() > 0) {
        setSpanVal(getSpan());
        sb.append(" class=\"");
        sb.append(getSpanVal());
        sb.append("\"");
    }

    sb.append(">");

    if (getMetricVal() == null || Double.isNaN(getMetricVal().doubleValue()) && defaultKeyIsSet) {
        sb.append(
                TagUtils.getInstance().message(pageContext, bundle, userLocale.toString(), getDefaultKeyVal()));
    }
    // XXXX remove duplication with the metric decorator
    // and the UnitsConvert/UnitsFormat stuff
    else if (getUnitVal().equals("ms")) {
        NumberFormat f = NumberFormat.getNumberInstance(userLocale);

        f.setMinimumFractionDigits(3);
        f.setMaximumFractionDigits(3);

        String formatted = f.format(getMetricVal().doubleValue() / 1000);
        String[] args = new String[] { formatted };

        sb.append(TagUtils.getInstance().message(pageContext, bundle, userLocale.toString(),
                "metric.tag.units.s.arg", args));
    } else {
        FormattedNumber f = UnitsConvert.convert(getMetricVal().doubleValue(), getUnitVal(), userLocale);

        sb.append(f.getValue());

        if (f.getTag() != null && f.getTag().length() > 0) {
            sb.append(" ").append(f.getTag());
        }
    }

    sb.append("</span>");

    try {
        pageContext.getOut().print(sb.toString());
    } catch (IOException e) {
        log.debug("could not write output: ", e);

        throw new JspException("Could not access metrics tag");
    }

    release();

    return EVAL_PAGE;
}

From source file:org.artificer.client.ArtificerAtomApiClient.java

/**
 * Creates the client executor that will be used by RESTEasy when
 * making the request.//from  w w w . j  a v a 2 s . c o  m
 */
private ClientExecutor createClientExecutor() {
    // TODO I think the http client is thread safe - so let's try to create just one of these
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            Locale l = getLocale();
            if (l == null) {
                l = Locale.getDefault();
            }
            request.addHeader("Accept-Language", l.toString());
        }
    });
    if (this.authProvider != null) {
        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                authProvider.provideAuthentication(request);
            }
        });
    }
    return new ApacheHttpClient4Executor(httpClient);
}

From source file:com.sun.faces.application.ViewHandlerImpl.java

public UIViewRoot createView(FacesContext context, String viewId) {
    if (context == null) {
        String message = Util.getExceptionMessageString(Util.NULL_PARAMETERS_ERROR_MESSAGE_ID);
        message = message + "context " + context;
        throw new NullPointerException(message);
    }/*from   ww  w.jav  a  2  s  .c  o  m*/
    Locale locale = null;
    String renderKitId = null;

    // use the locale from the previous view if is was one which will be
    // the case if this is called from NavigationHandler. There wouldn't be 
    // one for the initial case.
    if (context.getViewRoot() != null) {
        locale = context.getViewRoot().getLocale();
        renderKitId = context.getViewRoot().getRenderKitId();
    }
    UIViewRoot result = new UIViewRoot();
    result.setViewId(viewId);
    if (log.isDebugEnabled()) {
        log.debug("Created new view for " + viewId);
    }
    // PENDING(): not sure if we should set the RenderKitId here.
    // The UIViewRoot ctor sets the renderKitId to the default
    // one.
    // if there was no locale from the previous view, calculate the locale 
    // for this view.
    if (locale == null) {
        locale = context.getApplication().getViewHandler().calculateLocale(context);
        if (log.isDebugEnabled()) {
            log.debug("Locale for this view as determined by calculateLocale " + locale.toString());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Using locale from previous view " + locale.toString());
        }
    }

    if (renderKitId == null) {
        renderKitId = context.getApplication().getViewHandler().calculateRenderKitId(context);
        if (log.isDebugEnabled()) {
            log.debug("RenderKitId for this view as determined by calculateRenderKitId " + renderKitId);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Using renderKitId from previous view " + renderKitId);
        }
    }

    result.setLocale(locale);
    result.setRenderKitId(renderKitId);

    return result;
}

From source file:org.atomserver.core.dbstore.DBBasedAtomCollection.java

protected long getEntries(Abdera abdera, IRI iri, FeedTarget feedTarget, Date updatedMin, Date updatedMax,
        Feed feed) throws AtomServerException {

    if (getEntriesMonitor() != null) {
        getEntriesMonitor().updateNumberOfGetEntriesRequests(1);
    }/*from   w w  w.j  a  v  a 2s.  c  o  m*/
    String collection = feedTarget.getCollection();
    String workspace = feedTarget.getWorkspace();

    int totalEntries = 0;
    if (isProducingTotalResultsFeedElement()) {
        // SELECT COUNT BY LastModified
        totalEntries = getEntriesDAO().getCountByLastModified(feedTarget, updatedMin);

        if (totalEntries <= 0) {
            if (getEntriesMonitor() != null) {
                getEntriesMonitor().updateNumberOfGetEntriesRequestsReturningNone(1);
            }
            return 0L;
        }
    }

    long startIndex = feedTarget.getStartIndexParam();
    long endIndex = feedTarget.getEndIndexParam();
    boolean noLatency = feedTarget.getNoLatency();

    if (endIndex != -1 && endIndex < startIndex) {
        String msg = "endIndex parameter (" + endIndex + ") is less than the startIndex (" + startIndex + ")";
        log.error(msg);
        throw new BadRequestException(msg);
    }

    Locale locale = feedTarget.getLocaleParam();
    EntryType entryType = (feedTarget.getEntryTypeParam() != null) ? feedTarget.getEntryTypeParam()
            : EntryType.link;

    int pageSize = calculatePageSize(feedTarget, entryType);
    if (log.isDebugEnabled()) {
        log.debug(
                "getEntries:: startIndex= " + startIndex + " endIndex= " + endIndex + " pageSize " + pageSize);
    }

    Collection<BooleanExpression<AtomCategory>> categoryQuery = feedTarget.getCategoriesQuery();

    // SELECT Entries BY Page and Locale
    List<EntryMetaData> sortedList = getEntriesDAO().selectFeedPage(updatedMin, updatedMax, startIndex,
            endIndex, pageSize + 1 /* ask for 1 more than pageSize, to detect the end of the feed */, noLatency,
            locale == null ? null : locale.toString(), feedTarget, categoryQuery);

    int numEntries = sortedList.size();
    if (numEntries <= 0) {
        if (getEntriesMonitor() != null) {
            getEntriesMonitor().updateNumberOfGetEntriesRequestsReturningNone(1);
        }
        return 0L;
    }

    for (EntryMetaData entryMetaData : sortedList) {
        // we are looking for the unthinkable here -- if these if blocks ever trigger, that
        // means that SQL Server returned us a row with an UpdateTimestamp less than or equal
        // to the page delimiter that we requested!

        if (entryMetaData.getUpdateTimestamp() <= startIndex) {
            String message = MessageFormat.format("SQL-SERVER-ERROR!  (TIMESTAMP)  We requested the page "
                    + "starting at {0}, " + "and the response to the query contained an entry at {1}!\n"
                    + "** the full offending entry was: {2}\n" + "** the list of all entries was: \n *{3}",
                    startIndex, entryMetaData.getUpdateTimestamp(), entryMetaData,
                    StringUtils.join(sortedList, "\n *"));
            log.error(message);
            throw new AtomServerException(message);
        }

    }

    // Load the Categories to the EntryMetaData in the Feed 
    //   NOTE: this method calls the database!!!
    //   TODO: we could load these in the same query as above, except for HSQL limitations.
    if (isProducingEntryCategoriesFeedElement()) {
        loadCategoriesToEntryMetaData(sortedList, workspace, collection);
    }

    // Add elements to the Feed document
    return createFeedElements(feed, abdera, iri, feedTarget, entryType, sortedList, workspace, collection,
            locale, noLatency, numEntries, (numEntries <= pageSize), pageSize, startIndex, totalEntries);
}

From source file:com.liferay.portlet.journal.util.JournalConverterImpl.java

protected void updateJournalXSDDynamicElement(Element element) {
    Locale defaultLocale = LocaleUtil.getSiteDefault();

    String name = element.attributeValue("name");
    String type = element.attributeValue("type");

    Element metadataElement = element.element("meta-data");

    if (metadataElement == null) {
        metadataElement = element.addElement("meta-data");
    }/*  w w  w  .j  av  a2  s  .c o m*/

    if (type.equals("multi-list")) {
        element.addAttribute("multiple", "true");
    } else if (type.equals("selection_break")) {
        Element parentElement = element.getParent();

        parentElement.remove(element);

        return;
    } else {
        Element parentElement = element.getParent();

        String parentType = parentElement.attributeValue("type");

        if ((parentType != null) && parentType.equals("select")) {
            metadataElement.addAttribute("locale", defaultLocale.toString());

            addMetadataEntry(metadataElement, "label", name);

            element.addAttribute("name", "option" + StringUtil.randomId());
            element.addAttribute("type", "option");
            element.addAttribute("value", name);

            return;
        }
    }

    String indexType = StringPool.BLANK;

    Attribute indexTypeAttribute = element.attribute("index-type");

    if (indexTypeAttribute != null) {
        indexType = indexTypeAttribute.getValue();

        element.remove(indexTypeAttribute);
    }

    element.remove(element.attribute("type"));

    String dataType = _ddmDataTypes.get(type);

    if (dataType == null) {
        dataType = "string";
    }

    element.addAttribute("dataType", dataType);
    element.addAttribute("indexType", indexType);

    String required = "false";

    Element requiredElement = fetchMetadataEntry(metadataElement, "name", "required");

    if (requiredElement != null) {
        required = requiredElement.getText();
    }

    element.addAttribute("required", required);

    element.addAttribute("showLabel", "true");

    String newType = _journalTypesToDDMTypes.get(type);

    if (newType == null) {
        newType = type;
    }

    element.addAttribute("type", newType);

    if (newType.startsWith("ddm")) {
        element.addAttribute("fieldNamespace", "ddm");
    }

    metadataElement.addAttribute("locale", defaultLocale.toString());

    List<Element> entryElements = metadataElement.elements();

    if (entryElements.isEmpty()) {
        addMetadataEntry(metadataElement, "label", name);
    } else {
        for (Element entryElement : entryElements) {
            String oldEntryName = entryElement.attributeValue("name");

            String newEntryName = _ddmMetadataAttributes.get(oldEntryName);

            if (newEntryName == null) {
                metadataElement.remove(entryElement);
            } else {
                entryElement.addAttribute("name", newEntryName);
            }
        }
    }

    if (newType.equals("ddm-date") || newType.equals("ddm-decimal") || newType.equals("ddm-integer")
            || newType.equals("ddm-link-to-page") || newType.equals("ddm-number")
            || newType.equals("ddm-text-html") || newType.equals("text") || newType.equals("textarea")) {

        element.addAttribute("width", "25");
    } else if (newType.equals("wcm-image")) {
        element.addAttribute("fieldNamespace", "wcm");
        element.addAttribute("readOnly", "false");
    }

    List<Element> dynamicElementElements = element.elements("dynamic-element");

    for (Element dynamicElementElement : dynamicElementElements) {
        updateJournalXSDDynamicElement(dynamicElementElement);
    }
}

From source file:com.freedomotic.jfrontend.MainWindow.java

/**
 * /*  w  ww . j a  v a 2s . co m*/
 * @param evt 
 */
private void mnuLanguageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuLanguageActionPerformed
    //JDK 1,7 version: JComboBox<i18n.ComboLanguage> combo = new JComboBox<i18n.ComboLanguage>(I18n.getAvailableLocales());
    //JDK 1.6 version: next line
    Vector<ComboLanguage> languages = new Vector<ComboLanguage>();
    for (Locale loc : i18n.getAvailableLocales()) {
        languages.add(new ComboLanguage(
                loc.getDisplayCountry(i18n.getDefaultLocale()) + " - " + loc.getDisplayLanguage(loc),
                loc.toString(), loc));
    }
    Collections.sort(languages);
    languages.add(new ComboLanguage("Automatic", "auto", Locale.ENGLISH));

    JComboBox combo = new JComboBox(languages);

    for (ComboLanguage cmb : languages) {
        if (cmb.getValue().equals(i18n.getDefaultLocale())) {
            combo.setSelectedItem(cmb);
            break;
        }
    }
    JLabel lbl = new JLabel(i18n.msg("language"));
    int result = JOptionPane.showConfirmDialog(this, new Object[] { lbl, combo }, i18n.msg("language"),
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        ComboLanguage selected = (ComboLanguage) combo.getSelectedItem();
        i18n.setDefaultLocale(selected.getValue());
        updateStrings();
    }
}

From source file:org.jahia.services.sites.JahiaSitesBaseService.java

public JahiaSite addSite(JahiaUser currentUser, String title, String serverName, String siteKey, String descr,
        Locale selectedLocale, String selectTmplSet, final String[] modulesToDeploy, String firstImport,
        File fileImport, String fileImportName, Boolean asAJob, Boolean doImportServerPermissions,
        String originatingJahiaRelease, String legacyMappingFilePath, String legacyDefinitionsFilePath)
        throws JahiaException, IOException {
    JahiaSite site = new JahiaSite(-1, title, serverName, siteKey, descr, null, "/sites/" + siteKey);

    if (selectTmplSet != null) {
        site.setTemplatePackageName(selectTmplSet);
    }//ww w . j av  a 2  s.  c om
    // create site language
    site.setDefaultLanguage(selectedLocale.toString());
    site.setLanguages(new LinkedHashSet<String>(Arrays.asList(selectedLocale.toString())));
    site.setMandatoryLanguages(site.getLanguages());
    site.setMixLanguagesActive(false);
    // check there is no site with same server name before adding
    boolean importingSystemSite = false;

    try {

        if (getSiteByKey(site.getSiteKey()) == null) {
            final String siteKey1 = site.getSiteKey();
            final String templatePackage = site.getTemplatePackageName();
            site.setInstalledModules(new ArrayList<String>(Collections.singleton(templatePackage)));

            final Set<String> languages = site.getLanguages();
            final Set<String> inactiveLiveLanguages = site.getInactiveLiveLanguages();
            final Set<String> inactiveLanguages = site.getInactiveLanguages();
            final Set<String> mandatoryLanguages = site.getMandatoryLanguages();

            int id = 1;
            List<JahiaSite> sites = getSitesList();
            for (JahiaSite jahiaSite : sites) {
                if (id <= jahiaSite.getID()) {
                    id = jahiaSite.getID() + 1;
                }
            }
            final int siteId = id;
            site.setID(id);
            final JahiaSite finalSite = site;
            JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    Query q = session.getWorkspace().getQueryManager()
                            .createQuery("SELECT * FROM [jnt:virtualsitesFolder]", Query.JCR_SQL2);
                    QueryResult qr = q.execute();
                    NodeIterator ni = qr.getNodes();

                    while (ni.hasNext()) {
                        JCRNodeWrapper sitesFolder = (JCRNodeWrapper) ni.nextNode();
                        String options = "";
                        if (sitesFolder.hasProperty("j:virtualsitesFolderConfig")) {
                            options = sitesFolder.getProperty("j:virtualsitesFolderConfig").getString();
                        }

                        JCRNodeWrapper f = JCRContentUtils.getPathFolder(sitesFolder, siteKey1, options,
                                "jnt:virtualsitesFolder");
                        try {
                            f.getNode(siteKey1);
                        } catch (PathNotFoundException e) {
                            JCRNodeWrapper siteNode = f.addNode(siteKey1, "jnt:virtualsite");

                            if (sitesFolder.hasProperty("j:virtualsitesFolderSkeleton")) {
                                String skeletons = sitesFolder.getProperty("j:virtualsitesFolderSkeleton")
                                        .getString();
                                try {
                                    JCRContentUtils.importSkeletons(skeletons, f.getPath() + "/" + siteKey1,
                                            session);
                                } catch (Exception importEx) {
                                    logger.error("Unable to import data using site skeleton " + skeletons,
                                            importEx);
                                }
                            }

                            siteNode.setProperty("j:title", finalSite.getTitle());
                            siteNode.setProperty("j:description", finalSite.getDescr());
                            siteNode.setProperty("j:serverName", finalSite.getServerName());
                            siteNode.setProperty("j:siteId", siteId);
                            siteNode.setProperty(SitesSettings.DEFAULT_LANGUAGE,
                                    finalSite.getDefaultLanguage());
                            siteNode.setProperty(SitesSettings.MIX_LANGUAGES_ACTIVE,
                                    finalSite.isMixLanguagesActive());
                            siteNode.setProperty(SitesSettings.LANGUAGES,
                                    languages.toArray(new String[languages.size()]));
                            siteNode.setProperty(SitesSettings.INACTIVE_LIVE_LANGUAGES,
                                    inactiveLiveLanguages.toArray(new String[inactiveLiveLanguages.size()]));
                            siteNode.setProperty(SitesSettings.INACTIVE_LANGUAGES,
                                    inactiveLanguages.toArray(new String[inactiveLanguages.size()]));
                            siteNode.setProperty(SitesSettings.MANDATORY_LANGUAGES,
                                    mandatoryLanguages.toArray(new String[mandatoryLanguages.size()]));
                            siteNode.setProperty("j:templatesSet", templatePackage);
                            siteNode.setProperty("j:installedModules",
                                    new Value[] { session.getValueFactory().createValue(templatePackage) });

                            Set<String> modules = new LinkedHashSet<String>(
                                    2 + (modulesToDeploy != null ? modulesToDeploy.length : 0));
                            modules.add("default");
                            modules.add(templatePackage);
                            if (modulesToDeploy != null) {
                                modules.addAll(Arrays.asList(modulesToDeploy));
                            }
                            JahiaTemplateManagerService templateService = ServicesRegistry.getInstance()
                                    .getJahiaTemplateManagerService();
                            for (String module : modules) {
                                String source = "/templateSets/" + module;
                                String target = "/sites/" + siteKey1;
                                try {
                                    logger.info("Deploying module {} to {}", source, target);
                                    templateService.deployModule(source, target, session);
                                } catch (RepositoryException re) {
                                    logger.error("Unable to deploy module " + source + " to " + target
                                            + ". Cause: " + re.getMessage(), re);
                                }
                            }
                        }
                    }

                    session.save();

                    return null;
                }
            });

            if (site.getID() == -1) {
                return null;
            }

            addToCache(site);
        } else if (siteKey.equals(SYSTEM_SITE_KEY)) {
            site = getSiteByKey(SYSTEM_SITE_KEY);
            importingSystemSite = true;
        } else {
            throw new IOException("site already exists");
        }

        JCRSessionWrapper session = sessionFactory.getCurrentUserSession(null, selectedLocale);

        // continue if the site is added correctly...
        if (site.getID() != -1) {
            if (!site.isDefault() && !site.getSiteKey().equals(SYSTEM_SITE_KEY) && getNbSites() == 2) {
                setDefaultSite(site);
            }
            if (!importingSystemSite) {
                JahiaGroupManagerService jgms = ServicesRegistry.getInstance().getJahiaGroupManagerService();

                updateSite(site);

                site.setMixLanguagesActive(false);

                // create default groups...
                JahiaGroup usersGroup = jgms.lookupGroup(0, JahiaGroupManagerService.USERS_GROUPNAME);
                if (usersGroup == null) {
                    usersGroup = jgms.createGroup(0, JahiaGroupManagerService.USERS_GROUPNAME, null, false);
                }

                JahiaGroup guestGroup = jgms.lookupGroup(0, JahiaGroupManagerService.GUEST_GROUPNAME);
                if (guestGroup == null) {
                    guestGroup = jgms.createGroup(0, JahiaGroupManagerService.GUEST_GROUPNAME, null, false);
                }

                JahiaGroup privGroup = jgms.lookupGroup(0, JahiaGroupManagerService.PRIVILEGED_GROUPNAME);
                if (privGroup == null) {
                    privGroup = jgms.createGroup(0, JahiaGroupManagerService.PRIVILEGED_GROUPNAME, null, true);
                }

                JahiaGroup adminGroup = jgms.lookupGroup(site.getID(),
                        JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME);
                if (adminGroup == null) {
                    adminGroup = jgms.createGroup(site.getID(),
                            JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME, null, false);
                }

                // attach superadmin user (current) to administrators group...
                adminGroup.addMember(currentUser);

                if (!siteKey.equals(SYSTEM_SITE_KEY)) {
                    JahiaGroup sitePrivGroup = jgms.lookupGroup(site.getID(),
                            JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME);
                    if (sitePrivGroup == null) {
                        sitePrivGroup = jgms.createGroup(site.getID(),
                                JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, null, false);
                    }
                    // atach site privileged group to server privileged
                    privGroup.addMember(sitePrivGroup);
                }

                JCRNodeWrapper siteNode = getSite(site.getID(), session);
                if (!siteKey.equals(SYSTEM_SITE_KEY)) {
                    siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME,
                            Collections.singleton("privileged"));
                    siteNode.denyRoles("g:" + JahiaGroupManagerService.PRIVILEGED_GROUPNAME,
                            Collections.singleton("privileged"));
                }
                siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME,
                        Collections.singleton("site-administrator"));
                session.save();
            }
            File initialZip = null;
            if ("fileImport".equals(firstImport)) {
                initialZip = fileImport;
            }

            // create the default homepage...
            List<Locale> locales = new ArrayList<Locale>();
            locales.add(selectedLocale);

            if ("importRepositoryFile".equals(firstImport)
                    || (initialZip != null && initialZip.exists() && !"noImport".equals(firstImport))) {
                try {
                    Map<Object, Object> importInfos = new HashMap<Object, Object>();
                    importInfos.put("originatingJahiaRelease", originatingJahiaRelease);
                    ServicesRegistry.getInstance().getImportExportService().importSiteZip(initialZip, site,
                            importInfos, legacyMappingFilePath, legacyDefinitionsFilePath);
                } catch (RepositoryException e) {
                    logger.warn("Error importing site ZIP", e);
                }
            } else {
                try {
                    JCRNodeWrapper nodeWrapper = session.getNode("/sites/" + site.getSiteKey());
                    if (!nodeWrapper.hasNode("home")) {
                        session.checkout(nodeWrapper);
                        JCRNodeWrapper page = nodeWrapper.addNode("home", "jnt:page");
                        page.setProperty("jcr:title", "Welcome to " + site.getServerName());
                        page.setProperty("j:isHomePage", true);
                        session.save();
                    }
                    JCRNodeWrapper home = nodeWrapper.getNode("home");
                    if (!home.hasProperty("jcr:title")) {
                        home.setProperty("jcr:title", "Welcome to " + site.getServerName());
                        session.save();
                    }
                } catch (RepositoryException e) {
                    logger.warn("Error adding home node", e);
                }
            }

            JCRNodeWrapper nodeWrapper = session.getNode("/sites/" + site.getSiteKey());
            if (nodeWrapper.hasNode("templates")) {
                JCRPublicationService.getInstance().publishByMainId(
                        nodeWrapper.getNode("templates").getIdentifier(), "default", "live", null, true, null);
            }

            cacheService.getCache("JCRGroupCache").flush();

            logger.debug("Site updated with Home Page");
        } else {
            removeSite(site); // remove site because the process generate error(s)...
            return null;
        }
    } catch (RepositoryException e) {
        logger.warn("Error adding home node", e);
    }

    return site;
}

From source file:org.apache.myfaces.custom.calendar.HtmlCalendarRenderer.java

public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException {
    RendererUtils.checkParamValidity(facesContext, component, HtmlInputCalendar.class);

    HtmlInputCalendar inputCalendar = (HtmlInputCalendar) component;

    Locale currentLocale = facesContext.getViewRoot().getLocale();
    Map<String, List<ClientBehavior>> behaviors = inputCalendar.getClientBehaviors();
    if (!behaviors.isEmpty()) {
        ResourceUtils.renderDefaultJsfJsInlineIfNecessary(facesContext, facesContext.getResponseWriter());
    }//from  w  ww  .  j  av  a2  s.  c o m

    log.debug("current locale:" + currentLocale.toString());

    String textValue;

    Converter converter = inputCalendar.getConverter();
    Object submittedValue = inputCalendar.getSubmittedValue();

    Date value;

    if (submittedValue != null) {
        //Don't need to convert anything, the textValue is the same as the submittedValue
        textValue = (String) submittedValue;

        if (textValue == null || textValue.trim().length() == 0
                || textValue.equals(getHelperString(inputCalendar))) {
            value = null;
        } else {
            try {
                String formatStr = CalendarDateTimeConverter.createJSPopupFormat(facesContext,
                        inputCalendar.getPopupDateFormat());
                Calendar timeKeeper = Calendar.getInstance(currentLocale);
                int firstDayOfWeek = timeKeeper.getFirstDayOfWeek() - 1;
                org.apache.myfaces.dateformat.DateFormatSymbols symbols = new org.apache.myfaces.dateformat.DateFormatSymbols(
                        currentLocale);

                SimpleDateFormatter dateFormat = new SimpleDateFormatter(formatStr, symbols, firstDayOfWeek);
                value = dateFormat.parse(textValue);
            } catch (IllegalArgumentException illegalArgumentException) {
                value = null;
            }
        }
    } else {
        if (converter == null) {
            CalendarDateTimeConverter defaultConverter = new CalendarDateTimeConverter();

            value = (Date) getDateBusinessConverter(inputCalendar).getDateValue(facesContext, component,
                    inputCalendar.getValue());

            textValue = defaultConverter.getAsString(facesContext, inputCalendar, value);
        } else {
            Object componentValue = null;
            boolean usedComponentValue = false;
            //Use converter to retrieve the value.
            if (converter instanceof DateConverter) {
                value = ((DateConverter) converter).getAsDate(facesContext, inputCalendar);
            } else {
                componentValue = inputCalendar.getValue();
                if (componentValue instanceof Date) {
                    value = (Date) componentValue;
                } else {
                    usedComponentValue = true;
                    value = null;
                }
            }
            textValue = converter.getAsString(facesContext, inputCalendar,
                    usedComponentValue ? componentValue : value);
        }
    }
    /*        
    try
    {
    // value = RendererUtils.getDateValue(inputCalendar);
            
    Converter converter = getConverter(inputCalendar);
    if (converter instanceof DateConverter)
    {
        value = ((DateConverter) converter).getAsDate(facesContext, component);
    }
    else
    {
        //value = RendererUtils.getDateValue(inputCalendar);
        Object objectValue = RendererUtils.getObjectValue(component);
        if (objectValue == null || objectValue instanceof Date)
        {
            value = (Date) objectValue;
        }
        else
        {
            //Use Converter.getAsString and convert to date using 
            String stringValue = converter.getAsString(facesContext, component, objectValue);
            
            if(stringValue ==null || stringValue.trim().length()==0 ||stringValue.equals(getHelperString(inputCalendar)))
            {
                value = null;
            }
            else
            {
                String formatStr = CalendarDateTimeConverter.createJSPopupFormat(facesContext, inputCalendar.getPopupDateFormat());
                Calendar timeKeeper = Calendar.getInstance(currentLocale);
                int firstDayOfWeek = timeKeeper.getFirstDayOfWeek() - 1;
                org.apache.myfaces.dateformat.DateFormatSymbols symbols = new org.apache.myfaces.dateformat.DateFormatSymbols(currentLocale);
            
                SimpleDateFormatter dateFormat = new SimpleDateFormatter(formatStr, symbols, firstDayOfWeek);
                value = dateFormat.parse(stringValue);
            }
        }
    }
    }
    catch (IllegalArgumentException illegalArgumentException)
    {
    value = null;
    }
    */

    Calendar timeKeeper = Calendar.getInstance(currentLocale);
    timeKeeper.setTime(value != null ? value : new Date());

    DateFormatSymbols symbols = new DateFormatSymbols(currentLocale);

    if (inputCalendar.isRenderAsPopup()) {
        renderPopup(facesContext, inputCalendar, textValue, timeKeeper, symbols);
    } else {
        renderInline(facesContext, inputCalendar, timeKeeper, symbols);
    }

    component.getChildren().removeAll(component.getChildren());
}

From source file:com.yaodu.framework.controller.product.ProductSearchController.java

private List<Map.Entry<String, String>> fillTargetSet(StringBuffer targetStr,
        List<Map.Entry<String, String>> therapyDomainMap, Locale locale) {
    if (!"".equals(targetStr)) {
        Set<String> typeIdSet = new HashSet<String>();
        String[] arrStrs = targetStr.toString().split(",");

        for (int k = 0, h = arrStrs.length; k < h; k++) {
            if (StringUtils.isNotEmpty(arrStrs[k])) {
                typeIdSet.add(arrStrs[k]);
            }/*from ww w  .j  av a  2s .  co  m*/
        }

        if (typeIdSet.isEmpty()) {
            return therapyDomainMap;
        }

        List<Menu> menuList = menuService.findMenuListByIds(typeIdSet.toArray());

        if (null != menuList && !menuList.isEmpty()) {
            Map<String, String> therapyDomainMapTemp = new TreeMap<String, String>();
            Menu tempMenu = null;
            for (int i = 0, j = menuList.size(); i < j; i++) {
                //2015-05-01 working day
                //yannis ?others?
                if (null != menuList.get(i).getLabelEn()
                        && "Others".equalsIgnoreCase(menuList.get(i).getLabelEn())) {
                    tempMenu = menuList.get(i);
                    continue;
                }
                if ("zh_CN".equals(locale.toString())) {
                    therapyDomainMapTemp.put(String.valueOf(menuList.get(i).getId()),
                            menuList.get(i).getName());
                } else if ("en_US".equals(locale.toString())) {
                    therapyDomainMapTemp.put(String.valueOf(menuList.get(i).getId()),
                            menuList.get(i).getLabelEn());
                }
            }

            therapyDomainMap = sortMap(therapyDomainMap, therapyDomainMapTemp);
            if (null != tempMenu) {
                Map<String, String> tempMap = new HashMap<String, String>();
                if ("zh_CN".equals(locale.toString())) {
                    tempMap.put(String.valueOf(tempMenu.getId()), tempMenu.getName());
                } else if ("en_US".equals(locale.toString())) {
                    tempMap.put(String.valueOf(tempMenu.getId()), tempMenu.getLabelEn());
                }
                Iterator itor = tempMap.entrySet().iterator();
                while (itor.hasNext()) {
                    Entry entry = (Entry) itor.next();
                    therapyDomainMap.add(entry);
                }

            }
        }

    }

    return therapyDomainMap;
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DiskCaptchaBuffer.java

/**
 * Gets an entry from the Disk Store.//from ww w  . j a  v  a  2  s. co m
 *
 * @return The element
 */
protected synchronized Collection remove(int number, Locale locale) throws IOException {
    if (!isInitalized)
        return new ArrayList(0);
    DiskElement diskElement = null;
    int index = 0;
    boolean diskEmpty = false;

    Collection collection = new UnboundedFifoBuffer();

    //if no locale
    if (!diskElements.containsKey(locale)) {
        return collection;
    }

    try {
        while (!diskEmpty && index < number) {

            // Check if the element is on disk
            try {
                diskElement = (DiskElement) ((LinkedList) diskElements.get(locale)).removeFirst();

                // Load the element
                randomAccessFile.seek(diskElement.position);
                byte[] buffer = new byte[diskElement.payloadSize];
                randomAccessFile.readFully(buffer);
                ByteArrayInputStream instr = new ByteArrayInputStream(buffer);
                ObjectInputStream objstr = new ObjectInputStream(instr);

                collection.add(objstr.readObject());
                instr.close();
                objstr.close();

                freeBlock(diskElement);
                index++;
            } catch (NoSuchElementException e) {
                diskEmpty = true;
                log.debug("disk is empty for locale : " + locale.toString());
            }
        }
    } catch (Exception e) {
        log.error("Error while reading on disk ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("removed  " + collection.size() + " from disk buffer with locale " + locale.toString());
    }
    return collection;
}