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.dspace.app.xmlui.aspect.eperson.EditProfile.java

private void add_language(List identity, String defaultLanguage) throws WingException {
    if (!ConfigurationManager.getBooleanProperty("lr", "lr.xmlui.user.showlanguage", true)) {
        identity.addItem().addHidden("language")
                .setValue((defaultLanguage == null || defaultLanguage.equals(""))
                        ? I18nUtil.DEFAULTLOCALE.toString()
                        : defaultLanguage);
    } else {//from   w  w  w. java2 s.c o  m
        Select lang = identity.addItem().addSelect("language");
        lang.setLabel(T_language);
        if (supportedLocales.length > 0) {
            for (Locale lc : supportedLocales) {
                lang.addOption(lc.toString(), lc.getDisplayName());
            }
        } else {
            lang.addOption(I18nUtil.DEFAULTLOCALE.toString(), I18nUtil.DEFAULTLOCALE.getDisplayName());
        }
        lang.setOptionSelected(
                (defaultLanguage == null || defaultLanguage.equals("")) ? I18nUtil.DEFAULTLOCALE.toString()
                        : defaultLanguage);
        if (!registering && !ConfigurationManager.getBooleanProperty("xmlui.user.editmetadata", true)) {
            lang.setDisabled();
        }
    }
}

From source file:org.apache.jetspeed.portlets.clone.PortletCloneManagerPortlet.java

@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    String status = "fail";
    ClonePortletInfo clonePortletInfo = readClonePortletInfoFromRequest(request);
    PortletDefinition def = registry//from   w  ww .  j  a va2 s .com
            .getPortletDefinitionByUniqueName(clonePortletInfo.getOriginalPortletUniqueName());

    try {
        if (def == null) {
            throw new IllegalArgumentException(
                    "Cannot find the portlet or clone: " + clonePortletInfo.getOriginalPortletUniqueName());
        }

        if (StringUtils.isBlank(clonePortletInfo.getPortletName())) {
            throw new IllegalArgumentException("Invalid clone name: " + clonePortletInfo.getPortletName());
        }

        PortletDefinition clone = registry.clonePortletDefinition(def,
                StringUtils.trim(clonePortletInfo.getPortletName()));
        clone.getPortletInfo().setTitle(StringUtils.defaultString(clonePortletInfo.getPortletTitle()));
        clone.getPortletInfo()
                .setShortTitle(StringUtils.defaultString(clonePortletInfo.getPortletShortTitle()));
        clone.getPortletInfo().setKeywords(StringUtils.defaultString(clonePortletInfo.getPortletKeywords()));

        Locale defaultLocale = Locale.getDefault();
        DisplayName defaultDisplayName = null;

        for (DisplayName displayName : clone.getDisplayNames()) {
            if (displayName.getLocale().equals(defaultLocale)) {
                defaultDisplayName = displayName;
                break;
            }
        }

        if (defaultDisplayName == null) {
            defaultDisplayName = clone.addDisplayName(defaultLocale.toString());
        }

        defaultDisplayName.setDisplayName(StringUtils.defaultString(clonePortletInfo.getPortletDisplayName()));

        for (Map.Entry<String, List<String>> entry : clonePortletInfo.getPortletPreferences().entrySet()) {
            String prefName = entry.getKey();
            List<String> prefValues = entry.getValue();
            Preferences prefs = clone.getPortletPreferences();
            Preference pref = prefs.getPortletPreference(prefName);

            if (pref == null) {
                pref = prefs.addPreference(prefName);
            }

            List<String> values = pref.getValues();
            values.clear();
            values.addAll(prefValues);

            prefProvider.storeDefaults(clone, pref);
        }

        registry.savePortletDefinition(clone);
        status = "success";
    } catch (Exception e) {
        request.getPortletSession(true).setAttribute("errorMessage", e.toString());
        log.error("Failed to clone portlet from " + clonePortletInfo.getOriginalPortletUniqueName() + " to "
                + clonePortletInfo.getPortletName(), e);
    }

    request.getPortletSession(true).setAttribute("status", status);
}

From source file:org.alfresco.web.bean.LoginBean.java

/**
 * Invalidate ticket and logout user/*from  www .  j ava2  s. com*/
 */
public String logout() {
    FacesContext context = FacesContext.getCurrentInstance();

    // The outcome is decided in advance (before session expiry) and included as a parameter
    Map<?, ?> params = context.getExternalContext().getRequestParameterMap();
    String outcome = (String) params.get(PARAM_OUTCOME);
    if (outcome == null) {
        outcome = OUTCOME_LOGOUT;
    }

    Locale language = Application.getLanguage(context);

    // Perform log out actions
    Application.logOut(context);

    // set language to last used on the login page
    Application.setLanguage(context, language.toString());

    return outcome;
}

From source file:org.liveSense.server.i18n.loader.I18nLoader.java

public void install(Bundle bundle, String bundleName) throws Exception {
    // Removes proxy classes
    I18N.resetCache();/*from   www.j  a v  a  2 s  .c om*/
    log.info("Registering I18n: " + bundleName);
    i18nService.registerResourceBundle(bundle, bundleName);

    Session session = null;
    try {
        session = repository.loginAdministrative(null);
        // Writing entries to Repository
        String i18nPath = new File(bundleName.replace(".", "/")).getParent();
        String i18nName = new File(bundleName.replace(".", "/")).getName();
        Enumeration entries = bundle.getEntryPaths(i18nPath);

        if (entries != null) {
            while (entries.hasMoreElements()) {
                URL url = bundle.getEntry((String) entries.nextElement());
                String urlFileName = new File(url.getFile()).getName();
                if (urlFileName.endsWith(".properties") && (urlFileName.startsWith(i18nName))) {
                    log.info("Loading " + url + " into JCR repository");
                    String locale = urlFileName.substring(i18nName.length(),
                            urlFileName.length() - ".properties".length());
                    Locale loc = Locale.getDefault();
                    if (StringUtils.isNotEmpty(locale)) {
                        loc = LocaleUtils.toLocale(locale.substring(1));

                        Node n = createPath(session, "/" + path + "/" + bundleName + "/" + loc.toString(),
                                FOLDER_NODE_TYPE);
                        boolean foundType = false;
                        for (NodeType t : n.getMixinNodeTypes()) {
                            if (t.getName().equals(NodeType.MIX_LANGUAGE)) {
                                foundType = true;
                            }
                        }
                        if (!foundType)
                            n.addMixin(NodeType.MIX_LANGUAGE);
                        n.setProperty("jcr:language", loc.toString());
                        n.setProperty("sling:basename", bundleName);

                        java.util.Properties props = new java.util.Properties();
                        InputStream in = url.openStream();
                        props.load(in);
                        in.close();

                        for (Object key : props.keySet()) {
                            if (!n.hasNode((String) key)) {
                                log.info("Creating " + (String) key);
                                Node msgNode = n.addNode((String) key, "sling:MessageEntry");
                                msgNode.setProperty("sling:key", (String) key);
                                msgNode.setProperty("sling:message", props.getProperty((String) key));
                            }
                        }
                    }
                }
            }
        }
        if (session.hasPendingChanges())
            session.save();
    } catch (RepositoryException e) {
        log.error("Cannot get session", e);
    } finally {
        if (session != null && session.isLive()) {
            try {
                session.logout();
            } catch (Exception e) {
            }
        }
    }

}

From source file:org.dspace.app.xmlui.aspect.administrative.eperson.EditEPersonForm.java

private void add_config_info(Request request, EPerson edited_eperson, List identity,
        java.util.List<String> errors) throws SQLException, WingException {
    String languageValue = edited_eperson.getLanguage();
    String phoneValue = edited_eperson.getMetadata("phone");
    boolean canLogInValue = edited_eperson.canLogIn();
    boolean certificatValue = edited_eperson.getRequireCertificate();

    if (request.getParameter("phone") != null)
        phoneValue = request.getParameter("phone");
    if (request.getParameter("language") != null)
        languageValue = request.getParameter("language");

    if (!ConfigurationManager.getBooleanProperty("lr", "lr.xmlui.user.showlanguage", true)) {
        identity.addItem().addHidden("language").setValue(
                (languageValue == null || languageValue.equals("")) ? I18nUtil.DEFAULTLOCALE.toString()
                        : languageValue);
    } else {/* w  w  w . j a  v a 2 s. c  om*/
        if (isAdmin()) {
            Select language = identity.addItem(null, "admin-field").addSelect("language");
            language.setLabel(T_language);
            //language.setValue(languageValue);

            if (supportedLocales.length > 0) {
                for (Locale lc : supportedLocales) {
                    language.addOption(lc.toString(), lc.getDisplayName());
                }

            } else {
                language.addOption(I18nUtil.DEFAULTLOCALE.toString(), I18nUtil.DEFAULTLOCALE.getDisplayName());
            }
            language.setOptionSelected(
                    (languageValue == null || languageValue.equals("")) ? I18nUtil.DEFAULTLOCALE.toString()
                            : languageValue);

        } else {
            identity.addLabel(T_language);
            //identity.addItem(languageValue);
            identity.addItem(
                    (languageValue == null || languageValue.equals("")) ? I18nUtil.DEFAULTLOCALE.toString()
                            : languageValue);
        }
    }

    add_key_pair(isAdmin(), false, "phone", T_telephone, phoneValue, identity, null);

    if (isAdmin()) {
        // Administrative options:
        CheckBox canLogInField = identity.addItem(null, "admin-field").addCheckBox("can_log_in");
        canLogInField.setLabel(T_can_log_in);
        canLogInField.addOption(canLogInValue, "true");

        CheckBox certificateField = identity.addItem(null, "admin-field").addCheckBox("certificate");
        certificateField.setLabel(T_req_certs);
        certificateField.addOption(certificatValue, "true");

        CheckBox editsMetadata = identity.addItem(null, "admin-field").addCheckBox("can_edit_metadata");
        editsMetadata.setLabel("Can edit own item's metadata");
        editsMetadata.addOption(edited_eperson.canEditSubmissionMetadata(), "true");
    }

}

From source file:com.vmware.identity.SsoController.java

/**
 * Handle default tenant request sent with a wrong binding
 *//* w w  w.  jav  a 2 s .c  o  m*/
@RequestMapping(value = "/SAML2/SSO")
public void ssoDefaultTenantBindingError(Locale locale, HttpServletResponse response) throws IOException {
    logger.info("SSO binding error! The client locale is " + locale.toString() + ", DEFAULT tenant");
    sendError(locale, response, "Binding");
}

From source file:org.openmrs.web.controller.OptionsFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//  w  ww .j  a  v  a 2  s.  c om
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 * @should accept 2 characters as username
 * @should accept email address as username if enabled
 * @should reject 1 character as username
 * @should reject invalid email address as username if enabled
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (!errors.hasErrors()) {
        User loginUser = Context.getAuthenticatedUser();
        UserService us = Context.getUserService();
        User user = null;
        try {
            Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
            user = us.getUser(loginUser.getUserId());
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
        }

        OptionsForm opts = (OptionsForm) obj;

        Map<String, String> properties = user.getUserProperties();

        properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation());

        Locale locale = WebUtil.normalizeLocale(opts.getDefaultLocale());
        if (locale != null) {
            properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, locale.toString());
        }

        properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES,
                WebUtil.sanitizeLocales(opts.getProficientLocales()));
        properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION,
                opts.getNotification() == null ? "" : opts.getNotification().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS,
                opts.getNotificationAddress() == null ? "" : opts.getNotificationAddress().toString());

        if (!"".equals(opts.getOldPassword())) {
            try {
                String password = opts.getNewPassword();

                // check password strength
                if (password.length() > 0) {
                    try {
                        OpenmrsUtil.validatePassword(user.getUsername(), password,
                                String.valueOf(user.getUserId()));
                    } catch (PasswordException e) {
                        errors.reject(e.getMessage());
                    }
                    if (password.equals(opts.getOldPassword()) && !errors.hasErrors()) {
                        errors.reject("error.password.different");
                    }

                    if (!password.equals(opts.getConfirmPassword())) {
                        errors.reject("error.password.match");
                    }
                }

                if (!errors.hasErrors()) {
                    us.changePassword(opts.getOldPassword(), password);
                    if (opts.getSecretQuestionPassword().equals(opts.getOldPassword())) {
                        opts.setSecretQuestionPassword(password);
                    }
                    new UserProperties(user.getUserProperties()).setSupposedToChangePassword(false);
                }
            } catch (APIException e) {
                errors.rejectValue("oldPassword", "error.password.match");
            }
        } else {
            // if they left the old password blank but filled in new
            // password
            if (!"".equals(opts.getNewPassword())) {
                errors.rejectValue("oldPassword", "error.password.incorrect");
            }
        }

        if (!"".equals(opts.getSecretQuestionPassword())) {
            if (!errors.hasErrors()) {
                try {
                    us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(),
                            opts.getSecretAnswerNew());
                } catch (APIException e) {
                    errors.rejectValue("secretQuestionPassword", "error.password.match");
                }
            }
        } else if (!"".equals(opts.getSecretAnswerNew())) {
            // if they left the old password blank but filled in new
            // password
            errors.rejectValue("secretQuestionPassword", "error.password.incorrect");
        }

        String notifyType = opts.getNotification();
        if (notifyType != null && (notifyType.equals("internal") || notifyType.equals("internalProtected")
                || notifyType.equals("email"))) {
            if (opts.getNotificationAddress().isEmpty()) {
                errors.reject("error.options.notificationAddress.empty");
            } else if (!EmailValidator.getInstance().isValid(opts.getNotificationAddress())) {
                errors.reject("error.options.notificationAddress.invalid");
            }
        }

        if (opts.getUsername().length() > 0 && !errors.hasErrors()) {
            try {
                Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
                if (us.hasDuplicateUsername(user)) {
                    errors.rejectValue("username", "error.username.taken");
                }
            } finally {
                Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
            }
        }

        if (!errors.hasErrors()) {
            user.setUsername(opts.getUsername());
            user.setUserProperties(properties);

            // new name
            PersonName newPersonName = opts.getPersonName();

            // existing name
            PersonName existingPersonName = user.getPersonName();

            // if two are not equal then make the new one the preferred,
            // make the old one voided
            if (!existingPersonName.equalsContent(newPersonName)) {
                existingPersonName.setPreferred(false);
                existingPersonName.setVoided(true);
                existingPersonName.setVoidedBy(user);
                existingPersonName.setDateVoided(new Date());
                existingPersonName.setVoidReason("Changed name on own options form");

                newPersonName.setPreferred(true);
                user.addName(newPersonName);
            }

            Errors userErrors = new BindException(user, "user");
            ValidateUtil.validate(user, userErrors);

            if (userErrors.hasErrors()) {
                for (ObjectError error : userErrors.getAllErrors()) {
                    errors.reject(error.getCode(), error.getArguments(), "");
                }
            }

            if (errors.hasErrors()) {
                return super.processFormSubmission(request, response, opts, errors);
            }

            try {
                Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
                Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);

                us.saveUser(user);
                //trigger updating of the javascript file cache
                PseudoStaticContentController.invalidateCachedResources(properties);
                // update login user object so that the new name is visible
                // in the webapp
                Context.refreshAuthenticatedUser();
            } finally {
                Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
                Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
            }

            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved");
        } else {
            return super.processFormSubmission(request, response, opts, errors);
        }

        view = getSuccessView();
    }
    return new ModelAndView(new RedirectView(view));
}

From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneSearcherImpl.java

protected String findSortField(SearchParameters searchParameters, ClosingIndexSearcher searcher, String field,
        Locale sortLocale) {//w w w  . j a v a 2 s .  c om
    // find best field match

    MLAnalysisMode analysisMode = getLuceneConfig().getDefaultMLSearchAnalysisMode();
    HashSet<String> allowableLocales = new HashSet<String>();
    for (Locale l : MLAnalysisMode.getLocales(analysisMode, sortLocale, false)) {
        allowableLocales.add(l.toString());
    }

    String sortField = field;

    for (Object current : searcher.getReader().getFieldNames(FieldOption.INDEXED)) {
        String currentString = (String) current;
        if (currentString.startsWith(field) && currentString.endsWith(".sort")) {
            String fieldLocale = currentString.substring(field.length() + 1, currentString.length() - 5);
            if (allowableLocales.contains(fieldLocale)) {
                if (fieldLocale.equals(sortLocale.toString())) {
                    sortField = currentString;
                    break;
                } else if (sortLocale.toString().startsWith(fieldLocale)) {
                    if (sortField.equals(field) || (currentString.length() < sortField.length())) {
                        sortField = currentString;
                    }
                } else if (fieldLocale.startsWith(sortLocale.toString())) {
                    if (sortField.equals(field) || (currentString.length() < sortField.length())) {
                        sortField = currentString;
                    }
                }
            }
        }
    }
    return sortField;

}

From source file:no.abmu.abmstatistikk.web.AbstractReportController.java

protected ModelAndView basicReportDataByCounty(HttpServletRequest request,
        OrgUnitFinderSpecificationBean finderBean, SchemaTypeNameAndVersion schemaTypeNameAndVersion,
        String viewName) {/*from w w w . ja  v  a2s . co m*/

    Assert.checkRequiredArgument("request", request);
    Assert.checkRequiredArgument("finderBean", finderBean);
    Assert.checkRequiredArgument("schemaTypeNameAndVersion", schemaTypeNameAndVersion);
    Assert.checkRequiredArgument("viewName", viewName);

    if (logger.isDebugEnabled()) {
        logger.debug("[basicReportDataByCounty]: Start");
    }

    /*
     * This should be replaced with AOP in an XML spring config-file.
     */
    if (!isSecureContext()) {
        logger.error("[reportDataByCounty]: no secureContext loging off");
        return new ModelAndView(ViewNameConst.LOGOFF_VIEW);
    }

    Integer countyNumber = getCountyNumberFromRequestOrLoggedOnUser(request);
    if (null == countyNumber) {
        logger.error("[basicReportDataByCounty]: could not get any countyNumber, return to mainmenu.");
        return new ModelAndView(ViewNameConst.REDIRECT_2_MAIN_MENU);
    }

    finderBean.setCountyNumber(countyNumber);

    SchemaList jasperReportDataSource = reportService.createBasicReportData(finderBean,
            schemaTypeNameAndVersion);

    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    Locale locale = sessionLocaleResolver.resolveLocale(request);
    logger.info("We are using locale=[" + locale.toString() + "]");
    int reportPeriod = schemaTypeNameAndVersion.getYear();
    Map<String, Object> model = getModel(jasperReportDataSource);
    model.put("abmstatistikk.reportPeriod", Integer.toString(reportPeriod));
    model.put("abmstatistikk.budgetYear", Integer.toString(reportPeriod + 1));
    model.put(JRParameter.REPORT_LOCALE, locale);

    ModelAndView mav = new ModelAndView(viewName, model);
    return mav;
}

From source file:com.wcs.newsletter.controller.ConfigController.java

public void installDefaultContents() {
    try {//from   w  w w  . j a v  a  2 s  .  c o  m

        long id = CounterLocalServiceUtil.increment();
        ThemeDisplay themeDisplay = LiferayUtil.getThemeDisplay();
        DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(id);
        folder.setName("Webstar-Newsletter");
        folder.setParentFolderId(0);
        folder.setDescription("Folder for default Webstar-Newsletter contents");
        folder.setGroupId(themeDisplay.getScopeGroupId());
        folder.setCompanyId(themeDisplay.getCompanyId());
        folder.setUserId(themeDisplay.getRealUserId());
        folder.setParentFolderId(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
        long defaultRepoId = DLFolderConstants.getDataRepositoryId(themeDisplay.getScopeGroupId(),
                DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
        folder.setRepositoryId(defaultRepoId);
        Date allDate = new Date();
        folder.setCreateDate(allDate);
        folder.setModifiedDate(allDate);
        folder.setLastPostDate(allDate);
        folder = DLFolderLocalServiceUtil.addDLFolder(folder);
        ServiceContext serviceContext = new ServiceContext();
        serviceContext.setScopeGroupId(folder.getGroupId());
        serviceContext.setAddGuestPermissions(true);
        serviceContext.setGuestPermissions(new String[] { ActionKeys.ACCESS });

        long syncId = CounterLocalServiceUtil.increment();
        DLSync foldersSync = DLSyncLocalServiceUtil.createDLSync(syncId);
        foldersSync.setFileId(folder.getFolderId());
        foldersSync.setParentFolderId(folder.getParentFolderId());
        foldersSync.setCompanyId(folder.getCompanyId());
        foldersSync.setFileUuid(folder.getUuid());
        foldersSync.setRepositoryId(folder.getRepositoryId());
        foldersSync.setName(folder.getName());
        foldersSync.setEvent("add");
        foldersSync.setType("folder");
        foldersSync.setVersion("-1");
        foldersSync.setCreateDate(allDate);
        foldersSync.setModifiedDate(allDate);
        DLSyncLocalServiceUtil.updateDLSync(foldersSync);

        /* Confirm tempalte 1*/
        long fileId = CounterLocalServiceUtil.increment();
        InputStream inputStream = getClass().getClassLoader()
                .getResourceAsStream("install/HU_Confirm_Email.html");
        String filename = "Confirm_Template_HU.html";
        File confTemp1 = File.createTempFile("temp", ".tmp");
        FileOutputStream out = new FileOutputStream(confTemp1);
        IOUtils.copy(inputStream, out);

        DLFileEntry templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(),
                folder.getRepositoryId(), folder.getFolderId(), confTemp1.getName(), "text/html", filename,
                filename, "", folder.getDefaultFileEntryTypeId(), null, confTemp1, null,
                confTemp1.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null, confTemp1,
                null, confTemp1.getUsableSpace(), serviceContext);
        confTemp1.deleteOnExit();

        /* Confirm tempalte 2*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/EN_Confirm_Email.html");
        filename = "Confirm_Template_EN.html";
        File confTemp2 = File.createTempFile("temp2", ".tmp");
        out = new FileOutputStream(confTemp2);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), confTemp2.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, confTemp2, null, confTemp2.getUsableSpace(),
                serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null, confTemp2,
                null, confTemp2.getUsableSpace(), serviceContext);
        confTemp2.deleteOnExit();

        /*Set default confirm template to EN version */

        List<NewsletterConfig> configs = NewsletterConfigLocalServiceUtil.findByConfigKey("emailTemplate");
        NewsletterConfig defaultTemplate;
        if (configs.isEmpty()) {
            defaultTemplate = new NewsletterConfigImpl();
            defaultTemplate.setConfigKey("emailTemplate");
            defaultTemplate.setConfigValue(String.valueOf(templateFile.getFileEntryId()));
            NewsletterConfigLocalServiceUtil.addNewsletterConfig(defaultTemplate);
        } else {
            defaultTemplate = configs.get(0);
            defaultTemplate.setConfigValue(String.valueOf(templateFile.getFileEntryId()));
            NewsletterConfigLocalServiceUtil.updateNewsletterConfig(defaultTemplate);
        }

        /* Newsletter tempalte 1*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/HU_newsletterTemplate.html");
        filename = "Newsletter_Template_HU.html";
        File newsletterTemp1 = File.createTempFile("temp3", ".tmp");
        out = new FileOutputStream(newsletterTemp1);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), newsletterTemp1.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, newsletterTemp1, null,
                newsletterTemp1.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null,
                newsletterTemp1, null, newsletterTemp1.getUsableSpace(), serviceContext);
        newsletterTemp1.deleteOnExit();

        /* Newsletter tempalte 2*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/EN_newsletterTemplate.html");
        filename = "Newsletter_Template_EN.html";
        File newsletterTemp2 = File.createTempFile("temp4", ".tmp");
        out = new FileOutputStream(newsletterTemp2);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), newsletterTemp2.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, newsletterTemp2, null,
                newsletterTemp2.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null,
                newsletterTemp2, null, newsletterTemp2.getUsableSpace(), serviceContext);
        newsletterTemp2.deleteOnExit();

        NewsletterConfig defaultsInstalledConfig = new NewsletterConfigImpl();
        defaultsInstalledConfig.setConfigKey("defaultsInstalled");
        defaultsInstalledConfig.setConfigValue("1");
        NewsletterConfigLocalServiceUtil.addNewsletterConfig(defaultsInstalledConfig);

        Category actualCategory = null;
        Locale[] localesForDefaultCategories = LiferayUtil.getAvailableLocales();
        for (Locale local : localesForDefaultCategories) {
            actualCategory = new CategoryImpl();
            actualCategory.setLocale(local.toString());
            actualCategory.setName("Default_" + local);
            CategoryLocalServiceUtil.addCategory(actualCategory);
        }

    } catch (IOException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PortalException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SystemException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    }
}