Example usage for org.springframework.validation BindingResult rejectValue

List of usage examples for org.springframework.validation BindingResult rejectValue

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult rejectValue.

Prototype

void rejectValue(@Nullable String field, String errorCode, String defaultMessage);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

From source file:org.thymeleaf.engine.springintegration.context.ErrorsSpringIntegrationWebProcessingContextBuilder.java

@Override
protected void initBindingResult(final String bindingVariableName, final Object bindingObject, final ITest test,
        final BindingResult bindingResult, final Locale locale, final Map<String, Object> variables) {

    super.initBindingResult(bindingVariableName, bindingObject, test, bindingResult, locale, variables);

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> bindingErrorsList = (List<Map<String, Object>>) variables
            .get(BINDING_ERRORS_CONTEXT_VARIABLE_NAME);

    if (bindingErrorsList != null) {

        for (final Map<String, Object> bindingErrors : bindingErrorsList) {

            final Object bindingObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_NAME);
            if (bindingObj != null) {
                if (bindingObj.toString().equals(bindingVariableName)) {
                    // This error map applies to this binding variable

                    final Object fieldObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_FIELD_NAME);

                    final Object messageObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_MESSAGE_NAME);
                    if (messageObj == null) {
                        throw new TestEngineExecutionException(
                                "Error specification does not include property 'message', which is mandatory");
                    }//from w w  w .  j  a  va2s  .c  o  m

                    if (fieldObj != null) {
                        // Field error
                        bindingResult.rejectValue(fieldObj.toString(), "no_code", messageObj.toString());
                    } else {
                        // Global error
                        bindingResult.reject("no_code", messageObj.toString());
                    }

                }

            }

        }

    }

}

From source file:com.sf.springsecurityregistration1.web.controllers.AnnouncementDetailsController.java

/**
 * Method used to verify and persist the new announcement.
 *
 * @param status used to remove announcement from the session
 * @param announcement edited/* www . j av  a 2 s  .com*/
 * @param result used to search for errors in form
 * @param request for future code
 * @param errors for future code
 * @return model of next view (search for success, edit for errors)
 */
@RequestMapping(value = "/customer/announcement/create", method = { RequestMethod.POST })
public ModelAndView create(SessionStatus status, @Valid @ModelAttribute Announcements announcement,
        BindingResult result, WebRequest request, Errors errors) {
    String title = changeEncoding(announcement.getTitle(), pageEncoding, dbEncoding);
    announcement.setTitle(title);
    System.out.println("create " + title); // ISO-8859-1
    String header = changeEncoding(announcement.getHeader(), pageEncoding, dbEncoding);
    announcement.setHeader(header);
    String content = changeEncoding(announcement.getContent(), pageEncoding, dbEncoding);
    announcement.setContent(content);
    Announcements registered = null;
    if (!result.hasErrors() && !announcement.getHeader().equals("new")) {
        System.out.println("!result.hasErrors() ");
        registered = createAnnouncement(announcement, result);
    }
    if (registered == null) {
        System.out.println("registered == null");
        //            result.rejectValue("title", "message.title.error");

    }
    if (result.hasErrors()) {
        String titleErrorMessage = result.hasFieldErrors("title")
                ? result.getFieldError("title").getDefaultMessage()
                : "";
        System.out.println("result.hasErrors() " + titleErrorMessage);
        if (!titleErrorMessage.isEmpty()) {
            result.rejectValue("title", "message.title.error",
                    result.getFieldError("title").getDefaultMessage());
        }
        String contentErrorMessage = result.hasFieldErrors("content")
                ? result.getFieldError("content").getDefaultMessage()
                : "";
        if (!contentErrorMessage.isEmpty()) {
            result.rejectValue("content", "message.content.error",
                    result.getFieldError("content").getDefaultMessage());
        }
        ModelAndView model = new ModelAndView("/customer/announcement/create");
        model.addObject("announcements", announcement);
        return model;
        //            return "redirect:/customer/announcement/create";
    } else {
        if (announcement.getHeader().equals("new")) {
            int size = announcement.getNewHeader().length();
            if (size > 25 || 0 == size) {
                result.rejectValue("newHeader", "message.header.error");
                ModelAndView model = new ModelAndView("/customer/announcement/create");
                model.addObject("announcements", announcement);
                return model;
            }
            announcement.setHeader(changeEncoding(announcement.getNewHeader(), pageEncoding, dbEncoding));
            createAnnouncement(announcement, result);
        }
        ModelAndView model = new ModelAndView("/customer/announcement/search");
        //            model.addObject("announcements", announcement);
        model.addObject("announcementSearchCriteria", new AnnouncementSearchCriteria());
        model.addObject("categories", this.announcementService.findAllCategories());
        model.addObject("authors", this.announcementService.findAllAuthors());
        model.addObject("announcementsList",
                this.announcementService.findAnnouncements(new AnnouncementSearchCriteria()));
        status.setComplete();
        return model;
        //            return "redirect:/customer/announcement/search";
    }
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/app", method = RequestMethod.POST)
public String registerApp(ModelMap model, @ModelAttribute("application") Application application,
        @RequestParam("certificate") MultipartFile certificate, MultipartFile icon, BindingResult result,
        Authentication authentication) throws IOException {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());/*  w ww  .jav  a  2s.  c o m*/

    if (developer == null) {
        return "redirect:register_developer";
    } else {

        applicationValidator.validate(application, result);

        application.setRegistrationDate(new Date());
        application.setState(State.REGISTRATED);

        application.setDeveloper(developer);

        Application existingApp = appManagement.getApplicationByClientId(application.getClientId());

        if (existingApp != null) {
            result.rejectValue("clientId", "invalid.clientId",
                    "Klient id:et finns redan registrerat, var god vlj ett annat.");
        }

        // validate icon if it exists
        if (application.getIcon() != null && application.getIcon().length > 0) {
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon());
                BufferedImage bufferedImage = ImageIO.read(bis);
                log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight());
                application.setIconContentType(icon.getContentType());
                // TODO: Check width and height here!
            } catch (Exception e) {
                result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig");
            }
        }

        //For now we are just allowing the addition of just one certificate
        List<Certificate> certs = new ArrayList<>();

        if (certificate != null && certificate.getSize() > 0) {
            certs.add(createCertificate(certificate, result));
        }

        if (result.hasErrors()) {
            List<Permission> permissions = permissionServices.getAllPermissions();
            model.addAttribute("scopes", permissions);
            return "register_application";
        }

        Application savedApp = appManagement.registerApplication(application);

        for (Certificate cert : certs) {
            cert.setApplication(savedApp);
            appManagement.saveCertificate(cert);
            savedApp.getCertificates().add(cert);
        }

        try {
            log.debug("Composing message to: {}", mailAddress);
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            helper.setTo(mailAddress);
            helper.setFrom(new InternetAddress(mailFrom));

            log.debug("Creating message for existing app. User {} edited the app {}",
                    citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());
            helper.setSubject("Redigerad app: " + application.getName());
            helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: "
                    + application.getName());

            log.debug("Sending mail notification.");
            sender.send(message);
        } catch (Exception e) {
            log.error("Caught exception while trying to send email", e);
        }

        return "redirect:";
    }
}

From source file:org.openmrs.web.controller.concept.ConceptReferenceTermFormController.java

/**
 * Processes requests to save/update a concept reference term
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel the concept reference term object to save/update
 * @param result the {@link BindingResult} object
 * @return the url to redirect to/*from  ww w . j  ava 2  s .c  o m*/
 */
@RequestMapping(method = RequestMethod.POST, value = CONCEPT_REFERENCE_TERM_FORM_URL)
public String saveConceptReferenceTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel,
        BindingResult result) {

    ConceptReferenceTerm conceptReferenceTerm = conceptReferenceTermModel.getConceptReferenceTerm();
    // add all the term maps
    //store ids of already mapped terms so that we don't map a term multiple times
    Set<Integer> mappedTermIds = null;
    for (int x = 0; x < conceptReferenceTermModel.getTermMaps().size(); x++) {
        if (mappedTermIds == null) {
            mappedTermIds = new HashSet<Integer>();
        }
        ConceptReferenceTermMap map = conceptReferenceTermModel.getTermMaps().get(x);

        if (map != null && map.getTermB() != null) {
            //skip past this mapping because its term is already in use by another mapping for this term
            if (!mappedTermIds.add(map.getTermB().getConceptReferenceTermId())) {
                continue;
            }

            if (request.getParameter("_termMaps[" + x + "].exists") == null) {
                // because of the _termMap[x].exists input name in the jsp, the value will be null for
                // deleted maps, remove the map.
                conceptReferenceTerm.removeConceptReferenceTermMap(map);
            } else {
                if (map.getConceptMapType() == null) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.error.mapTypeRequired",
                            "Concept Map Type is required");
                    log.warn("Concept Map Type is required");
                    break;
                } else if (map.getTermB().equals(conceptReferenceTerm)) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.map.sameTerm",
                            "Cannot map a concept reference term to itself");
                    log.warn("Cannot map a concept reference term to itself");
                    break;
                } else if (!conceptReferenceTerm.getConceptReferenceTermMaps().contains(map)) {
                    conceptReferenceTerm.addConceptReferenceTermMap(map);
                }
            }
        }
    }

    //if there are errors  with the term
    if (!result.hasErrors()) {
        try {
            result.pushNestedPath("conceptReferenceTerm");
            ValidationUtils.invokeValidator(new ConceptReferenceTermValidator(), conceptReferenceTerm, result);
            ValidationUtils.invokeValidator(new ConceptReferenceTermWebValidator(), conceptReferenceTerm,
                    result);
        } finally {
            result.popNestedPath();
        }
    }

    if (!result.hasErrors()) {
        try {
            conceptReferenceTerm = Context.getConceptService().saveConceptReferenceTerm(conceptReferenceTerm);
            if (log.isDebugEnabled()) {
                log.debug("Saved concept reference term: " + conceptReferenceTerm.toString());
            }
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ConceptReferenceTerm.saved",
                    WebRequest.SCOPE_SESSION);
            return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId="
                    + conceptReferenceTerm.getConceptReferenceTermId();
        } catch (APIException e) {
            log.error("Error while saving concept reference term", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "ConceptReferenceTerm.save.error",
                    WebRequest.SCOPE_SESSION);
        }
    }

    return CONCEPT_REFERENCE_TERM_FORM;
}

From source file:com.devnexus.ting.web.controller.RegisterController.java

@RequestMapping(value = "/s/registerPageTwo", method = RequestMethod.POST)
public String validateDetailsForm(HttpServletRequest request, Model model,
        @Valid RegistrationDetails registerForm, BindingResult result) {

    Event currentEvent = businessService.getCurrentEvent();
    EventSignup eventSignup = businessService.getEventSignup();
    PaymentMethod paymentMethod = PaymentMethod.PAYPAL;
    prepareHeader(currentEvent, model);//  w w w .j  a va 2s .  c  o  m
    model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup));
    model.addAttribute("registrationDetails", registerForm);
    registerForm.setFinalCost(getTotal(registerForm));
    registerForm.setEvent(currentEvent);

    if (result.hasErrors()) {
        return "register2";
    }

    for (int index = 0; index < registerForm.getOrderDetails().size(); index++) {
        TicketOrderDetail orderDetails = registerForm.getOrderDetails().get(index);

        TicketGroup ticketGroup = businessService.getTicketGroup(orderDetails.getTicketGroup());

        if (!com.google.common.base.Strings.isNullOrEmpty(orderDetails.getCouponCode())
                && ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0) {
            if (!hasCode(ticketGroup.getCouponCodes(), orderDetails.getCouponCode())) {
                result.addError(new FieldError("registrationDetails", "orderDetails[" + index + "].couponCode",
                        "Invalid Coupon Code."));
            }
        }

        if (StringUtils.isEmpty(orderDetails.getFirstName())) {
            result.rejectValue("orderDetails[" + index + "].firstName", "firstName.isRequired",
                    "First Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getLastName())) {
            result.rejectValue("orderDetails[" + index + "].lastName", "lastName.isRequired",
                    "Last Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getEmailAddress())) {
            result.rejectValue("orderDetails[" + index + "].emailAddress", "emailAddress.isReq uired",
                    "Email Address is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCity())) {
            result.rejectValue("orderDetails[" + index + "].city", "city.isRequired", "City is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getState())) {
            result.rejectValue("orderDetails[" + index + "].state", "state.isRequired", "State is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCountry())) {
            result.rejectValue("orderDetails[" + index + "].country", "country.isRequired",
                    "Country is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getJobTitle())) {
            result.rejectValue("orderDetails[" + index + "].jobTitle", "jobTitle.isRequired",
                    "Job Title is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCompany())) {
            result.rejectValue("orderDetails[" + index + "].company", "company.isRequired",
                    "Company is required.");
        }

    }

    if (result.hasErrors()) {

        return "register2";
    }

    for (TicketOrderDetail detail : registerForm.getOrderDetails()) {
        detail.setRegistration(registerForm);
    }

    switch (paymentMethod) {

    case INVOICE:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.REQUIRES_INVOICE);
        registerForm.setFinalCost(getTotal(registerForm));
        businessService.createPendingRegistrationForm(registerForm);
        return "index";
    case PAYPAL:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.PAYPAL_CREATED);
        registerForm.setFinalCost(getTotal(registerForm));
        registerForm = businessService.createPendingRegistrationForm(registerForm);
        String baseUrl = String.format("%s://%s:%d/", request.getScheme(), request.getServerName(),
                request.getServerPort());
        Payment createdPayment = runPayPal(registerForm, baseUrl);
        return "redirect:" + createdPayment.getLinks().stream().filter(link -> {
            return link.getRel().equals("approval_url");
        }).findFirst().get().getHref();
    default:
        throw new IllegalStateException("The system did not understand the payment type.");

    }

}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public ModelAndView editApp(ModelMap model, Authentication authentication,
        @ModelAttribute("application") Application application, MultipartFile icon,
        @RequestParam(value = "certificate", required = false) MultipartFile certificate,
        BindingResult result) {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());
    List<Permission> permissions = permissionServices.getAllPermissions();

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());/*from  w  w  w . ja va2 s  .c  o m*/

    if (developer == null) {
        return new ModelAndView("redirect:register_developer");
    } else {

        applicationValidator.validate(application, result);

        log.info("app id: " + application.getId());
        Application dbApp = appManagement.getApplication(application.getId());

        if (!user.getUsername().equals(dbApp.getDeveloper().getResidentIdentificationNumber())) {
            throw new IllegalArgumentException(
                    "The application developer is not the same as the logged in user");
        }

        if (application.getIcon() == null && dbApp.getIcon() != null && dbApp.getIcon().length > 0) {
            application.setIcon(dbApp.getIcon());
            log.debug("Icon wasn't updated this time around");
        } else if (application.getIcon() != null) {
            log.debug("Icon was updated");
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon());
                BufferedImage bufferedImage = ImageIO.read(bis);
                log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight());
                application.setIconContentType(icon.getContentType());
                // TODO: Check width and height here!
            } catch (Exception e) {
                result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig");
            }
        }

        application.setCertificates(dbApp.getCertificates());
        application.setRegistrationDate(dbApp.getRegistrationDate());
        application.setState(dbApp.getState());
        application.setDeveloper(developer);

        //For now we are just allowing the addition of just one certificate
        List<Certificate> certs = new ArrayList<>();

        if (certificate != null && certificate.getSize() > 0) {
            certs.add(createCertificate(certificate, result));
        }

        //Error handling
        if (result.hasErrors()) {
            model.addAttribute(application);
            model.addAttribute("scopes", permissions);
            return new ModelAndView("application/edit");
        }

        Application savedApp = appManagement.updateApplication(application);

        //Remove everything old.
        // Just allow one certificate to be set right now even though the model allows for more.
        //If this behavior is unwanted the GUI has to adapt for this as well as it only caters
        //for on certificate right now.
        if (certificate != null && certificate.getSize() > 0) {
            Set<Certificate> oldCerts = new HashSet<>();

            //Clone in order to not get a concurrent modification exception
            for (Certificate cert : savedApp.getCertificates()) {
                oldCerts.add(cert);
            }

            //Remove anything old
            for (Certificate cert : oldCerts) {
                cert.setApplication(null);
                savedApp.getCertificates().remove(cert);
                appManagement.removeCertificate(cert);
            }

            //Set the new Certificate
            for (Certificate cert : certs) {
                cert.setApplication(savedApp);
                appManagement.saveCertificate(cert);
                savedApp.getCertificates().add(cert);
            }
        }

        try {
            log.debug("Composing message to: {}", mailAddress);
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            helper.setTo(mailAddress);
            helper.setFrom(new InternetAddress(mailFrom));

            log.debug("Creating message for existing app. User {} edited the app {}",
                    citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());
            helper.setSubject("Redigerad app: " + application.getName());
            helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: "
                    + application.getName());

            log.debug("Sending mail notification.");
            sender.send(message);
        } catch (Exception e) {
            log.error("Caught exception while trying to send email", e);
        }
    }
    return new ModelAndView("redirect:/developer");
}

From source file:cec.easyshop.storefront.controllers.pages.checkout.steps.SopPaymentResponseController.java

@RequestMapping(value = "/response", method = RequestMethod.POST)
@RequireHardLogIn/*from  w  ww  .  ja v  a 2  s. co  m*/
public String doHandleSopResponse(final HttpServletRequest request,
        @Valid final SopPaymentDetailsForm sopPaymentDetailsForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    final Map<String, String> resultMap = getRequestParameterMap(request);

    final boolean savePaymentInfo = sopPaymentDetailsForm.isSavePaymentInfo()
            || getCheckoutCustomerStrategy().isAnonymousCheckout();
    final PaymentSubscriptionResultData paymentSubscriptionResultData = this.getPaymentFacade()
            .completeSopCreateSubscription(resultMap, savePaymentInfo);

    if (paymentSubscriptionResultData.isSuccess() && paymentSubscriptionResultData.getStoredCard() != null
            && StringUtils.isNotBlank(paymentSubscriptionResultData.getStoredCard().getSubscriptionId())) {
        final CCPaymentInfoData newPaymentSubscription = paymentSubscriptionResultData.getStoredCard();

        if (getUserFacade().getCCPaymentInfos(true).size() <= 1) {
            getUserFacade().setDefaultPaymentInfo(newPaymentSubscription);
        }
        getCheckoutFacade().setPaymentDetails(newPaymentSubscription.getId());
    } else if ((paymentSubscriptionResultData.getDecision() != null
            && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error"))
            || (paymentSubscriptionResultData.getErrors() != null
                    && !paymentSubscriptionResultData.getErrors().isEmpty())) {
        // Have SOP errors that we can display

        setupAddPaymentPage(model);

        // Build up the SOP form data and render page containing form
        try {
            setupSilentOrderPostPage(sopPaymentDetailsForm, model);
        } catch (final Exception e) {
            LOG.error("Failed to build beginCreateSubscription request", e);
            GlobalMessages.addErrorMessage(model,
                    "checkout.multi.paymentMethod.addPaymentDetails.generalError");
            return enterStep(model, redirectAttributes);
        }

        if (paymentSubscriptionResultData.getErrors() != null
                && !paymentSubscriptionResultData.getErrors().isEmpty()) {
            GlobalMessages.addErrorMessage(model, "checkout.error.paymentethod.formentry.invalid");
            // Add in specific errors for invalid fields
            for (final PaymentErrorField paymentErrorField : paymentSubscriptionResultData.getErrors()
                    .values()) {
                if (paymentErrorField.isMissing()) {
                    bindingResult.rejectValue(paymentErrorField.getName(),
                            "checkout.error.paymentethod.formentry.sop.missing." + paymentErrorField.getName(),
                            "Please enter a value for this field");
                }
                if (paymentErrorField.isInvalid()) {
                    bindingResult.rejectValue(paymentErrorField.getName(),
                            "checkout.error.paymentethod.formentry.sop.invalid." + paymentErrorField.getName(),
                            "This value is invalid for this field");
                }
            }
        } else if (paymentSubscriptionResultData.getDecision() != null
                && paymentSubscriptionResultData.getDecision().equalsIgnoreCase("error")) {
            LOG.error(
                    "Failed to create subscription. Error occurred while contacting external payment services.");
            GlobalMessages.addErrorMessage(model,
                    "checkout.multi.paymentMethod.addPaymentDetails.generalError");
        }

        return ControllerConstants.Views.Pages.MultiStepCheckout.SilentOrderPostPage;
    } else {
        // SOP ERROR!
        LOG.error("Failed to create subscription.  Please check the log files for more information");
        return REDIRECT_URL_ERROR + "/?decision=" + paymentSubscriptionResultData.getDecision() + "&reasonCode="
                + paymentSubscriptionResultData.getResultCode();
    }

    return getCheckoutStep().nextStep();
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {//  w  w  w  . jav a  2 s  . c o  m
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java

/**
 * Handles form submission/*from  www. j  a v  a  2  s .  co m*/
 * @param request the request
 * @param message the message
 * @param result the binding result
 * @param status the session status
 * @return the view
 * @throws IllegalStateException
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message,
        BindingResult result, SessionStatus status) throws IllegalStateException {

    DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
    MultipartFile file = req.getFile("sdmxhdMessage");
    File destFile = null;

    if (!(file.getSize() <= 0)) {
        AdministrationService as = Context.getAdministrationService();
        String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
        String filename = file.getOriginalFilename();
        filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
        destFile = new File(dir + File.separator + filename);
        destFile.mkdirs();

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            HttpSession session = request.getSession();
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
            return "/module/sdmxhdintegration/messageUpload";
        }

        message.setZipFilename(filename);
    }

    new SDMXHDMessageValidator().validate(message, result);

    if (result.hasErrors()) {
        log.error("SDMXHDMessage object failed validation");
        if (destFile != null) {
            destFile.delete();
        }
        return "/module/sdmxhdintegration/messageUpload";
    }

    SDMXHDService service = Context.getService(SDMXHDService.class);
    ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
    service.saveMessage(message);

    // delete all existing mappings and reports
    List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message);
    for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
        KeyFamilyMapping kfm = iterator.next();
        Integer reportDefinitionId = kfm.getReportDefinitionId();
        service.deleteKeyFamilyMapping(kfm);
        if (reportDefinitionId != null) {
            rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
        }
    }

    // create initial keyFamilyMappings
    try {
        DSD dsd = Utils.getDataSetDefinition(message);
        List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
        for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
            KeyFamily keyFamily = iterator.next();

            KeyFamilyMapping kfm = new KeyFamilyMapping();
            kfm.setKeyFamilyId(keyFamily.getId());
            kfm.setMessage(message);
            service.saveKeyFamilyMapping(kfm);
        }
    } catch (Exception e) {
        log.error("Error parsing SDMX-HD Message: " + e, e);
        if (destFile != null) {
            destFile.delete();
        }

        service.deleteMessage(message);
        result.rejectValue("sdmxhdZipFileName", "upload.file.rejected",
                "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
        return "/module/sdmxhdintegration/messageUpload";
    }

    return "redirect:messages.list";
}