Example usage for java.util ResourceBundle getString

List of usage examples for java.util ResourceBundle getString

Introduction

In this page you can find the example usage for java.util ResourceBundle getString.

Prototype

public final String getString(String key) 

Source Link

Document

Gets a string for the given key from this resource bundle or one of its parents.

Usage

From source file:es.pode.empaquetador.presentacion.avanzado.recursos.exportar.ExportarRecursosControllerImpl.java

public String selectAction(ActionMapping mapping, SelectActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String result = null;//from   w  ww.jav a2  s.  c o  m
    String actionSubmit = form.getAction();
    java.util.Locale locale = (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE);
    ResourceBundle i18n = ResourceBundle.getBundle("application-resources", locale);

    if (form.getAction() == (null)) {
        throw new ValidatorException("{portal_empaquetado.exception}");
    }

    else if (actionSubmit.equals(i18n.getString("presentacion.avanzado.recursos.exportar.cancelar"))) {
        result = "Cancelar";
    } else if (actionSubmit.equals(i18n.getString("presentacion.avanzado.recursos.exportar.aceptar"))) {
        result = "Aceptar";
    } else {

        Logger.getLogger(this.getClass())
                .debug("El valor del submit no es correcto (actionSubmit = " + actionSubmit + ";");
    }
    return result;
}

From source file:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {//  www.  jav a 2  s.  c om
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:com.redhat.rhn.common.localization.XmlMessages.java

/**
 * Method to format a string from the resource bundle.  This
 * method allows the user of this class to directly specify the
 * bundle package name to be used.  Allows us to have
 * resource bundles in packages without classes.  Eliminates
 * the need for "Dummy" classes./*from  ww w  .j  ava  2s  .  c om*/
 *
 * @param clazz the class to which the string belongs
 * @param locale the locale used to find the resource bundle
 * @param key the key for the string to be obtained from the resource bundle
 * @param args the arguments that should be applied to the string obtained
 * from the resource bundle. Can be null, to represent no arguments
 * @return the formatted message for the given key and arguments
 */
public String format(final Class clazz, final Locale locale, final String key, final Object... args) {

    // Fetch the bundle
    ResourceBundle bundle = getBundle(getBundleName(clazz), locale);
    String pattern = StringEscapeUtils.unescapeHtml(bundle.getString(key));

    pattern = pattern.replaceAll(PRODUCT_NAME_MACRO, Config.get().getString("web.product_name"));

    if (args == null || args.length == 0) {
        return pattern;
    }

    //MessageFormat uses single quotes to escape text. Therefore, we have to
    //escape the single quote so that MessageFormat keeps the single quote and
    //does replace all arguments after it.
    String escapedPattern = pattern.replaceAll("'", "''");
    MessageFormat mf = new MessageFormat(escapedPattern, locale);
    return mf.format(args);
}

From source file:com.autentia.tnt.bean.reports.ReportParameterDefinition.java

private String getTraslateValue(String value) {
    String traslateValue = "";
    try {//from   w w w .  j av a2 s. co  m
        ResourceBundle resource = ResourceBundle.getBundle("com.autentia.tnt.resources.report",
                FacesUtils.getViewLocale());
        traslateValue = resource.getString(value.trim());
    } catch (MissingResourceException ex) {
        log.error(ex.getMessage());
    }
    return traslateValue;
}

From source file:com.flexive.shared.exceptions.FxExceptionMessage.java

/**
 * Returns the resource bundle, which is cached within the request.
 *
 * @param key       resource key/*from w w  w.  j ava2  s  . c  om*/
 * @param locale    the requested locale
 * @return the resource bundle value
 */
public String getResource(String key, Locale locale) {
    if (!initialized) {
        initialize();
    }
    final FxSharedUtils.MessageKey messageKey = new FxSharedUtils.MessageKey(locale, key);
    String cachedMessage = cachedMessages.get(messageKey);
    if (cachedMessage != null) {
        return cachedMessage;
    }
    for (FxSharedUtils.BundleReference bundleReference : resourceBundles) {
        try {
            final ResourceBundle bundle = getResources(bundleReference, locale);
            final String message = bundle.getString(key);
            cachedMessage = cachedMessages.putIfAbsent(messageKey, message);
            return cachedMessage != null ? cachedMessage : message;
        } catch (MissingResourceException e) {
            // continue with next bundle
        }
    }
    if (!locale.equals(Locale.ENGLISH)) {
        //try to find the locale in english as last resort
        //this is a fix for using PropertyResourceBundles which can only handle one locale (have to use them thanks to JBoss 5...)
        for (FxSharedUtils.BundleReference bundleReference : resourceBundles) {
            try {
                final ResourceBundle bundle = getResources(bundleReference, Locale.ENGLISH);
                final String message = bundle.getString(key);
                cachedMessage = cachedMessages.putIfAbsent(messageKey, message);
                return cachedMessage != null ? cachedMessage : message;
            } catch (MissingResourceException e) {
                // continue with next bundle
            }
        }
    }
    throw new MissingResourceException("Resource not found", FxExceptionMessage.class.getCanonicalName(), key);
}

From source file:org.fornax.cartridges.sculptor.framework.web.errorhandling.ErrorBindingPhaseListener.java

/** 
 * Pull out the Spring Errors object from context and convert each error into
 * a FacesMessage.//  ww  w  .java2  s .  c  o m
 * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
 */
public void afterPhase(PhaseEvent event) {
    FacesContext context = event.getFacesContext();

    RequestContext requestContext = RequestContextHolder.getRequestContext();

    if (requestContext == null)
        return;
    Map<?, ?> model;
    try {
        model = requestContext.getFlashScope().asMap();
    } catch (IllegalStateException e) {
        return;
    }
    Locale locale = context.getExternalContext().getRequestLocale();

    for (Iterator<?> iter = model.keySet().iterator(); iter.hasNext();) {
        String key = (String) iter.next();
        Object value = model.get(key);

        // If we have an Errors object and it is not the duplicate currentFormObject
        // one (always provided for compatibility with single object forms)
        if (value instanceof Errors && !key.endsWith("currentFormObject")) {
            Errors errors = (Errors) value;

            for (Iterator<?> eter = errors.getAllErrors().iterator(); eter.hasNext();) {
                ObjectError error = (ObjectError) eter.next();
                String summary = null;
                try {
                    ResourceBundle bundle = ResourceBundle.getBundle("i18n.messages",
                            context.getViewRoot().getLocale());
                    summary = bundle.getString(error.getCode());

                    /* another way of getting the error code resolved */
                    /* it might be better to use this one */
                    /*FacesContext fc = FacesContext.getCurrentInstance();
                    ELContext elc = fc.getELContext();
                    ExpressionFactory ef = fc.getApplication().getExpressionFactory();
                    ValueExpression ve = ef.createValueExpression(elc, "#{msg}", PropertyResourceBundle.class);
                    PropertyResourceBundle msg = (PropertyResourceBundle) ve.getValue(elc);
                    if (msg != null) {
                       summary = msg.getString(error.getCode());
                    }*/

                    summary = MessageFormat.format(summary, error.getArguments());

                    // if it's a field error we prepend the name of the field to the message
                    if (error instanceof FieldError) {
                        FieldError fieldError = (FieldError) error;
                        summary = fieldError.getField() + " - " + summary;
                    }
                } catch (MissingResourceException mrexception) {
                    summary = error.getDefaultMessage();
                    // try to translate the message
                    if (messageSource != null) {
                        summary = messageSource.getMessage(error, locale);
                    }
                    if (summary != null) {
                        summary = MessageFormat.format(summary, error.getArguments());
                    }
                }

                if (summary != null) {
                    String detail = summary;
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
                    context.addMessage(null, message);
                }
            }
        }
    }
}

From source file:com.inkubator.hrm.web.converter.PaySalaryJurnalModelJurnalConverter.java

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("Messages",
            new Locale(FacesUtil.getSessionAttribute(HRMConstant.BAHASA_ACTIVE).toString()));

    String messages = StringUtils.EMPTY;
    Integer data = (Integer) value;
    if (data == HRMConstant.PAY_SALARY_JURNAL_MODEL_CASH) {
        messages = resourceBundle.getString("paySalaryJurnal.cash");
    } else if (data == HRMConstant.PAY_SALARY_JURNAL_MODEL_TRANSFER) {
        messages = resourceBundle.getString("paySalaryJurnal.transfer");
    }//from w w w .  j  ava2s  .co m
    return messages;
}

From source file:com.inkubator.hrm.web.converter.PaySalaryJurnalTypeJurnalConverter.java

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("Messages",
            new Locale(FacesUtil.getSessionAttribute(HRMConstant.BAHASA_ACTIVE).toString()));

    String messages = StringUtils.EMPTY;
    Integer data = (Integer) value;
    if (data == HRMConstant.PAY_SALARY_JURNAL_TYPE_DEBET) {
        messages = resourceBundle.getString("paySalaryJurnal.debet");
    } else if (data == HRMConstant.PAY_SALARY_JURNAL_TYPE_KREDIT) {
        messages = resourceBundle.getString("paySalaryJurnal.kredit");
    }//w  w  w. j  ava2  s. co m
    return messages;
}

From source file:es.pode.empaquetador.presentacion.archivos.creararchivo.CrearArchivoControllerImpl.java

/**
 * @see es.pode.empaquetador.presentacion.archivos.creararchivo.CrearArchivoController#crearArchivo(org.apache.struts.action.ActionMapping, es.pode.empaquetador.presentacion.archivos.creararchivo.CrearArchivoForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///w w  w .  ja  va  2s .co m
public final void crearArchivo(ActionMapping mapping,
        es.pode.empaquetador.presentacion.archivos.creararchivo.CrearArchivoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    EmpaquetadorSession sesEmpaq = this.getEmpaquetadorSession(request);
    GestorArchivosSession sesArch = this.getGestorArchivosSession(request);

    java.util.Locale locale = (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE);
    ResourceBundle i18n = ResourceBundle.getBundle("application-resources", locale);

    String opcion = form.getAction();

    if (opcion.equals(i18n.getString("presentacion.archivos.creararchivo.input.submit.aceptar"))) {

        String tipo1 = form.getTipo1();
        String tipo2 = form.getTipo2();
        String tipo3 = form.getTipo3();

        ValidatorException exception1 = null;
        ValidatorException exception2 = null;
        ValidatorException exception3 = null;

        FormFile ficheroN1 = form.getFichero1();
        if (!ficheroN1.getFileName().equals("")) {
            try {
                operacionesFicheros(ficheroN1, tipo1, sesArch, sesEmpaq, i18n);
            } catch (ValidatorException e) {
                exception1 = e;
            }
        }
        FormFile ficheroN2 = form.getFichero2();
        if (!ficheroN2.getFileName().equals("")) {
            try {
                operacionesFicheros(ficheroN2, tipo2, sesArch, sesEmpaq, i18n);
            } catch (ValidatorException e) {
                exception2 = e;
            }
        }
        FormFile ficheroN3 = form.getFichero3();
        if (!ficheroN3.getFileName().equals("")) {
            try {
                operacionesFicheros(ficheroN3, tipo3, sesArch, sesEmpaq, i18n);
            } catch (ValidatorException e) {
                exception3 = e;
            }
        }

        if (ficheroN1.getFileName().equals("") && ficheroN2.getFileName().equals("")
                && ficheroN3.getFileName().equals("")) {
            throw new ValidatorException("{presentacion.archivos.creararchivo.error.seleccion}");
        }
        if (exception1 != null || exception2 != null || exception3 != null) {
            StringBuffer mensaje = new StringBuffer(
                    i18n.getString("portalempaquetado.archivos.error.importar") + DOSPUNTOS);
            if (exception1 != null) {
                mensaje.append("<p>");
                mensaje.append(exception1.getMessage());
                //               mensaje.append("</li>");
            }
            if (exception2 != null) {
                mensaje.append("<p>");
                mensaje.append(exception2.getMessage());
                //               mensaje.append("</li>");
            }
            if (exception3 != null) {
                mensaje.append("<p>");
                mensaje.append(exception3.getMessage());
                //               mensaje.append("</li>");
            }
            //            mensaje.append("</ul>");
            String mensajeFinal = mensaje.toString();
            throw new ValidatorException(mensajeFinal);
        }
    }
}

From source file:es.pode.empaquetador.presentacion.avanzado.organizaciones.elementos.secuencia.SecuenciaControllerImpl.java

public final java.lang.String selectAction(ActionMapping mapping,
        es.pode.empaquetador.presentacion.avanzado.organizaciones.elementos.secuencia.SelectActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    String result = null;/*from   w  ww .ja va2s  . c o  m*/
    String actionSubmit = form.getAction();
    java.util.Locale locale = (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE);
    ResourceBundle i18n = ResourceBundle.getBundle("application-resources", locale);

    if (form.getAction() == (null)) {
        throw new ValidatorException("{portal_empaquetado.exception}");
    }

    else if (actionSubmit.equals(i18n.getString("portal_empaquetado_secuencia.cancelar"))) {
        result = "Cancelar";
    } else if (actionSubmit.equals(i18n.getString("portal_empaquetado_secuencia.aceptar"))) {
        result = "aceptar";
    } else if (actionSubmit.equals(i18n.getString("secuencia.valorPorDefecto"))) {
        result = "default";
    }

    Logger.getLogger(this.getClass())
            .error("El valor del submit no es correcto (actionSubmit = " + actionSubmit + ";");

    return result;
}