Conflicts:
	pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java
	pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java
	pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java
	pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java
This commit is contained in:
michal_aibin 2016-11-03 12:01:28 +01:00
commit 3eb57fa478
46 changed files with 1074 additions and 43 deletions

View File

@ -0,0 +1,46 @@
package com.baeldung.hexToAscii;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HexToAscii {
@Test
public static void whenHexToAscii() {
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
assertEquals(asciiString, hexToAscii(hexEquivalent));
}
@Test
public static void whenAsciiToHex() {
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
assertEquals(hexEquivalent, asciiToHex(asciiString));
}
//
private static String asciiToHex(String asciiStr) {
char[] chars = asciiStr.toCharArray();
StringBuilder hex = new StringBuilder();
for (char ch : chars) {
hex.append(Integer.toHexString((int) ch));
}
return hex.toString();
}
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
}

View File

@ -17,6 +17,11 @@ public class EchoClient {
return instance;
}
public static void stop() throws IOException {
client.close();
buffer = null;
}
private EchoClient() {
try {
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
@ -42,5 +47,4 @@ public class EchoClient {
return response;
}
}

View File

@ -1,21 +1,19 @@
package com.baeldung.java.nio.selector;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.Set;
import java.util.Iterator;
import java.net.InetSocketAddress;
import java.io.File;
import java.util.Set;
public class EchoServer {
public static void main(String[] args)
throws IOException {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", 5454));
@ -49,7 +47,6 @@ public class EchoServer {
}
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";

View File

@ -4,19 +4,32 @@ import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NioEchoIntegrationTest {
Process server;
EchoClient client;
@Before
public void setup() throws IOException, InterruptedException {
server = EchoServer.start();
client = EchoClient.start();
}
@Test
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
Process process = EchoServer.start();
EchoClient client = EchoClient.start();
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
assertEquals("world", resp2);
}
process.destroy();
@After
public void teardown() throws IOException {
server.destroy();
EchoClient.stop();
}
}

View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<modules>
<module>spring-dispatcher-servlet</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -3,6 +3,7 @@ package com.baeldung.patterns.intercepting.filter.commands;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
public class LoginCommand extends FrontCommand {
@Override
@ -12,10 +13,8 @@ public class LoginCommand extends FrontCommand {
session.setAttribute("username", request.getParameter("username"));
response.sendRedirect(request.getParameter("redirect"));
} else {
String queryString = request.getQueryString();
if (queryString == null) {
queryString = "command=Home";
}
String queryString = Optional.ofNullable(request.getQueryString())
.orElse("command=Home");
request.setAttribute("redirect", request.getRequestURL()
.append("?").append(queryString).toString());
forward("login");

View File

@ -3,14 +3,17 @@ package com.baeldung.patterns.intercepting.filter.commands;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
public class LogoutCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
super.process();
HttpSession session = request.getSession(false);
session.removeAttribute("username");
session.removeAttribute("order");
Optional.ofNullable(request.getSession(false))
.ifPresent(session -> {
session.removeAttribute("username");
session.removeAttribute("order");
});
response.sendRedirect("/?command=Home");
}
}

View File

@ -8,6 +8,7 @@ import com.baeldung.patterns.intercepting.filter.data.OrderImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
public class OrderCommand extends FrontCommand {
@Override
@ -15,11 +16,10 @@ public class OrderCommand extends FrontCommand {
super.process();
if (request.getMethod().equals("POST")) {
HttpSession session = request.getSession(false);
Order order = (Order) session.getAttribute("order");
if (order == null) {
String username = (String) session.getAttribute("username");
order = new OrderImpl(username);
}
Order order = Optional
.ofNullable(session.getAttribute("order"))
.map(Order.class::cast)
.orElseGet(() -> new OrderImpl((String) session.getAttribute("username")));
Bookshelf bookshelf = (Bookshelf) request.getServletContext()
.getAttribute("bookshelf");
String isbn = request.getParameter("isbn");

View File

@ -4,6 +4,7 @@ import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
import java.util.Optional;
@WebFilter(
servletNames = {"intercepting-filter"},
@ -24,10 +25,9 @@ public class EncodingFilter extends BaseFilter {
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
String encoding = request.getParameter("encoding");
if (encoding == null) {
encoding = this.encoding;
}
String encoding = Optional
.ofNullable(request.getParameter("encoding"))
.orElse(this.encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}

View File

@ -10,6 +10,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Optional;
@WebFilter(servletNames = "intercepting-filter")
public class LoggingFilter extends BaseFilter {
@ -23,10 +24,10 @@ public class LoggingFilter extends BaseFilter {
) throws IOException, ServletException {
chain.doFilter(request, response);
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String username = (String) httpServletRequest.getAttribute("username");
if (username == null) {
username = "guest";
}
String username = Optional
.ofNullable(httpServletRequest.getAttribute("username"))
.map(Object::toString)
.orElse("guest");
log.info("Request from '{}@{}': {}?{}", username, request.getRemoteAddr(),
httpServletRequest.getRequestURI(), request.getParameterMap());
}

View File

@ -5,6 +5,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class VisitorCounterFilter implements Filter {
@ -21,8 +22,9 @@ public class VisitorCounterFilter implements Filter {
FilterChain chain
) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession(false);
String username = (String) session.getAttribute("username");
users.add(username);
Optional.ofNullable(session.getAttribute("username"))
.map(Object::toString)
.ifPresent(users::add);
request.setAttribute("counter", users.size());
chain.doFilter(request, response);
}

View File

@ -95,6 +95,7 @@
<module>spring-data-neo4j</module>
<module>spring-data-redis</module>
<module>spring-data-rest</module>
<module>spring-dispatcher-servlet</module>
<module>spring-exceptions</module>
<module>spring-freemarker</module>
<module>spring-hibernate3</module>

View File

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-dispatcher-servlet</artifactId>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.12.v20160915</version>
<configuration>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,19 @@
package com.baeldung.spring.dispatcher.servlet;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.*;
@Configuration
public class RootConfiguration {
@Bean
public Map<String, List<Task>> taskList() {
Map<String, List<Task>> taskMap = new HashMap<>();
List<Task> taskList = new ArrayList<>();
taskList.add(new Task("Clean the dishes!", new Date()));
taskMap.put("Cid", taskList);
return taskMap;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.spring.dispatcher.servlet;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebApplicationInitializer implements org.springframework.web.WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext webContext =
new AnnotationConfigWebApplicationContext();
webContext.register(WebConfiguration.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
dispatcherServlet);
servlet.addMapping("/*");
MultipartConfigElement multipartConfigElement =
new MultipartConfigElement("/tmp");
servlet.setMultipartConfig(multipartConfigElement);
}
}

View File

@ -0,0 +1,129 @@
package com.baeldung.spring.dispatcher.servlet;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import org.springframework.web.servlet.theme.CookieThemeResolver;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext;
import java.util.Locale;
@Configuration
@ComponentScan("com.baeldung.spring.dispatcher.servlet.web")
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/public/**")
.addResourceLocations("/public/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(themeChangeInterceptor());
}
@Bean
public ServletContextTemplateResolver templateResolver(ServletContext servletContext) {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(ServletContextTemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setFallbackToSystemLocale(false);
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(Locale.ENGLISH);
localeResolver.setCookieName("locale");
localeResolver.setCookieMaxAge(-1);
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
localeChangeInterceptor.setIgnoreInvalidLocale(true);
return localeChangeInterceptor;
}
@Bean
public ResourceBundleThemeSource themeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setBasenamePrefix("theme-");
themeSource.setFallbackToSystemLocale(false);
return themeSource;
}
@Bean
public ThemeResolver themeResolver() {
CookieThemeResolver themeResolver = new CookieThemeResolver();
themeResolver.setDefaultThemeName("robotask");
themeResolver.setCookieName("theme");
themeResolver.setCookieMaxAge(-1);
return themeResolver;
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
themeChangeInterceptor.setParamName("theme");
return themeChangeInterceptor;
}
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
@Bean
public HandlerExceptionResolver handlerExceptionResolver() {
return new ExceptionHandlerExceptionResolver();
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.spring.dispatcher.servlet.models;
import java.util.UUID;
public class Attachment {
private String id;
private String name;
private String description;
public Attachment() {
this.id = UUID.randomUUID().toString();
}
public Attachment(String name, String description) {
this();
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attachment that = (Attachment) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.spring.dispatcher.servlet.models;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Task {
private String description;
@DateTimeFormat(pattern = "yyyy-MM-dd'T'hh:mm")
private Date due;
private Set<Attachment> attachments = new HashSet<>();
public Task() {
}
public Task(Date due) {
this.due = due;
}
public Task(String description, Date due) {
this.description = description;
this.due = due;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDue() {
return due;
}
public void setDue(Date due) {
this.due = due;
}
public Set<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(Set<Attachment> attachments) {
this.attachments = attachments;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/attachments")
public interface AttachmentController {
@GetMapping("/{attachmentId}")
ResponseEntity<FileSystemResource> getAttachment(
@PathVariable("attachmentId") String attachmentId,
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
);
}

View File

@ -0,0 +1,45 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.net.URLConnection;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@Controller
public class AttachmentControllerImpl implements AttachmentController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public ResponseEntity<FileSystemResource> getAttachment(
@PathVariable("attachmentId") String attachmentId,
@RequestParam(name = "download", required = false, defaultValue = "false") boolean forcedDownload
) {
FileSystemResource resource = new FileSystemResource("/tmp/" + attachmentId);
HttpHeaders headers = new HttpHeaders();
taskMap.values().stream()
.flatMap(Collection::stream)
.flatMap(t -> t.getAttachments().stream())
.filter(a -> a.getId().equals(attachmentId))
.findFirst()
.ifPresent(a -> {
headers.add("Content-Disposition",
"attachment; filename=" + a.getName());
headers.add("Content-Type", forcedDownload ?
MediaType.APPLICATION_OCTET_STREAM_VALUE :
URLConnection.guessContentTypeFromName(a.getName()));
});
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.dispatcher.servlet.web;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/")
public interface HomeController {
@GetMapping("/*")
String home(
Model model
);
}

View File

@ -0,0 +1,25 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Controller
public class HomeControllerImpl implements HomeController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public String home(Model model) {
List<String> users = taskMap.keySet().stream()
.sorted()
.collect(Collectors.toList());
model.addAttribute("users", users);
return "home";
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/tasks")
public interface TaskController {
@GetMapping("/{username}/list")
String listTasks(
@PathVariable("username") String username,
Model model
);
@GetMapping("/{username}/add")
String addTask(
@PathVariable("username") String username,
Model model
);
@PostMapping("/{username}/add")
String addTask(
@PathVariable("username") String username,
@ModelAttribute Task task
);
@GetMapping("/{username}/get/{id}")
String getTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
);
@GetMapping("/{username}/get/{id}/attach")
String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
);
@PostMapping("/{username}/get/{id}/attach")
String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
@RequestParam("attachment") MultipartFile attachment,
@RequestParam("description") String description
);
}

View File

@ -0,0 +1,111 @@
package com.baeldung.spring.dispatcher.servlet.web;
import com.baeldung.spring.dispatcher.servlet.models.Attachment;
import com.baeldung.spring.dispatcher.servlet.models.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
@Controller
public class TaskControllerImpl implements TaskController {
@Autowired
private Map<String, List<Task>> taskMap;
@Override
public String listTasks(
@PathVariable("username") String username,
Model model
) {
List<Task> tasks = taskMap.get(username).stream()
.sorted(Comparator.comparing(Task::getDue))
.collect(Collectors.toList());
model.addAttribute("username", username);
model.addAttribute("tasks", tasks);
return "task-list";
}
@Override
public String addTask(
@PathVariable("username") String username,
Model model
) {
model.addAttribute("username", username);
model.addAttribute("task", new Task(new Date()));
return "task-add";
}
@Override
public String addTask(
@PathVariable("username") String username,
@ModelAttribute Task task
) {
List<Task> taskList = taskMap.get(username);
if (taskList == null) {
taskList = new ArrayList<>();
}
taskList.add(task);
taskMap.put(username, taskList);
return "redirect:list";
}
@Override
public String getTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
) {
Task task = taskMap.get(username).get(id);
model.addAttribute("username", username);
model.addAttribute("id", id);
model.addAttribute("task", task);
return "task-get";
}
@Override
public String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
Model model
) {
model.addAttribute("username", username);
model.addAttribute("id", id);
return "task-attach";
}
@Override
public String attachToTask(
@PathVariable("username") String username,
@PathVariable("id") int id,
@RequestParam("attachment") MultipartFile multipartFile,
@RequestParam("description") String description
) {
Task task = taskMap.get(username).get(id);
Attachment attachment = new Attachment(multipartFile.getOriginalFilename(),
description);
task.getAttachments().add(attachment);
try (InputStream inputStream =
new BufferedInputStream(multipartFile.getInputStream());
OutputStream outputStream =
new BufferedOutputStream(Files.newOutputStream(
Paths.get("/tmp", attachment.getId())))) {
byte[] buf = new byte[1024 * 16];
int len;
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException("Failed to upload file!", e);
}
return "redirect:./";
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,22 @@
home.title=Welcome to TaskTools!
task.add.description=description
task.add.due=due
task.add.header=Adding a task to {0}''s list:
task.add.submit=Submit
task.add.title={0}: task add
task.attach.attachment=attached file
task.attach.description=description
task.attach.header=task #{0}: attach file
task.attach.submit=Submit
task.attach.title=#{0}: Attach file
task.get.attach=Attach file
task.get.attachments=attachments:
task.get.download=Download
task.get.header=task #{0}:
task.get.list=Back
task.get.title={0}: task details
task.list.add-new=Add new
task.list.details=Details
task.list.header={0}''s tasks:
task.list.home=Home
task.list.title={0}: task list

View File

@ -0,0 +1,22 @@
home.title=Willkommen bei TaskTools!
task.add.description=Beschreibung
task.add.due=f\u00e4llig
task.add.header=F\u00fcge eine Aufgabe zu {0}''s Liste hinzu:
task.add.submit=Senden
task.add.title={0}: Task hinzuf\u00fcgen
task.attach.attachment=Angeh\u00e4ngte Datei
task.attach.description=Beschreibung
task.attach.header=Task #{0}: Datei anh\u00e4ngen
task.attach.submit=Senden
task.attach.title=#{0}: Datei anh\u00e4ngen
task.get.attach=Datei anh\u00e4ngen
task.get.attachments=Anh\u00e4nge:
task.get.download=Download
task.get.header=Task #{0}:
task.get.list=Zur\u00fcck
task.get.title={0}: Task Details
task.list.add-new=Neuer Task
task.list.details=Details
task.list.header={0}''s Tasks:
task.list.home=Startseite
task.list.title={0}: Task Liste

View File

@ -0,0 +1 @@
stylesheet=/public/css/themes/post_it.css

View File

@ -0,0 +1 @@
stylesheet=/public/css/themes/robotask.css

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Error</title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2>Error:</h2>
<p th:text="|URL: ${url}|"></p>
<p th:text="${exception}"></p>
</body>
</html>

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{home.title}"></title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2>TaskTools</h2>
<ul>
<li th:each="username : ${users}">
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="${username}"></a>
</li>
</ul>
</body>
</html>

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{task.add.title(${username})}"></title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2 th:text="#{task.add.header(${username})}"></h2>
<form method="post" action="#" th:action="@{/tasks/{username}/add(username=${username})}" th:object="${task}">
<input type="text" th:field="*{description}" th:placeholder="#{task.add.description}"/>
<input type="datetime-local" th:field="*{due}" th:placeholder="#{task.add.due}"/>
<input type="submit" th:value="#{task.add.submit}"/>
</form>
</body>
</html>

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{task.attach.title(${id})}"></title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2 th:text="#{task.attach.header(${id})}"></h2>
<form method="post" action="#" enctype="multipart/form-data"
th:action="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}">
<input type="file" name="attachment" th:placeholder="#{task.attach.attachment}"/>
<input type="text" name="description" th:placeholder="#{task.attach.description}"/>
<input type="submit" th:value="#{task.attach.submit}"/>
</form>
</body>
</html>

View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{task.get.title(${task.description})}"></title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2 th:text="#{task.get.header(${id})}"></h2>
<p th:text="${task.due}"></p>
<p th:text="${task.description}"></p>
<hr/>
<p th:text="#{task.get.attachments}"></p>
<dl th:each="attachment : ${task.attachments}">
<dt><img src="#" th:src="@{/attachments/{id}(id=${attachment.id})}"></dt>
<dt>
<span th:text="${attachment.name}"></span>
<a class="button" th:href="@{/attachments/{id}(id=${attachment.id},download=true)}"
th:text="#{task.get.download}"></a>
</dt>
<dd th:text="${attachment.description}"></dd>
</dl>
<p>
<a th:href="@{/tasks/{username}/list(username=${username})}" th:text="#{task.get.list}"></a>
<a th:href="@{/tasks/{username}/get/{id}/attach(username=${username},id=${id})}" th:text="#{task.get.attach}"></a>
</p>
</body>
</html>

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{task.list.title(${username})}"></title>
<link rel="stylesheet" type="text/css" href="/public/css/base.css">
<link rel="stylesheet" type="text/css" th:href="${#themes.code('stylesheet')}">
</head>
<body>
<h2 th:text="#{task.list.header(${username})}"></h2>
<ul>
<li th:each="task : ${tasks}">
<p th:text="*{task.due}"></p>
<p th:text="*{task.description}"></p>
<a th:href="@{/tasks/{username}/get/{id}(username=${username},id=${taskStat.index})}" th:text="#{task.list.details}"></a>
</li>
</ul>
<p>
<a th:href="@{/}" th:text="#{task.list.home}"></a>
<a th:href="@{/tasks/{username}/add(username=${username})}" th:text="#{task.list.add-new}"></a>
</p>
</body>
</html>

View File

@ -0,0 +1,8 @@
a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: #2196f3;
background-color: #e0e0e0;
}

View File

@ -0,0 +1,8 @@
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');
* {
font-family: 'Indie Flower', sans-serif;
font-size: 18px;
color: #ffeb3b;
background-color: #212121;
}

View File

@ -0,0 +1,8 @@
@import url('https://fonts.googleapis.com/css?family=Roboto');
* {
font-family: Roboto, sans-serif;
font-size: 1em;
color: #212121;
background-color: #fafafa;
}

View File

@ -13,5 +13,12 @@
- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache)
- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource)
To ignore "No persistence xml file found in project", you do:
Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator

View File

@ -0,0 +1,52 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ErrorController {
@RequestMapping(value = "500Error", method = RequestMethod.GET)
public void throwRuntimeException() {
throw new NullPointerException("Throwing a null pointer exception");
}
@RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
ModelAndView errorPage = new ModelAndView("errorPage");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code : 400 . Bad Request";
break;
}
case 401: {
errorMsg = "Http Error Code : 401. Unauthorized";
break;
}
case 404: {
errorMsg = "Http Error Code : 404. Resource not found";
break;
}
// Handle other 4xx error codes.
case 500: {
errorMsg = "Http Error Code : 500. Internal Server Error";
break;
}
// Handle other 5xx error codes.
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest
.getAttribute("javax.servlet.error.status_code");
}
}

View File

@ -0,0 +1,10 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>${errorMsg}</h1>
</body>
</html>

View File

@ -43,4 +43,7 @@
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<location>/errors</location>
</error-page>
</web-app>

View File

@ -332,5 +332,17 @@
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
</properties>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>3.0.4</version>
<configuration>
<effort>Max</effort>
<omitVisitors>FindDeadLocalStores,FindNullDeref</omitVisitors>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -2,15 +2,16 @@
## Spring Thymeleaf Example Project
### Relevant Articles:
- [Introduction to Using Thymeleaf in Spring](http://www.baeldung.com/thymeleaf-in-spring-mvc)
- [CSRF Protection with Spring MVC and Thymeleaf](http://www.baeldung.com/csrf-thymeleaf-with-spring-security)
### Build the Project
mvn clean install
### Run the Project
mvn cargo:run
- **note**: starts on port '8082'

View File

@ -5,4 +5,4 @@
### Relevant Articles:
- [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/java-mutation-testing-with-pitest)
- [Intro to JaCoCo](http://www.baeldung.com/jacoco)
- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest)