Skip to content

Add ability to specify URL for an image #587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
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, Url.ADD_IMAGE_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
109 changes: 105 additions & 4 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,8 @@
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.dto.NullableImageUrl;
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 +75,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 +180,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 +222,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 @@ -242,14 +266,47 @@ public String showInfo(
return "series/info";
}

@PostMapping(Url.ADD_IMAGE_SERIES_PAGE)
@SuppressWarnings("checkstyle:parameternumber")
@PostMapping(path = Url.ADD_IMAGE_SERIES_PAGE, params = "imageUrl")
public String processImageWithImageUrl(
@Validated({
AddImageForm.ImageUrlChecks.class,
AddImageForm.ImageChecks.class
}) AddImageForm form,
BindingResult result,
@PathVariable("id") Integer seriesId,
Model model,
@CurrentUser Integer currentUserId,
Locale userLocale,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {

return processImage(
form,
result,
seriesId,
model,
currentUserId,
userLocale,
request,
response
);
}

@SuppressWarnings("checkstyle:parameternumber")
@PostMapping(path = Url.ADD_IMAGE_SERIES_PAGE, params = "!imageUrl")
public String processImage(
@Valid AddImageForm form,
@Validated({
AddImageForm.RequireImageCheck.class,
AddImageForm.ImageChecks.class })
AddImageForm form,
BindingResult result,
@PathVariable("id") Integer seriesId,
Model model,
@CurrentUser Integer currentUserId,
Locale userLocale,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {

Expand All @@ -265,6 +322,8 @@ public String processImage(
return null;
}

loadErrorsFromDownloadInterceptor(form, result, request);

boolean maxQuantityOfImagesExceeded = !isAdmin() && !isAllowedToAddingImages(series);
model.addAttribute("maxQuantityOfImagesExceeded", maxQuantityOfImagesExceeded);

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

private static void loadErrorsFromDownloadInterceptor(
NullableImageUrl 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.nullifyImageUrl();
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";
}

}
Loading