Search in sources :

Example 11 with Valid

use of javax.validation.Valid in project vboard by voyages-sncf-technologies.

the class MessagesController method addMessage.

// Add a new displayable message
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
@Valid
public Message addMessage(@Valid @RequestBody MessageParams params) {
    final String content = params.getContent();
    final String type = params.getType();
    permission.ensureCurrentUserIsAdmin();
    final Message message = new Message(type, content);
    try {
        this.logger.debug("addMessage: author={} - type={} -content={}", permission.getSessionUser().getUserString(), type, content);
        // Find the previous active message (if one if found)
        final Message previousMessage = this.messageDAO.findByActive(true);
        if (previousMessage != null) {
            // Deactivate the previous active message
            previousMessage.setActive(false);
            this.messageDAO.save(previousMessage);
        }
        this.messageDAO.save(message);
    } catch (UnexpectedRollbackException e) {
        throw new VBoardException(e.getMessage(), e.getMostSpecificCause());
    }
    return message;
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) Valid(javax.validation.Valid)

Example 12 with Valid

use of javax.validation.Valid in project vboard by voyages-sncf-technologies.

the class MessagesController method sendEmailsNL.

// Send an email of the newsletter
@RequestMapping(value = "/sendEmails/nl", method = RequestMethod.POST)
@ResponseBody
@Valid
public void sendEmailsNL(@Valid @RequestBody EmailParams emailParams) {
    permission.ensureUserHasNewsletterRole();
    DateTime lastNLDate = new DateTime(this.getLastNL().getPostDateUTC());
    if (lastNLDate.plusMinutes(10).isBeforeNow()) {
        // Prevent the newsletter to be sent twice withing 10 minutes
        this.sendNLEmailsToAll(emailParams, /*test=*/
        false);
        this.logger.debug("Newsletter email not sent");
    } else {
        this.logger.debug("Newsletter email test not sent: last NL sent to recently");
    }
}
Also used : DateTime(org.joda.time.DateTime) Valid(javax.validation.Valid)

Example 13 with Valid

use of javax.validation.Valid in project vboard by voyages-sncf-technologies.

the class PinsController method addNewPinVblog.

// Post pins from Vblog (wordpress) (see previous method)
@RequestMapping(value = "/vblog", method = RequestMethod.POST, consumes = { "application/x-www-form-urlencoded" })
@ResponseBody
@Valid
public Pin addNewPinVblog(@RequestParam("title") final String title, @RequestParam("url") final String url, @RequestParam("imgType") String imgType, @RequestParam("description") final String description, @RequestParam("labels") String labels, @RequestParam("author") String author, @RequestParam("ID") final String ID) {
    // TODO only authorize wordpress (vblog) to access that url/method
    if (!this.isMediaInternetImage(imgType)) {
        imgType = null;
    }
    if (isNotBlank(labels)) {
        labels = "#" + labels;
    }
    User user = this.userDAO.findByEmail(author);
    if (user != null) {
        author = user.getUserString();
    }
    Pin pin = this.pinDAO.findByPinId("vblog-" + ID);
    if (pin == null) {
        DateTime postDateUTC = new DateTime(DateTimeZone.UTC);
        pin = new Pin("vblog-" + ID, title, url, 0, imgType, labels, description, author, postDateUTC);
    } else {
        pin.setPinTitle(title);
        pin.setHrefUrl(url);
        pin.setImgType(imgType);
        pin.setLabels(labels);
        pin.setIndexableTextContent(description);
        pin.setAuthor(author);
    }
    try {
        this.logger.debug("addNewPinVblog: pinId= vblog-{} title={} - url={} - likes=0 - imgType={} - description={} - labels={} - author={}", ID, title, url, imgType, description, labels, author);
        pin = this.pinDAO.save(pin);
        this.elsClient.updatePin(pin);
    } catch (UnexpectedRollbackException e) {
        throw new VBoardException(e.getMessage(), e.getMostSpecificCause());
    }
    // Add the new labels in the list of labels
    if (isNotBlank(labels)) {
        List<String> pinLabels = Arrays.asList(labels.split(","));
        pinLabels.forEach(l -> this.labelDAO.save(new Label(l)));
    }
    if (this.isMediaInternetImage(imgType)) {
        uploadsManager.savePinImage(imgType, pin.getPinId());
    }
    if (user != null) {
        this.gamification.updateStats(user);
    }
    return pin;
}
Also used : UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) DateTime(org.joda.time.DateTime) Valid(javax.validation.Valid)

Example 14 with Valid

use of javax.validation.Valid in project vboard by voyages-sncf-technologies.

the class PinsController method addNewPin.

@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
@Valid
public // Parsing the params in the JSON body requires using a dedicated @RequestBody annotated class instead of simple @RequestParam arguments
Pin addNewPin(@Valid @RequestBody AddNewPinParams params) {
    Pin retval;
    // Save
    String title = params.getTitle();
    String url = params.getUrl();
    String imgType = params.getImgType();
    if (isNotBlank(url) && !uploadsManager.isMultiplePinsPerUrlAllowed()) {
        List<Pin> existingPins = this.pinDAO.findByHrefUrl(url);
        if (!existingPins.isEmpty()) {
            throw new DuplicateContentException("Existing pin already exist for this URL: " + existingPins.stream().map(pin -> "[ID=" + pin.getPinId() + " creationDate=" + pin.getPostDateUTC() + "]").collect(Collectors.joining()));
        }
    }
    String description = params.getDescription();
    String[] labels = params.getLabels();
    String strLabels = labels == null || labels.length == 0 ? "" : Arrays.stream(params.getLabels()).map(label -> label.startsWith("#") ? label : "#" + label).collect(Collectors.joining(","));
    String author = params.getAuthor();
    // Check if the author given is effectively the one that posted the pin
    permission.ensureNewEntityAuthorMatchesSessionUser(author);
    DateTime postDateUTC = new DateTime(DateTimeZone.UTC);
    Pin newPin = new Pin(title, url, 0, imgType, strLabels, description, author, postDateUTC);
    // If the media is an image (!<iframe) and is a base64image (custom) (version compatibility) the image points out on its localisation (relative url)
    if (this.isMediaBase64Image(imgType)) {
        String nasURL = "/pinImg/" + newPin.getPinId() + ".png";
        newPin.setImgType(nasURL);
    }
    // If the media is a video, the content is set as it is
    if (this.isMediaVideo(imgType)) {
        newPin.setImgType(imgType);
    }
    try {
        this.logger.debug("addNewPin: title={} - url={} - imgType={} - description={} - labels={} - author={}", title, url, newPin.getImgType(), description, strLabels, author);
        retval = this.pinDAO.save(newPin);
        this.elsClient.addPin(newPin);
        // If the image given is not a video (iframe) and exists, the image is saved (if not url, see inside the method) in the NAS
        if (this.isMediaBase64Image(params.getImgType()) || this.isMediaInternetImage(params.getImgType())) {
            uploadsManager.savePinImage(params.getImgType(), retval.getPinId());
        }
        // Update the stats
        this.gamification.updateStats(permission.getSessionUser());
    } catch (UnexpectedRollbackException e) {
        throw new VBoardException(e.getMessage(), e.getMostSpecificCause());
    }
    // Send a notification
    this.notifications.addNotificationsFromPin(newPin.getPinId(), "a ajouté une épingle avec un label que vous suivez");
    // Add the new labels in the list of labels
    if (isNotBlank(strLabels)) {
        List<String> pinLabels = Arrays.asList(strLabels.split(","));
        pinLabels.forEach(l -> this.labelDAO.save(new Label(l)));
    }
    return retval;
}
Also used : DateTimeZone(org.joda.time.DateTimeZone) SSLContext(javax.net.ssl.SSLContext) java.util(java.util) URL(java.net.URL) DAO(com.vsct.vboard.DAO) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) TrustManager(javax.net.ssl.TrustManager) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) Valid(javax.validation.Valid) Matcher(java.util.regex.Matcher) JavaUtils(com.vsct.vboard.utils.JavaUtils) AddNewPinParams(com.vsct.vboard.parameterFormat.AddNewPinParams) com.vsct.vboard.services(com.vsct.vboard.services) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) ProxyConfig(com.vsct.vboard.config.ProxyConfig) UTF_8(java.nio.charset.StandardCharsets.UTF_8) DateTime(org.joda.time.DateTime) JSONObject(org.codehaus.jettison.json.JSONObject) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) JSONException(org.codehaus.jettison.json.JSONException) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) com.vsct.vboard.models(com.vsct.vboard.models) DuplicateContentException(com.vsct.vboard.exceptions.DuplicateContentException) DuplicateContentException(com.vsct.vboard.exceptions.DuplicateContentException) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) DateTime(org.joda.time.DateTime) Valid(javax.validation.Valid)

Example 15 with Valid

use of javax.validation.Valid in project vboard by voyages-sncf-technologies.

the class SavedPinController method deleteSavedPin.

// Delete the current pin (current user)
@RequestMapping(value = "/{pin_id}", method = RequestMethod.DELETE)
@ResponseBody
@Valid
public void deleteSavedPin(@PathVariable("pin_id") String pinId) {
    SavedPin savedPin = this.savedPinDAO.findById(pinId + permission.getSessionUser().getEmail()).orElse(null);
    this.savedPinDAO.delete(savedPin);
    this.gamification.updateStats(permission.getSessionUser());
    this.logger.debug("savedPin {} deleted by: {}", pinId, permission.getSessionUser().getUserString());
}
Also used : SavedPin(com.vsct.vboard.models.SavedPin) Valid(javax.validation.Valid)

Aggregations

Valid (javax.validation.Valid)59 Response (javax.ws.rs.core.Response)14 Logger (org.slf4j.Logger)14 LoggerFactory (org.slf4j.LoggerFactory)14 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)14 List (java.util.List)12 java.util (java.util)11 Autowired (org.springframework.beans.factory.annotation.Autowired)11 Timed (com.codahale.metrics.annotation.Timed)10 User (com.vsct.vboard.models.User)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 Path (javax.ws.rs.Path)10 Produces (javax.ws.rs.Produces)10 DateTime (org.joda.time.DateTime)10 VBoardException (com.vsct.vboard.models.VBoardException)9 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 Optional (java.util.Optional)9 Collectors (java.util.stream.Collectors)9 Collectors.toList (java.util.stream.Collectors.toList)9