Example usage for org.springframework.context.support MessageSourceAccessor getMessage

List of usage examples for org.springframework.context.support MessageSourceAccessor getMessage

Introduction

In this page you can find the example usage for org.springframework.context.support MessageSourceAccessor getMessage.

Prototype

public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException 

Source Link

Document

Retrieve the given MessageSourceResolvable (e.g.

Usage

From source file:nz.co.senanque.pizzabundle.AppFactoryImpl.java

public App createApp(Blackboard blackboard) {
    // Explicitly fetch this bean to ensure it is not instantiated until the session has started.
    m_maduraSessionManager = m_beanFactory.getBean("maduraSessionManager", MaduraSessionManager.class);
    App ret = new App();
    MaduraFieldGroup fieldGroup = getMaduraSessionManager().createMaduraFieldGroup();
    final Layout layout = new Layout(m_maduraSessionManager, fieldGroup);
    layout.setBlackboard(blackboard);//from   w  w  w  . j ava  2 s . co m
    ret.setComponentContainer(layout);
    Pizza pizza = new Pizza();

    m_maduraSessionManager.getValidationSession().bind(pizza);
    MenuBar menuBar = new MenuBar();
    final MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
    final MenuBar.MenuItem edit = menuBar.addItem(messageSourceAccessor.getMessage("menu.edit", "Edit"), null);

    CommandExt command = fieldGroup.createMenuItemCommand(new ClickListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            Notification.show(messageSourceAccessor.getMessage("message.clicked.cancel"),
                    messageSourceAccessor.getMessage("message.noop"), Notification.Type.HUMANIZED_MESSAGE);

        }
    });
    MenuItem menuItemSave = edit.addItem("menu.cancel", command);
    fieldGroup.bind(menuItemSave);

    command = fieldGroup.createMenuItemCommandSubmit(new ClickListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event) {
            Notification.show(messageSourceAccessor.getMessage("message.clicked.submit"),
                    messageSourceAccessor.getMessage("message.noop"), Notification.Type.HUMANIZED_MESSAGE);

        }
    });
    MenuItem menuItemCancel = edit.addItem("menu.save", command);
    fieldGroup.bind(menuItemCancel);

    ret.setMenuBar(menuBar);

    layout.load(pizza);

    return ret;
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.PasswordHintController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

    String username = request.getParameter("username");
    MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }//w  w  w.j  av  a2s . c  o m

    log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        User user = userManager.getUserByUsername(username);

        StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        message.setTo(user.getEmail());
        String subject = '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint");
        message.setSubject(subject);
        message.setText(msg.toString());
        mailEngine.send(message);

        saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (UsernameNotFoundException e) {
        log.warn(e.getMessage());
        saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (MailException me) {
        log.warn(me.getMessage());
        saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:org.openmrs.module.web.controller.ModuleListController.java

@Override
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    MessageSourceAccessor msa = getMessageSourceAccessor();

    map.put("allowAdmin", ModuleUtil.allowAdmin().toString());
    map.put("disallowUploads", msa.getMessage("Module.disallowUploads",
            new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }));

    map.put("openmrsVersion", OpenmrsConstants.OPENMRS_VERSION_SHORT);
    map.put("moduleRepositoryURL", WebConstants.MODULE_REPOSITORY_URL);

    map.put("loadedModules", ModuleFactory.getLoadedModules());

    return map;//from ww w .j  a v a2s .co m
}

From source file:nz.co.senanque.vaadinsupport.MaduraPropertyWrapper.java

public void setValue(Object newValue) {
    if (isReadOnly()) {
        return;/*from   ww  w  . j  ava  2 s  . c  o  m*/
    }
    try {
        Class<?> clazz = this.getDataType();
        Object converted = newValue;
        if (m_propertyFormatter != null) {
            try {
                converted = m_propertyFormatter.parse(String.valueOf(newValue));
            } catch (Exception e) {
                MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(m_messageSource);
                String message = messageSourceAccessor.getMessage(
                        "nz.co.senanque.validationengine.numericparse",
                        new Object[] { this.m_label, String.valueOf(newValue) });
                throw new ValidationException(message);
            }
        } else {
            if (converted instanceof ChoiceBase) {
                converted = ((ChoiceBase) converted).getKey();
            }
            if (clazz != String.class) {
                try {
                    if (clazz.isEnum()) {
                        Method fromValueMethod = clazz.getMethod("fromValue", String.class);
                        converted = fromValueMethod.invoke(null, new Object[] { String.valueOf(newValue) });
                    } else {
                        MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(
                                m_messageSource);
                        converted = ConvertUtils.convertToObject(clazz, newValue, messageSourceAccessor);
                    }
                } catch (Exception e) {
                    throw e;
                }
            }
        }
        m_setter.invoke(m_owner, new Object[] { converted });
        setErrorText(null);
        m_lastFailedValue = null;
    } catch (InvocationTargetException e) {
        logger.warn("error", e);
        Throwable target = e.getTargetException();
        if (target != null) {
            if (target instanceof ValidationException) {
                setErrorText(target.getLocalizedMessage());
                m_lastFailedValue = newValue;
            } else {
                throw new RuntimeException(target);
            }
        } else {
            throw new RuntimeException(e);
        }
    } catch (ValidationException e) {
        logger.warn("error", e);
        setErrorText(e.getLocalizedMessage());
        m_lastFailedValue = newValue;
    } catch (Exception e) {
        logger.warn("error", e);
        throw new RuntimeException(e);
    }
}

From source file:org.springjutsu.validation.ValidationErrorMessageHandler.java

/**
 * If we're trying to resolve the message key for a path on the model,
 * this method will unwrap that message key.
 * For instance, consider our model is a Account instance, which has a 
 * field accountOwner of type User, and that User object has a 
 * username field of type String:/*from w  w  w. ja  v a  2  s . c om*/
 * If rulePath was "accountOwner.username", then it would return a
 * message key of "user.username", which is the simple classname of the
 * owning object of the failed validation path, and the field name.
 * This is so we can display the label of the field that failed validation
 * in the error message. For instance "User Name must be 8 chars" instead
 * of something cryptic like "accountOwner.username must be 8 chars".
 * @param rulePath Validation rule path to the failed field.
 * @param rootModel The root model owning the field that failed.
 * @return A message key used to resolve a message describing the field
 * that failed.
 */
protected String getModelMessageKey(String rawRulePath, Object rootModel) {

    if (rawRulePath == null || rawRulePath.length() < 1) {
        return rawRulePath;
    }

    // clean up any collection and/or map indexing paths from last path segment.
    String rulePath = rawRulePath.trim().replaceAll("\\[[^\\]]+\\]$", "");

    Class<?> parentType = null;
    String fieldPath = null;

    if (rulePath.contains(".")) {
        fieldPath = rulePath.substring(rulePath.lastIndexOf(".") + 1);
        String parentPath = rulePath.substring(0, rulePath.lastIndexOf("."));
        BeanWrapperImpl beanWrapper = new BeanWrapperImpl(rootModel);
        parentType = beanWrapper.getPropertyType(parentPath);
    } else {
        fieldPath = rulePath;
        parentType = rootModel.getClass();
    }

    if (enableSuperclassFieldLabelLookup) {
        MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(messageSource);
        Class<?> messageBearingType = parentType;
        while (messageBearingType != null) {
            if (!messageSourceAccessor
                    .getMessage(buildMessageKey(messageBearingType, fieldPath), "MessageNotFound")
                    .equals("MessageNotFound")) {
                break;
            } else {
                messageBearingType = messageBearingType.getSuperclass();
            }
        }
        if (messageBearingType != null) {
            parentType = messageBearingType;
        }
    }

    return buildMessageKey(parentType, fieldPath);
}

From source file:alpha.portal.webapp.controller.PasswordHintController.java

/**
 * Handle request.//from   ww w  .  j a  v a2 s  . c om
 * 
 * @param request
 *            the request
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(final HttpServletRequest request) throws Exception {
    this.log.debug("entering 'handleRequest' method...");

    final String username = request.getParameter("username");
    final MessageSourceAccessor text = new MessageSourceAccessor(this.messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        this.log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }

    this.log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        final User user = this.userManager.getUserByUsername(username);

        final StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        this.message.setTo(user.getEmail());
        final String subject = '[' + text.getMessage("webapp.name") + "] "
                + text.getMessage("user.passwordHint");
        this.message.setSubject(subject);
        this.message.setText(msg.toString());
        this.mailEngine.send(this.message);

        this.saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (final UsernameNotFoundException e) {
        this.log.warn(e.getMessage());
        this.saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (final MailException me) {
        this.log.warn(me.getMessage());
        this.saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:org.openmrs.module.sync.web.controller.ConfigListController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    log.debug("in onSubmit");

    ModelAndView result = new ModelAndView(new RedirectView(getSuccessView()));

    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    HttpSession httpSession = request.getSession();
    String success = "";
    String error = "";
    MessageSourceAccessor msa = getMessageSourceAccessor();

    String action = ServletRequestUtils.getStringParameter(request, "action", "");

    log.debug("action is " + action);

    if ("deleteServer".equals(action)) {
        // check to see if the user is trying to delete a server, react accordingly
        Integer serverId = ServletRequestUtils.getIntParameter(request, "serverId", 0);
        String serverName = "Server " + serverId.toString();

        SyncService ss = Context.getService(SyncService.class);

        if (serverId > 0) {
            RemoteServer deleteServer = ss.getRemoteServer(serverId);
            serverName = deleteServer.getNickname();

            try {
                ss.deleteRemoteServer(deleteServer);
                Object[] args = { serverName };
                success = msa.getMessage("sync.config.server.deleted", args);
            } catch (Exception e) {
                Object[] args = { serverName };
                error = msa.getMessage("sync.config.server.deleteFailed", args);
            }/*from   w w  w.ja v  a2  s .  c  o  m*/
        } else {
            error = msa.getMessage("sync.config.server.notDeleted");
        }

    } else if ("manualTx".equals(action)) {
        try {
            Integer serverId = ServletRequestUtils.getIntParameter(request, "serverId", 0);
            RemoteServer server = Context.getService(SyncService.class).getRemoteServer(serverId);

            log.warn("IN MANUAL-TX WITH SERVERID: " + serverId);

            // we are creating a sync-transmission, so start by generating a SyncTransmission object
            SyncTransmission tx = SyncUtilTransmission.createSyncTransmission(server, true,
                    SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE));
            String toTransmit = tx.getFileOutput();

            // Record last attempt
            server.setLastSync(new Date());
            Context.getService(SyncService.class).saveRemoteServer(server);

            // Write sync transmission to response
            InputStream in = new ByteArrayInputStream(toTransmit.getBytes());
            response.setContentType("text/xml; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + tx.getFileName() + ".xml");
            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
            out.flush();
            out.close();

            // don't return a model/view - we'll need to return a file instead.
            result = null;
        } catch (Exception e) {
            error = msa.getMessage("sync.status.createTx.error");
            e.printStackTrace();
        }

    }

    if (!success.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);

    if (!error.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);

    return result;
}

From source file:org.openmrs.module.sync.web.controller.StatusListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//  w  w  w . jav  a  2s .  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)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    ModelAndView result = new ModelAndView(new RedirectView(getSuccessView()));

    // TODO - replace with privilege check
    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    RemoteServer parent = null;
    HttpSession httpSession = request.getSession();
    String success = "";
    String error = "";
    MessageSourceAccessor msa = getMessageSourceAccessor();

    String action = ServletRequestUtils.getStringParameter(request, "action", "");

    SyncService syncService = Context.getService(SyncService.class);

    if ("resetAttempts".equals(action)) {
        List<SyncRecord> syncRecords = syncService.getSyncRecords(SyncRecordState.FAILED_AND_STOPPED);
        for (SyncRecord syncRecord : syncRecords) {
            syncRecord.setState(SyncRecordState.FAILED);
            syncRecord.setRetryCount(0);
            syncService.updateSyncRecord(syncRecord);
        }
        success = msa.getMessage("sync.status.transmission.reset.attempts.success",
                new Object[] { syncRecords.size() });
        result.addObject("mode", request.getParameter("mode"));
    } else if ("createTx".equals(action)) { // handle transmission generation
        try {
            parent = syncService.getParentServer();
            if (parent == null) {
                throw new SyncException(
                        "Could not retrieve information about the parent server; null returned.");
            }

            // we are creating a sync-transmission, so start by generating a SyncTransmission object
            // and this is a sychronization via file   due the value of action being createTx   
            SyncTransmission tx = SyncUtilTransmission.createSyncTransmission(parent, true,
                    SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE));
            String toTransmit = null; // the actual text that will be sent (either an ST or an STR)

            // Pull out the committed records from parent that haven't been sent back for confirmation
            // these are all the records we've received and are not sending a confirmation of receipt
            List<SyncImportRecord> syncImportRecords = syncService
                    .getSyncImportRecords(SyncRecordState.COMMITTED, SyncRecordState.ALREADY_COMMITTED);

            SyncTransmissionResponse str = new SyncTransmissionResponse();
            str.setState(SyncTransmissionState.OK);
            str.setSyncImportRecords(syncImportRecords);
            //note: this is transmission *response* object: as in child's response to parent
            //so the target/source is viewed from 'parent' perspective, 
            //hence for responses the target ID contains the server that generated the response
            //in this case that means: the target uuid is current server (child) uuid and source uuid is the parent 
            str.setSyncSourceUuid(tx.getSyncTargetUuid());
            str.setSyncTargetUuid(tx.getSyncSourceUuid());
            str.setSyncTransmission(tx);
            str.setTimestamp(tx.getTimestamp());
            str.setUuid(tx.getUuid());
            str.setFileName(""); //of no relevance; we're not saving to file system

            str.createFile(false);
            toTransmit = str.getFileOutput();

            // Record last attempt
            parent.setLastSync(new Date());
            syncService.saveRemoteServer(parent);

            // Write text to response
            InputStream in = new ByteArrayInputStream(toTransmit.getBytes());
            response.setContentType("text/xml; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + tx.getFileName() + ".xml");
            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
            out.flush();
            out.close();

            for (SyncImportRecord record : syncImportRecords) {
                record.setState(SyncRecordState.COMMITTED_AND_CONFIRMATION_SENT);
                syncService.updateSyncImportRecord(record);
            }

            // don't return a model/view - we'll need to return a file instead.
            result = null;
        } catch (Exception e) {
            e.printStackTrace();
            error = msa.getMessage("sync.status.createTx.error");
        }
    } else if ("uploadResponse".equals(action) && request instanceof MultipartHttpServletRequest) {

        try {
            String contents = "";
            parent = syncService.getParentServer();

            // first, get contents of file that is being uploaded.  it is clear we are uploading a response from parent at this point
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartSyncFile = multipartRequest.getFile("syncResponseFile");
            if (multipartSyncFile != null && !multipartSyncFile.isEmpty()) {
                InputStream inputStream = null;
                StringBuilder sb = new StringBuilder();

                try {
                    inputStream = multipartSyncFile.getInputStream();
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(inputStream, SyncConstants.UTF8));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    contents = sb.toString();
                } catch (Exception e) {
                    log.error("Unable to read in sync data file", e);
                    error = e.getMessage();
                } finally {
                    try {
                        if (inputStream != null)
                            inputStream.close();
                    } catch (IOException io) {
                        log.error("Unable to close temporary input stream", io);
                    }
                }
            }

            if (contents.length() > 0) {
                SyncTransmissionResponse str = SyncDeserializer.xmlToSyncTransmissionResponse(contents);

                int numCommitted = 0;
                int numAlreadyCommitted = 0;
                int numFailed = 0;
                int numOther = 0;

                if (str.getSyncImportRecords() == null)
                    log.debug("No records to process in response");
                else {
                    // process each incoming syncImportRecord, this is just status update
                    for (SyncImportRecord importRecord : str.getSyncImportRecords()) {
                        Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord,
                                parent);
                    }
                }

                try {
                    // store this file on filesystem too
                    str.createFile(false, SyncConstants.DIR_JOURNAL);
                } catch (Exception e) {
                    log.error("Unable to create file to store SyncTransmissionResponse: " + str.getFileName());
                    e.printStackTrace();
                }

                // now pull out the data that originated on the 'source' server and try to process it
                SyncTransmission st = str.getSyncTransmission();

                // now process the syncTransmission if one was received                    
                if (st != null) {
                    str = SyncUtilTransmission.processSyncTransmission(st, SyncUtil
                            .getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE));
                    // get some numbers about what was just processed to show user the results
                    if (str.getSyncImportRecords() != null) {
                        for (SyncImportRecord importRecord : str.getSyncImportRecords()) {
                            if (importRecord.getState().equals(SyncRecordState.COMMITTED))
                                numCommitted++;
                            else if (importRecord.getState().equals(SyncRecordState.ALREADY_COMMITTED))
                                numAlreadyCommitted++;
                            else if (importRecord.getState().equals(SyncRecordState.FAILED))
                                numFailed++;
                            else
                                numOther++;
                        }
                    }
                }

                Object[] args = { numCommitted, numFailed, numAlreadyCommitted, numOther };

                success = msa.getMessage("sync.status.uploadResponse.success", args);
            } else {
                error = msa.getMessage("sync.status.uploadResponse.fileEmpty");
            }
        } catch (Exception e) {
            e.printStackTrace();
            error = msa.getMessage("sync.status.uploadResponse.error");
        }
    }

    if (!success.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);

    if (!error.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);

    return result;
}

From source file:org.openmrs.hl7.web.controller.Hl7DeletedFormController.java

/**
 * This method pushes a message that had been deleted previously back into the queue to be
 * processed/*from w w  w . j a  v a 2  s.  c om*/
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    HttpSession httpSession = request.getSession();
    String view = getFormView();
    StringBuffer success = new StringBuffer();
    StringBuffer error = new StringBuffer();
    MessageSourceAccessor msa = getMessageSourceAccessor();

    String[] queueForm = request.getParameterValues("queueId");

    HL7Service hL7Service = Context.getHL7Service();

    if (queueForm != null) {
        for (String queueId : queueForm) {
            // Argument to pass to the success/error message
            Object[] args = new Object[] { queueId };

            try {
                //Restore Selected Message to the in queue table
                HL7InArchive hl7InArchive = hL7Service.getHL7InArchive(Integer.valueOf(queueId));
                HL7InQueue hl7InQueue = new HL7InQueue(hl7InArchive);
                hL7Service.saveHL7InQueue(hl7InQueue);

                //Delete selected Message from the archives table
                hL7Service.purgeHL7InArchive(hl7InArchive);

                //Display a message for the operation
                success.append(msa.getMessage("Hl7inQueue.queueForm.restored", args) + "<br/>");
            } catch (APIException e) {
                log.warn("Error restoring deleted queue item", e);
                error.append(msa.getMessage("Hl7inQueue.queueForm.error", args) + "<br/>");
            }
        }
    }

    view = getSuccessView();

    if (!success.toString().equals("")) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success.toString());
    }
    if (!error.toString().equals("")) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error.toString());
    }

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