Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
/series/add: allow to specify image URL.
  • Loading branch information
php-coder committed Oct 1, 2017
commit 7fb62899c334c7ca096d8ec34111ce0c8b1ed7c7
1 change: 1 addition & 0 deletions NEWS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- (functionality) name of category/country in Russian now are optional fields
- (functionality) preview now is generated after uploading an image
- (functionality) add interface for adding buyers and sellers
- (functionality) add capability to specify image URL (as alternative to providing a file)

0.3
- (functionality) implemented possibility to user to add series to his collection
Expand Down
9 changes: 9 additions & 0 deletions src/main/config/findbugs-filter.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
<Class name="~.*\.dto\..*" />
<Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2" />
</Match>
<Match>
<!--
String[] allowedContentTypes: potentially caller can modify data after passing it to the
constructor. I don't want to fix it because all such places are known and under our
control.
-->
<Class name="ru.mystamps.web.service.HttpURLConnectionDownloaderService" />
<Bug pattern="EI_EXPOSE_REP2" />
</Match>
<Match>
<!--
It's ok, that we're don't override parent's equals() method.
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/ru/mystamps/web/config/ControllersConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import lombok.RequiredArgsConstructor;

Expand Down Expand Up @@ -131,4 +132,10 @@ public SuggestionController getSuggestionController() {
);
}

@Bean
@Profile({ "test", "travis" })
public TestController getTestController() {
return new TestController();
}

}
9 changes: 9 additions & 0 deletions src/main/java/ru/mystamps/web/config/MvcConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@

import ru.mystamps.web.Url;
import ru.mystamps.web.controller.converter.LinkEntityDtoGenericConverter;
import ru.mystamps.web.controller.interceptor.DownloadImageInterceptor;
import ru.mystamps.web.support.spring.security.CurrentUserArgumentResolver;

@Configuration
Expand Down Expand Up @@ -126,6 +127,10 @@ public Validator getValidator() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getLocaleChangeInterceptor());

registry
.addInterceptor(getDownloadImageInterceptor())
.addPathPatterns(Url.ADD_SERIES_PAGE);
}

@Override
Expand All @@ -149,4 +154,8 @@ private static HandlerInterceptor getLocaleChangeInterceptor() {
return interceptor;
}

private HandlerInterceptor getDownloadImageInterceptor() {
return new DownloadImageInterceptor(servicesConfig.getDownloaderService());
}

}
5 changes: 5 additions & 0 deletions src/main/java/ru/mystamps/web/config/ServicesConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ public CronService getCronService() {
);
}

@Bean
public DownloaderService getDownloaderService() {
return new HttpURLConnectionDownloaderService(new String[]{"image/jpeg", "image/png"});
}

@Bean
public ImageService getImageService() {
return new ImageServiceImpl(
Expand Down
69 changes: 67 additions & 2 deletions src/main/java/ru/mystamps/web/controller/SeriesController.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.groups.Default;
Expand Down Expand Up @@ -62,6 +63,7 @@
import ru.mystamps.web.controller.dto.AddImageForm;
import ru.mystamps.web.controller.dto.AddSeriesForm;
import ru.mystamps.web.controller.dto.AddSeriesSalesForm;
import ru.mystamps.web.controller.interceptor.DownloadImageInterceptor;
import ru.mystamps.web.dao.dto.EntityWithIdDto;
import ru.mystamps.web.dao.dto.LinkEntityDto;
import ru.mystamps.web.dao.dto.PurchaseAndSaleDto;
Expand All @@ -72,6 +74,7 @@
import ru.mystamps.web.service.SeriesSalesService;
import ru.mystamps.web.service.SeriesService;
import ru.mystamps.web.service.TransactionParticipantService;
import ru.mystamps.web.service.dto.DownloadResult;
import ru.mystamps.web.service.dto.FirstLevelCategoryDto;
import ru.mystamps.web.service.dto.SeriesDto;
import ru.mystamps.web.support.spring.security.Authority;
Expand Down Expand Up @@ -176,15 +179,34 @@ public View showFormWithCountry(
return view;
}

@PostMapping(Url.ADD_SERIES_PAGE)
@PostMapping(path = Url.ADD_SERIES_PAGE, params = "imageUrl")
public String processInputWithImageUrl(
@Validated({ Default.class,
AddSeriesForm.ImageUrlChecks.class,
AddSeriesForm.ReleaseDateChecks.class,
AddSeriesForm.ImageChecks.class }) AddSeriesForm form,
BindingResult result,
@CurrentUser Integer currentUserId,
Locale userLocale,
Model model,
HttpServletRequest request) {

return processInput(form, result, currentUserId, userLocale, model, request);
}

@PostMapping(path = Url.ADD_SERIES_PAGE, params = "!imageUrl")
public String processInput(
@Validated({ Default.class,
AddSeriesForm.RequireImageCheck.class,
AddSeriesForm.ReleaseDateChecks.class,
AddSeriesForm.ImageChecks.class }) AddSeriesForm form,
BindingResult result,
@CurrentUser Integer currentUserId,
Locale userLocale,
Model model) {
Model model,
HttpServletRequest request) {

loadErrorsFromDownloadInterceptor(form, result, request);

if (result.hasErrors()) {
String lang = LocaleUtils.getLanguageOrNull(userLocale);
Expand All @@ -199,6 +221,7 @@ public String processInput(

// don't try to re-display file upload field
form.setImage(null);
form.setDownloadedImage(null);
return null;
}

Expand Down Expand Up @@ -475,6 +498,48 @@ private void addSeriesSalesFormToModel(Model model) {
model.addAttribute("buyers", buyers);
}

private static void loadErrorsFromDownloadInterceptor(
AddSeriesForm form,
BindingResult result,
HttpServletRequest request) {

Object downloadResultErrorCode =
request.getAttribute(DownloadImageInterceptor.ERROR_CODE_ATTR_NAME);

if (downloadResultErrorCode == null) {
return;
}

if (downloadResultErrorCode instanceof DownloadResult.Code) {
DownloadResult.Code code = (DownloadResult.Code)downloadResultErrorCode;
switch (code) {
case INVALID_URL:
// Url is being validated by @URL, to avoid showing an error message
// twice we're skipping error from an interceptor.
break;
case INSUFFICIENT_PERMISSIONS:
// A user without permissions has tried to download a file. It means that he
// didn't specify a file but somehow provide a URL to an image. In this case,
// let's show an error message that file is required.
result.rejectValue(
"image",
"ru.mystamps.web.support.beanvalidation.NotEmptyFilename.message"
);
form.setImageUrl(null);
break;
default:
result.rejectValue(
DownloadImageInterceptor.DOWNLOADED_IMAGE_FIELD_NAME,
DownloadResult.class.getName() + "." + code.toString(),
"Could not download image"
);
break;
}
}

request.removeAttribute(DownloadImageInterceptor.ERROR_CODE_ATTR_NAME);
}

private static void addImageFormToModel(Model model) {
AddImageForm form = new AddImageForm();
model.addAttribute("addImageForm", form);
Expand Down
61 changes: 61 additions & 0 deletions src/main/java/ru/mystamps/web/controller/TestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2009-2017 Slava Semushin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ru.mystamps.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ru.mystamps.web.Url;

@Controller
public class TestController {

@GetMapping("/test/invalid/response-301")
public void redirect(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", Url.SITE);
}

@GetMapping("/test/invalid/response-400")
public void badRequest(HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}

@GetMapping("/test/invalid/response-404")
public void notFound(HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

@GetMapping("/test/invalid/empty-jpeg-file")
public void emptyJpegFile(HttpServletResponse response) {
response.setContentType("image/jpeg");
response.setContentLength(0);
}

@GetMapping(path = "/test/invalid/not-image-file", produces = "application/json")
@ResponseBody
public String simpleJson() {
return "test";
}

}
75 changes: 64 additions & 11 deletions src/main/java/ru/mystamps/web/controller/dto/AddSeriesForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.StringUtils;

import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL;

import org.springframework.web.multipart.MultipartFile;

Expand All @@ -37,6 +40,7 @@
import ru.mystamps.web.dao.dto.LinkEntityDto;
import ru.mystamps.web.service.dto.AddSeriesDto;
import ru.mystamps.web.support.beanvalidation.CatalogNumbers;
import ru.mystamps.web.support.beanvalidation.HasImageOrImageUrl;
import ru.mystamps.web.support.beanvalidation.ImageFile;
import ru.mystamps.web.support.beanvalidation.MaxFileSize;
import ru.mystamps.web.support.beanvalidation.MaxFileSize.Unit;
Expand All @@ -45,6 +49,7 @@
import ru.mystamps.web.support.beanvalidation.NotNullIfFirstField;
import ru.mystamps.web.support.beanvalidation.Price;
import ru.mystamps.web.support.beanvalidation.ReleaseDateIsNotInFuture;
import ru.mystamps.web.support.beanvalidation.RequireImageOrImageUrl;

import static ru.mystamps.web.validation.ValidationRules.MAX_DAYS_IN_MONTH;
import static ru.mystamps.web.validation.ValidationRules.MAX_IMAGE_SIZE;
Expand All @@ -58,6 +63,7 @@
@Setter
// TODO: combine price with currency to separate class
@SuppressWarnings({ "PMD.TooManyFields", "PMD.AvoidDuplicateLiterals" })
@RequireImageOrImageUrl(groups = AddSeriesForm.ImageUrl1Checks.class)
@NotNullIfFirstField.List({
@NotNullIfFirstField(
first = "month", second = "year", message = "{month.requires.year}",
Expand All @@ -69,7 +75,7 @@
)
})
@ReleaseDateIsNotInFuture(groups = AddSeriesForm.ReleaseDate3Checks.class)
public class AddSeriesForm implements AddSeriesDto {
public class AddSeriesForm implements AddSeriesDto, HasImageOrImageUrl {

// FIXME: change type to plain Integer
@NotNull
Expand Down Expand Up @@ -128,13 +134,48 @@ public class AddSeriesForm implements AddSeriesDto {
@Size(max = MAX_SERIES_COMMENT_LENGTH, message = "{value.too-long}")
private String comment;

@NotNull
@NotEmptyFilename(groups = Image1Checks.class)
@NotEmptyFile(groups = Image2Checks.class)
@MaxFileSize(value = MAX_IMAGE_SIZE, unit = Unit.Kbytes, groups = Image3Checks.class)
@ImageFile(groups = Image3Checks.class)
// Name of this field should match with the value of
// DownloadImageInterceptor.UPLOADED_IMAGE_FIELD_NAME.
@NotEmptyFilename(groups = RequireImageCheck.class)
@NotEmptyFile(groups = Image1Checks.class)
@MaxFileSize(value = MAX_IMAGE_SIZE, unit = Unit.Kbytes, groups = Image2Checks.class)
@ImageFile(groups = Image2Checks.class)
private MultipartFile image;

// Name of this field must match with the value of DownloadImageInterceptor.URL_PARAMETER_NAME.
@URL(groups = ImageUrl2Checks.class)
private String imageUrl;

// This field holds a file that was downloaded from imageUrl.
// Name of this field must match with the value of
// DownloadImageInterceptor.DOWNLOADED_IMAGE_FIELD_NAME.
@NotEmptyFile(groups = Image1Checks.class)
@MaxFileSize(value = MAX_IMAGE_SIZE, unit = Unit.Kbytes, groups = Image2Checks.class)
@ImageFile(groups = Image2Checks.class)
private MultipartFile downloadedImage;

@Override
public MultipartFile getImage() {
if (hasImage()) {
return image;
}

return downloadedImage;
}

// This method has to be implemented to satisfy HasImageOrImageUrl requirements.
// The latter is being used by RequireImageOrImageUrl validator.
@Override
public boolean hasImage() {
return image != null && StringUtils.isNotEmpty(image.getOriginalFilename());
}

// This method has to be implemented to satisfy HasImageOrImageUrl requirements.
// The latter is being used by RequireImageOrImageUrl validator.
@Override
public boolean hasImageUrl() {
return StringUtils.isNotEmpty(imageUrl);
}

@GroupSequence({
ReleaseDate1Checks.class,
Expand All @@ -153,10 +194,25 @@ public interface ReleaseDate2Checks {
public interface ReleaseDate3Checks {
}

public interface RequireImageCheck {
}

@GroupSequence({
ImageUrl1Checks.class,
ImageUrl2Checks.class,
})
public interface ImageUrlChecks {
}

public interface ImageUrl1Checks {
}

public interface ImageUrl2Checks {
}

@GroupSequence({
Image1Checks.class,
Image2Checks.class,
Image3Checks.class
Image2Checks.class
})
public interface ImageChecks {
}
Expand All @@ -167,7 +223,4 @@ public interface Image1Checks {
public interface Image2Checks {
}

public interface Image3Checks {
}

}
Loading