diff --git a/APPLICATIONS/EmbededSolar/pom.xml b/APPLICATIONS/EmbededSolar/pom.xml new file mode 100644 index 00000000..634c1631 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + EmbededSolar + EmbededSolar + 1.0-SNAPSHOT + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + solr-core + org.apache.solr + 8.8.2 + + + + org.apache.solr + solr-solrj + 5.5.0 + + + + + + + org.springframework.data + spring-data-solr + 2.0.5.RELEASE + + + + org.apache.jackrabbit + oak-solr-embedded + 0.7 + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..d4fbbcf4 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,173 @@ +package com.espark.adarsh; + +import org.apache.jackrabbit.oak.plugins.index.solr.embedded.EmbeddedSolrServerProvider; +import org.apache.jackrabbit.oak.plugins.index.solr.embedded.SolrServerConfiguration; +import org.apache.lucene.search.Query; +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrServer; +import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +//import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder; +import org.apache.solr.client.solrj.impl.HttpSolrServer; +import org.apache.solr.client.solrj.impl.XMLResponseParser; +import org.apache.solr.core.CoreContainer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.data.solr.core.SolrTemplate; +import org.springframework.data.solr.server.support.HttpSolrClientFactory; +import org.xml.sax.SAXException; + +import javax.annotation.PostConstruct; +import javax.xml.parsers.ParserConfigurationException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +@SpringBootApplication +public class ApplicationMain { + + @Value("${solr.core.name}") + private String coreName; + + @Autowired + ApplicationContext applicationContext; + + Resource resource = null; + + @PostConstruct + public void init() throws Exception { + resource = this.applicationContext.getResource("classpath:/solr/oak"); + if (!resource.exists()) { + throw new FileNotFoundException("Solr Configuration Not Found"); + } + System.setProperty("oak.data.dir", resource.getURL().getPath() + File.separator + "data"); + System.setProperty("oak.core.name", coreName); + } + + public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { + SpringApplication.run(ApplicationMain.class, args); + + } + + @Bean + public SolrClient createSolrServer() throws Exception { + CoreContainer coreContainer = new CoreContainer(resource.getURL().getPath()); + coreContainer.load(); + EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, coreName); + return server; + } + + + + /* @Bean + public EmbeddedSolrServer createEmbeddedSolrServer() { + String targetLocation = ApplicationMain.class + .getProtectionDomain().getCodeSource().getLocation().getFile() + "/.."; + String solrHome = targetLocation + "/classes/solrembeded"; + // Note that the following property could be set through JVM level arguments too + System.setProperty("solr.solr.home", solrHome); + CoreContainer coreContainer = new CoreContainer(solrHome); + coreContainer.load(); + EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, "solrembeded"); + return server; + } + +*/ + + /* @Bean + public EmbeddedSolrServerProvider embeddedSolrServerProvider() { + EmbeddedSolrServerProvider embeddedSolrServerProvider=null; + try { + *//* SolrServerConfiguration solrServerConfiguration = new SolrServerConfiguration("target/solr","target/solr/solr + * .xml", "oak"); + EmbeddedSolrServerProvider embeddedSolrServerProvider = new EmbeddedSolrServerProvider(solrServerConfiguration); + SolrServer solrServer = embeddedSolrServerProvider.getSolrServer();*//* + + Resource resource = this.applicationContext.getResource("classpath:/solr/oak"); + if(!resource.exists()) { + throw new FileNotFoundException("Solr Configuration Not Found"); + } + + String path = resource.getFile().getPath(); + EmbeddedSolrServerConfiguration embeddedSolrServerConfiguration=new EmbeddedSolrServerConfiguration(path, + "oak"); + embeddedSolrServerProvider = new EmbeddedSolrServerProvider(embeddedSolrServerConfiguration); + } catch (Exception e) { + log.error("label=EmbeddedSolrSearchIndexConfigure exception={}",e); + } + return embeddedSolrServerProvider; + }*/ + + + /* @Bean + public EmbeddedSolrServer server() { +try { + SolrServerConfiguration solrServerConfiguration = new SolrServerConfiguration("target/solr","target/solr/solr + .xml", "oak"); + EmbeddedSolrServerProvider embeddedSolrServerProvider = new EmbeddedSolrServerProvider(solrServerConfiguration); + embeddedSolrServerProvider.getSolrServer(); + + File resource = new File("/Users/akumar38/Desktop/EmbededSolar/src/main/resources/solr/data"); + Path dataPath = Paths.get("/Users/akumar38/Desktop/EmbededSolar/src/main/resources/solr/data"); + EmbeddedSolrServer server = new EmbeddedSolrServer(dataPath,"embedded-core"); + return server; + } catch (Exception e) { + e.printStackTrace(); + } + + + return null; + }*/ + + + + + + /* public HttpSolrClient solrClient(@Autowired HttpSolrServer solrServer) { + *//*HttpSolrClient.Builder builder = new HttpSolrClient.Builder("http://localhost:8983/solrembeded"); + return builder.build();*//* + + HttpSolrClient httpSolrClient=new HttpSolrClient("http://localhost:8983/solr"); + return httpSolrClient; + } + + + public SolrTemplate solrTemplate(@Autowired HttpSolrClient client) throws Exception { + return new SolrTemplate(client); + }*/ + + + + /* public HttpSolrServer createHttpSolrServer() { + String url = "http://localhost:8983/solr"; + HttpSolrServer server = new HttpSolrServer(url); + server.setMaxRetries(1); // defaults to 0. > 1 not recommended. + server.setConnectionTimeout(5000); // 5 seconds to establish TCP + // Setting the XML response parser is only required for cross + // version compatibility and only when one side is 1.4.1 or + // earlier and the other side is 3.1 or later. + server.setParser(new XMLResponseParser()); // binary parser is used by default + // The following settings are provided here for completeness. + // They will not normally be required, and should only be used + // after consulting javadocs to know whether they are truly required. + server.setSoTimeout(1000); // socket read timeout + server.setDefaultMaxConnectionsPerHost(100); + server.setMaxTotalConnections(100); + server.setFollowRedirects(false); // defaults to false + // allowCompression defaults to false. + // Server side must support gzip or deflate for this to have any effect. + server.setAllowCompression(true); + return server; + }*/ + +} diff --git a/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..16093ed1 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.controller; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.client.solrj.response.UpdateResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.solr.core.SolrTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +public class ApplicationController { + + /* @Autowired + private SolrTemplate solrTemplate; + + @PostMapping("/data") + public @ResponseBody UpdateResponse saveData(@RequestBody Map data){ + return solrTemplate.saveBean(data); + } + + @GetMapping("/data/{id}") + public Map getData(@PathVariable("id") String id){ + return this.solrTemplate.getById(id, HashMap.class); + }*/ + + @Autowired + private SolrClient solrServer; + + @GetMapping("/data") + public long getData() throws Exception { + SolrQuery query = new SolrQuery(); + query.setQuery("*:*"); + QueryResponse resp = solrServer.query(query); + long numDocs = resp.getResults().getNumFound(); + return numDocs; + } +} diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/application.properties b/APPLICATIONS/EmbededSolar/src/main/resources/application.properties new file mode 100644 index 00000000..6ae0340c --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/application.properties @@ -0,0 +1 @@ +solr.core.name=oak \ No newline at end of file diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/logback.xml b/APPLICATIONS/EmbededSolar/src/main/resources/logback.xml new file mode 100644 index 00000000..c06135c8 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/logback.xml @@ -0,0 +1,21 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/lang/stopwords_en.txt b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/lang/stopwords_en.txt new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/protwords.txt b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/protwords.txt new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/schema.xml b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/schema.xml new file mode 100644 index 00000000..d1f42a67 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/schema.xml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + id + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/solrconfig.xml b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/solrconfig.xml new file mode 100644 index 00000000..134fa134 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/solrconfig.xml @@ -0,0 +1,59 @@ + + + + 6.2.1 + + ${oak.data.dir} + + + + + single + + + + + + + + + + + + + + + 1000 + 5000 + + + + + solr + + solrconfig.xml + schema.xml + + q=solr&version=2.0&start=0&rows=0 + + + server-enabled + + + \ No newline at end of file diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/synonyms.txt b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/conf/synonyms.txt new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/core.properties b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/core.properties new file mode 100644 index 00000000..3329f73a --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/core.properties @@ -0,0 +1 @@ +name=oak \ No newline at end of file diff --git a/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/solr.xml b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/solr.xml new file mode 100644 index 00000000..95f667e6 --- /dev/null +++ b/APPLICATIONS/EmbededSolar/src/main/resources/solr/oak/solr.xml @@ -0,0 +1,21 @@ + + + + 127.0.0.1 + 8983 + solr + 15000 + true + + + + 10 + 10 + + + + + ${oak.core.name} + + \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/pom.xml b/APPLICATIONS/EsparkSpringBootFileUload/pom.xml new file mode 100644 index 00000000..2793abd9 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + espark-spring-boot-file-upload + espark-spring-boot-file-upload + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.2.RELEASE + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..33cdc123 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +/** + * Created by adarsh_k on 5/18/2017. + */ +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageException.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageException.java new file mode 100644 index 00000000..22460a3a --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageException.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.exception; + +public class StorageException extends RuntimeException { + + public StorageException(String message) { + super(message); + } + + public StorageException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageFileNotFoundException.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageFileNotFoundException.java new file mode 100644 index 00000000..427ca8d2 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/exception/StorageFileNotFoundException.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.exception; + +public class StorageFileNotFoundException extends StorageException { + + public StorageFileNotFoundException(String message) { + super(message); + } + + public StorageFileNotFoundException(String message, Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/FileSystemStorageService.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/FileSystemStorageService.java new file mode 100644 index 00000000..08b2e638 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/FileSystemStorageService.java @@ -0,0 +1,88 @@ +package com.espark.adarsh.storage; + +import com.espark.adarsh.exception.StorageException; +import com.espark.adarsh.exception.StorageFileNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.stereotype.Service; +import org.springframework.util.FileSystemUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +@Service +public class FileSystemStorageService implements StorageService { + + private final Path rootLocation; + + @Autowired + public FileSystemStorageService(StorageProperties properties) { + this.rootLocation = Paths.get(properties.getLocation()); + } + + @Override + public void store(MultipartFile file) { + try { + if (file.isEmpty()) { + throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); + } + Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename())); + } catch (IOException e) { + throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); + } + } + + @Override + public Stream loadAll() { + try { + return Files.walk(this.rootLocation, 1) + .filter(path -> !path.equals(this.rootLocation)) + .map(path -> this.rootLocation.relativize(path)); + } catch (IOException e) { + throw new StorageException("Failed to read stored files", e); + } + + } + + @Override + public Path load(String filename) { + return rootLocation.resolve(filename); + } + + @Override + public Resource loadAsResource(String filename) { + try { + Path file = load(filename); + Resource resource = new UrlResource(file.toUri()); + if(resource.exists() || resource.isReadable()) { + return resource; + } + else { + throw new StorageFileNotFoundException("Could not read file: " + filename); + + } + } catch (MalformedURLException e) { + throw new StorageFileNotFoundException("Could not read file: " + filename, e); + } + } + + @Override + public void deleteAll() { + FileSystemUtils.deleteRecursively(rootLocation.toFile()); + } + + @Override + public void init() { + try { + Files.createDirectory(rootLocation); + } catch (IOException e) { + throw new StorageException("Could not initialize storage", e); + } + } +} diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageProperties.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageProperties.java new file mode 100644 index 00000000..20dbb3ef --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageProperties.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.storage; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties("storage") +public class StorageProperties { + + /** + * Folder location for storing files + */ + private String location = "C:\\ADARSHKUMAR\\spring_boot\\EsparkSpringBootFileUload\\upload"; + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + +} diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageService.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageService.java new file mode 100644 index 00000000..88d3940d --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/storage/StorageService.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.storage; + +import org.springframework.core.io.Resource; +import org.springframework.web.multipart.MultipartFile; + +import java.nio.file.Path; +import java.util.stream.Stream; + +public interface StorageService { + + void init(); + + void store(MultipartFile file); + + Stream loadAll(); + + Path load(String filename); + + Resource loadAsResource(String filename); + + void deleteAll(); + +} diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/web/FileUploadController.java b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/web/FileUploadController.java new file mode 100644 index 00000000..bcdc88ed --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/com/espark/adarsh/web/FileUploadController.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.web; + +/** + * Created by adarsh_k on 5/18/2017. + */ + +import com.espark.adarsh.exception.StorageFileNotFoundException; +import com.espark.adarsh.storage.StorageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import java.io.IOException; +import java.util.stream.Collectors; + +@Controller +public class FileUploadController { + + private final StorageService storageService; + + @Autowired + public FileUploadController(StorageService storageService) { + this.storageService = storageService; + } + + @GetMapping("/") + public String listUploadedFiles(Model model) throws IOException { + + model.addAttribute("files", storageService + .loadAll() + .map(path -> + MvcUriComponentsBuilder + .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString()) + .build().toString()) + .collect(Collectors.toList())); + + return "uploadForm"; + } + + @GetMapping("/files/{filename:.+}") + @ResponseBody + public ResponseEntity serveFile(@PathVariable String filename) { + + Resource file = storageService.loadAsResource(filename); + return ResponseEntity + .ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"") + .body(file); + } + + @PostMapping("/") + public String handleFileUpload(@RequestParam("file") MultipartFile file, + RedirectAttributes redirectAttributes) { + + storageService.store(file); + redirectAttributes.addFlashAttribute("message", + "You successfully uploaded " + file.getOriginalFilename() + "!"); + + return "redirect:/"; + } + + @ExceptionHandler(StorageFileNotFoundException.class) + public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) { + return ResponseEntity.notFound().build(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/help/help.txt b/APPLICATIONS/EsparkSpringBootFileUload/src/main/java/help/help.txt new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/application.properties b/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/application.properties new file mode 100644 index 00000000..09a638e7 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.http.multipart.max-file-size=128KB +spring.http.multipart.max-request-size=128KB +com.espark.adarsh.storage.StorageProperties.storage=/ +com.espark.adarsh.storage.StorageProperties.upload-dir=/ \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/templates/uploadForm.html b/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/templates/uploadForm.html new file mode 100644 index 00000000..bb481928 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/main/resources/templates/uploadForm.html @@ -0,0 +1,26 @@ + + + +
+

+

+ +
+
+ + + +
File to upload:
+
+
+ + + + + \ No newline at end of file diff --git a/APPLICATIONS/EsparkSpringBootFileUload/src/test/java/com/espark/adarsh/test/FileUploadTests.java b/APPLICATIONS/EsparkSpringBootFileUload/src/test/java/com/espark/adarsh/test/FileUploadTests.java new file mode 100644 index 00000000..1e41f398 --- /dev/null +++ b/APPLICATIONS/EsparkSpringBootFileUload/src/test/java/com/espark/adarsh/test/FileUploadTests.java @@ -0,0 +1,71 @@ +package com.espark.adarsh.test; + +/** + * Created by adarsh_k on 5/18/2017. + */ + +import com.espark.adarsh.exception.StorageFileNotFoundException; +import com.espark.adarsh.storage.StorageService; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import java.nio.file.Paths; +import java.util.stream.Stream; + +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@AutoConfigureMockMvc +@SpringBootTest +public class FileUploadTests { + + @Autowired + private MockMvc mvc; + + @MockBean + private StorageService storageService; + + @Test + public void shouldListAllFiles() throws Exception { + given(this.storageService.loadAll()) + .willReturn(Stream.of(Paths.get("first.txt"), Paths.get("second.txt"))); + + this.mvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(model().attribute("files", + Matchers.contains("http://localhost/files/first.txt", "http://localhost/files/second.txt"))); + } + + @Test + public void shouldSaveUploadedFile() throws Exception { + MockMultipartFile multipartFile = + new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes()); + this.mvc.perform(fileUpload("/").file(multipartFile)) + .andExpect(status().isFound()) + .andExpect(header().string("Location", "/")); + + then(this.storageService).should().store(multipartFile); + } + + @Test + public void should404WhenMissingFile() throws Exception { + given(this.storageService.loadAsResource("test.txt")) + .willThrow(StorageFileNotFoundException.class); + + this.mvc.perform(get("/files/test.txt")) + .andExpect(status().isNotFound()); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/README.md b/APPLICATIONS/README.md new file mode 100644 index 00000000..3f4fd8d6 --- /dev/null +++ b/APPLICATIONS/README.md @@ -0,0 +1,743 @@ + +OWNER : ADARSH KUMAR + +EMAIL : ADARSHKUMARSINGH83@GMAIL.COM + +**[Espark Youtube Spring Boot ](https://www.youtube.com/playlist?list=PLBH_SvM38ibHFj5ulvAobbYbd9dOiIAOW)** + +ESPARK SPRING BOOT EXAMPLES +------------------------------------- + +* ### EmbededSolar +> description: +> . +> . +> . + +* ### SpringBootSecurityHsSqlDbExample +> description: +> . +> . +> . + +* ### springboot-cloudconfig-example +> description: +> . +> . +> . + +* ### EsparkSpringBootFileUload +> description: +> . +> . +> . + +* ### SpringBootSecurityMongoDbExample +> description: +> . +> . +> . + +* ### springboot-conditions +> description: +> . +> . +> . + +* ### SpringBootSocialFbAndGitLoginExample +> description: +> . +> . +> . + +* ### springboot-contact-validation +> description: +> . +> . +> . + +* ### SpringBootSolr +> description: +> . +> . +> . + +* ### springboot-custom-auto-configuration +> description: +> . +> . +> . + +* ### SpringBootSwaggerExample +> description: +> . +> . +> . + +* ### springboot-custom-module +> description: +> . +> . +> . + +* ### SPRING-BOOT-ELASIC-MQ +> description: +> . +> . +> . + +* ### SpringBootTokenAuthenticatoinHibernateExample +> description: +> . +> . +> . + +* ### springboot-custom-yml +> description: +> . +> . +> . + +* ### SPRINGBOOT-JPA-SAMPLES +> description: +> . +> . +> . + +* ### SpringBootTomcatSSLServerExample +> description: +> . +> . +> . + +* ### springboot-custominterceptor +> description: +> . +> . +> . + +* ### SpringBootAopExample +> description: +> . +> . +> . + +* ### SpringBootTomcatServerExample +> description: +> . +> . +> . + +* ### springboot-docker-maven +> description: +> . +> . +> . + +* ### SpringBootBasicExample +> description: +> . +> . +> . + +SpringBootWebMvcJspExample +> description: +> . +> . +> . + +* ### springboot-dropwizard +> description: +> . +> . +> . + +* ### SpringBootCasandraBasicExample +> description: +> . +> . +> . + +* ### SpringBootWebMvcProfileExample +> description: +> . +> . +> . + +* ### springboot-espark-json +> description: +> . +> . +> . + +* ### SpringBootEmbeddedLdapExample +> description: +> . +> . +> . + +* ### SpringBootZuulProxyServerExample +> description: +> . +> . +> . + +* ### springboot-gradle-standalone +> description: +> . +> . +> . + +* ### SpringBootEmbidedKafkaExample +> description: +> . +> . +> . + +* ### SpringSecurityBootDaoAuthenticationExample +> description: +> . +> . +> . + +* ### springboot-gradle-web +> description: +> . +> . +> . + +* ### SpringBootExternalLdapExample +> description: +> . +> . +> . + +* ### SpringSecurityMvcEmbeddedLdap +> description: +> . +> . +> . + +* ### springboot-groovy-java +> description: +> . +> . +> . + +* ### SpringBootFileUploadExample +> description: +> . +> . +> . + +* ### SpringSolarExample +> description: +> . +> . +> . + +* ### springboot-h2-jpa +> description: +> . +> . +> . + +* ### SpringBootHibernateExample +> description: +> . +> . +> . + +* ### SpringbootJackRabbit +> description: +> . +> . +> . + +* ### springboot-hibrenate-plugin +> description: +> . +> . +> . + +* ### SpringBootInMemoSecurityExample +> description: +> . +> . +> . + +* ### completable-future-async +> description: +> . +> . +> . + +* ### springboot-import-selector +> description: +> . +> . +> . + +* ### SpringBootJerseyExample +> description: +> . +> . +> . + +* ### custom-annotation-processing +> description: +> . +> . +> . + +* ### springboot-inmemo-hazelcast-cache +> description: +> . +> . +> . + +* ### SpringBootJettySSLServerExample +> description: +> . +> . +> . + +* ### custom-module-starter +> description: +> . +> . +> . + +* ### springboot-jelasticsearch-restclient +> description: +> . +> . +> . + +* ### SpringBootJettyServerExample +> description: +> . +> . +> . + +* ### springboot-kinesis +> description: +> . +> . +> . + +* ### SpringBootJpaExample +> description: +> . +> . +> . + +* ### elsatic-mq +> description: +> . +> . +> . + +* ### springboot-maven-profiling +> description: +> . +> . +> . + +* ### SpringBootJpaMongoExample +> description: +> . +> . +> . + +* ### espark-jsonschema-validation +> description: +> . +> . +> . + +* ### springboot-messges +> description: +> . +> . +> . + +* ### SpringBootJpaOneToOneMappingExample +> description: +> . +> . +> . + +* ### logback-runtime-change +> description: +> . +> . +> . + +* ### springboot-mock-test +> description: +> . +> . +> . + +* ### SpringBootJsonXmlRequestResponseExample +> description: +> . +> . +> . + +* ### product-information-system +> description: +> . +> . +> . + +* ### springboot-mocketo +> description: +> . +> . +> . + +* ### SpringBootJspJettyExample +> description: +> . +> . +> . + +* ### springboot-module-gradle +> description: +> . +> . +> . + +* ### SpringBootJspTomcatExample +> description: +> . +> . +> . + +* ### solr-client-query-example +> description: +> . +> . +> . + +* ### springboot-multimodule-gradle +> description: +> . +> . +> . + +* ### SpringBootMockitoExmaple +> description: +> . +> . +> . + +* ### sprinboot-sqs-elastic-queue +> description: +> . +> . +> . + +* ### springboot-neo4j-docker +> description: +> . +> . +> . + +* ### SpringBootMultiContextExample +> description: +> . +> . +> . + +* ### spring-boot-admin +> description: +> . +> . +> . + +* ### springboot-nginx-docker +> description: +> . +> . +> . + +* ### SpringBootMvcAndRestExample +> description: +> . +> . +> . + +* ### spring-boot-hystrix +> description: +> . +> . +> . + +* ### springboot-react +> description: +> . +> . +> . + +* ### SpringBootMvcAndRestSecurityExample +> description: +> . +> . +> . + +* ### spring-boot-reference.pdf +> description: +> . +> . +> . + +* ### springboot-react-restcall +> description: +> . +> . +> . + +* ### SpringBootMvcJspSecurityExample +> description: +> . +> . +> . + +* ### spring-cloud-stream-kafka-master +> description: +> . +> . +> . + +* ### springboot-restart-programatically +> description: +> . +> . +> . + +* ### SpringBootMvcSecurityExample +> description: +> . +> . +> . + +* ### spring-data-jpa-postgresql +> description: +> . +> . +> . + +* ### springboot-server-hazelcast-cache +> description: +> . +> . +> . + +* ### SpringBootOAuthExample +> description: +> . +> . +> . + +* ### spring-framework-reference.pdf +> description: +> . +> . +> . + +* ### springboot-ssl +> description: +> . +> . +> . + +* ### SpringBootParallelAsynchronousCallExample +> description: +> . +> . +> . + +* ### spring-kafka-producer-consumer +> description: +> . +> . +> . + +* ### springboot-swagger-yml +> description: +> . +> . +> . + +* ### SpringBootParallelAsynchronousCallServer&Client +> description: +> . +> . +> . + +* ### spring-mvc-annoation +> description: +> . +> . +> . + +* ### springboot-vault +> description: +> . +> . +> . + +* ### SpringBootProfileExample +> description: +> . +> . +> . + +* ### spring-reflection +> description: +> . +> . +> . + +* ### springboot-version +> description: +> . +> . +> . + +* ### SpringBootProfileTest +> description: +> . +> . +> . + +* ### springboot-annotation-module +> description: +> . +> . +> . + +* ### springboot-web-rest +> description: +> . +> . +> . + +* ### SpringBootRabbitMqExample +> description: +> . +> . +> . + +* ### springboot-async-example +> description: +> . +> . +> . + +* ### springboot-wiremock +> description: +> . +> . +> . + +* ### SpringBootRestMvcExample +> description: +> . +> . +> . + +* ### springboot-awssqs-elasticmq +> description: +> . +> . +> . + +* ### springboot-xml-jsonparsing +> description: +> . +> . +> . + +* ### SpringBootRestMvcSecurityExample +> description: +> . +> . +> . +* ### springboot-batch +> description: +> . +> . +> . + +* ### springboot-zipkin-sleuth +> description: +> . +> . +> . + +* ### SpringBootSecurityDaoAuthenticationExample +> description: +> . +> . +> . + +* ### springboot-batch-example +> description: +> . +> . +> . + +* ### springbootautoconfiguraiton.txt +> description: +> . +> . +> . + +* ### SpringBootSecurityHibernateExample +> description: +> . +> . +> . + +* ### springboot-cassandra +> description: +> . +> . +> . + +* ### springboot-logs +> description: \ +> . sample application which demo the +> . different log configuraiton like rolling file appender +> . and sluth configuraitons for tracid and spanid + +* ### springboot-elasticsearch +> description: \ +> . spring boot sample to connect to the elastic search +> . and elastic search is spinned using docker and kibina to +> . view the elastic search connect indexed on the elastic search + +* ### springboot-ssl-server-client +> description: \ +> spring boot self signed certificate configure rest server \ +> spring boot self signed certificate configure rest template client \ + +* ### [springboot-redis-cache](https://github.com/adarshkumarsingh83/spring_boot/tree/master/springboot-redis-cache) +> description: \ +> . spring boot sample to connect to the redis Cache \ +> . it used spring data project which has repositories \ +> . to perform the curd operation on the redis cache + +* ### [springboot-embedded-hazelcast-cache](https://github.com/adarshkumarsingh83/spring_boot/tree/master/springboot-embedded-hazelcast-cache) +> description: \ +> spring boot hazel cast embedded cache example \ +> where data is stored in cache and retived from cache\ +> management-center help to connect to the cache and give indepth + +* ### [springboot-haproxy](https://github.com/adarshkumarsingh83/spring_boot/tree/master/springboot-haproxy) +> description: \ +> spring boot haproxy sample with load balancing example \ diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/help.txt b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/help.txt new file mode 100644 index 00000000..e4734a1a --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/help.txt @@ -0,0 +1,3 @@ +$ mvn clean package +$ mvn spring-boot:run +$ curl -H "Content-Type:application/json" -X POST http://localhost:8080/api/message -d '{"data":"espark message from client"}' \ No newline at end of file diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/.gitignore b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/document/help.txt b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/document/help.txt new file mode 100644 index 00000000..5ddab0e2 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/document/help.txt @@ -0,0 +1,7 @@ + +$ mvn clean package + +$ mvn spring-boot:run + +# post message +$ curl -H "Content-Type:application/json" -X POST http://localhost:8080/api/message -d '{"data":"espark message from client"}' \ No newline at end of file diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/pom.xml b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/pom.xml new file mode 100644 index 00000000..1a19bd78 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/pom.xml @@ -0,0 +1,88 @@ + + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-elastic-mq-client + 0.0.1-SNAPSHOT + springboot-elastic-mq-client + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.10.1 + + + + org.springframework.cloud + spring-cloud-aws-messaging + 2.2.1.RELEASE + + + + com.amazonaws + amazon-sqs-java-messaging-lib + 1.0.3 + + + + javax.jms + javax.jms-api + 2.0.1 + + + + org.springframework + spring-jms + 4.3.3.RELEASE + + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/bean/MessageBean.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/bean/MessageBean.java new file mode 100644 index 00000000..4cb7d9cb --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/bean/MessageBean.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public class MessageBean implements Serializable { + + private T data; + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + @Override + public String toString() { + return "MessageBean{" + + "data=" + data.toString() + + '}'; + } +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java new file mode 100644 index 00000000..2499538c --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.config; + +import com.amazon.sqs.javamessaging.ProviderConfiguration; +import com.amazon.sqs.javamessaging.SQSConnectionFactory; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.sqs.AmazonSQSClient; +import com.espark.adarsh.handler.SqsListenerExceptionHandler; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.elasticmq.rest.sqs.SQSRestServer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.jms.support.destination.DynamicDestinationResolver; + +import javax.jms.ConnectionFactory; +import javax.jms.Session; + +@Slf4j +@Configuration +public class ElasticMqConfig { + + private SQSRestServer server; + private static final String mqEndpoint = "http://localhost:9324"; + + @Bean(name = "connection") + public ConnectionFactory mqConnectionFactory() { + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")); + amazonSQSClient.setEndpoint(mqEndpoint); + return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQSClient); + } + + @Bean + @Autowired + public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( + @Qualifier("connection") ConnectionFactory connectionFactory + , SqsListenerExceptionHandler sqsListenerExceptionHandler) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + factory.setDestinationResolver(new DynamicDestinationResolver()); + factory.setConcurrency("1-3"); + factory.setErrorHandler(sqsListenerExceptionHandler); + factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); + return factory; + } + + @Bean + @Autowired + public JmsTemplate sqsJmsTemplate(ConnectionFactory connectionFactory) { + return new JmsTemplate(connectionFactory); + } + + @Bean + public ObjectMapper objectMapper(){ + return new ObjectMapper(); + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/consumer/ApplicationConsumer.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/consumer/ApplicationConsumer.java new file mode 100644 index 00000000..f702b85e --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/consumer/ApplicationConsumer.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.consumer; + +import com.espark.adarsh.bean.MessageBean; +import com.espark.adarsh.util.CompressionUtil; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jms.annotation.JmsListener; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.messaging.handler.annotation.Headers; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.Map; + +@Slf4j +@Service +public class ApplicationConsumer { + + @Autowired + ObjectMapper objectMapper; + + @Autowired + CompressionUtil compressionUtil; + + @JmsListener(destination = "${epsark.queue.consumer:WORK-LOCAL-CONSUMING}") + void onMessageReceived(byte[] message, @Headers Map headers) throws IOException { + + if (message != null && message.length != 0) { + String json = this.compressionUtil.decompress(message); + MessageBean messageBean = this.objectMapper.readValue(json, new TypeReference() { + }); + log.info("label=onMessageReceived() ", messageBean.getData()); + } + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/handler/SqsListenerExceptionHandler.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/handler/SqsListenerExceptionHandler.java new file mode 100644 index 00000000..1d9737e1 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/handler/SqsListenerExceptionHandler.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.handler; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.ErrorHandler; + +@Slf4j +@Component +public class SqsListenerExceptionHandler implements ErrorHandler { + + @Override + public void handleError(Throwable t) { + log.error("label=handler exception={}", t.getLocalizedMessage()); + } +} + + diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/publisher/ApplicationPublisher.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/publisher/ApplicationPublisher.java new file mode 100644 index 00000000..284dc220 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/publisher/ApplicationPublisher.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.publisher; + +import com.espark.adarsh.bean.MessageBean; +import com.espark.adarsh.util.CompressionUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.jms.core.MessageCreator; +import org.springframework.stereotype.Service; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Session; +import java.io.IOException; + +@Slf4j +@Service +public class ApplicationPublisher { + + @Autowired + ObjectMapper objectMapper; + + @Autowired + JmsTemplate jmsTemplate; + + @Autowired + CompressionUtil compressionUtil; + + @Value("${epsark.queue.producer:WORK-LOCAL-PRODUCING}") + String workLocalQueue; + + + public String sendMessage(MessageBean messageBean) throws IOException { + String message = objectMapper.writeValueAsString(messageBean); + byte[] compressedData = compressionUtil.compress(message); + jmsTemplate.send(workLocalQueue, new MessageCreator() { + @Override + public Message createMessage(Session session) throws JMSException { + Message jmsMessage = session.createObjectMessage(compressedData); + jmsMessage.setStringProperty("traceId", System.nanoTime() + ""); + return jmsMessage; + } + }); + return "MESSAGE SEND SUCCESSFUL"; + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/util/CompressionUtil.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/util/CompressionUtil.java new file mode 100644 index 00000000..c28de669 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/util/CompressionUtil.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.util; + +import org.springframework.stereotype.Component; + +import java.io.*; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +@Component +public class CompressionUtil { + + public String decompress(byte[] compressed) throws IOException { + ByteArrayInputStream bis = new ByteArrayInputStream(compressed); + GZIPInputStream gis = new GZIPInputStream(bis); + BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8")); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + gis.close(); + bis.close(); + return sb.toString(); + } + + public byte[] compress(String data) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); + GZIPOutputStream gzip = new GZIPOutputStream(bos); + gzip.write(data.getBytes()); + gzip.close(); + byte[] compressed = bos.toByteArray(); + bos.close(); + return compressed; + } +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..a86ffaf2 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.MessageBean; +import com.espark.adarsh.publisher.ApplicationPublisher; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + private ApplicationPublisher publisher; + + @PostMapping("/message") + public String postMessage(@RequestBody MessageBean messageBean) throws Exception { + log.info("label=postMessage() messageBean={}", messageBean); + return this.publisher.sendMessage(messageBean); + } +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/resources/application.properties b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/resources/application.properties new file mode 100644 index 00000000..7f2a6691 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/main/resources/application.properties @@ -0,0 +1,7 @@ +logging.level.com.espark.adarsh=DEBUG +logging.level.root=DEBUG + + +epsark.queue.consumer=WORK-LOCAL-CONSUMING +epsark.queue.producer=WORK-LOCAL-CONSUMING +#epsark.queue.producer=WORK-LOCAL-PRODUCING \ No newline at end of file diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java new file mode 100644 index 00000000..17250856 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-client/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootElasicmqApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/.gitignore b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/pom.xml b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/pom.xml new file mode 100644 index 00000000..d70ad22d --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-elastic-mq-server + 0.0.1-SNAPSHOT + springboot-elastic-mq-server + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.10.1 + + + + org.springframework.cloud + spring-cloud-aws-messaging + 2.2.1.RELEASE + + + + com.amazonaws + aws-java-sdk-sqs + 1.11.763 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java new file mode 100644 index 00000000..c038cdd7 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/java/com/espark/adarsh/config/ElasticMqConfig.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.config; + +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.sqs.AmazonSQSClient; +import lombok.extern.slf4j.Slf4j; +import org.elasticmq.rest.sqs.SQSRestServer; +import org.elasticmq.rest.sqs.SQSRestServerBuilder; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@Slf4j +@Component +public class ElasticMqConfig { + + private SQSRestServer server; + private static final String endpoint = "http://localhost:9324"; + + @PostConstruct + public void init() { + log.info("label=init() executed "); + server = SQSRestServerBuilder.withPort(9324).withInterface("localhost").start(); + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")); + amazonSQSClient.setEndpoint(endpoint); + amazonSQSClient.createQueue("WORK-LOCAL-CONSUMING"); + amazonSQSClient.createQueue("WORK-LOCAL-PRODUCING"); + } + + @PreDestroy + public void destroy() { + log.info("label=destroy() executed "); + server.stopAndGetFuture(); + } +} diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/resources/application.properties b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/resources/application.properties new file mode 100644 index 00000000..9a3581ac --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/main/resources/application.properties @@ -0,0 +1,3 @@ +logging.level.com.espark.adarsh=TRACE +logging.level.root=DEBUG +server.port=8181 diff --git a/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java new file mode 100644 index 00000000..17250856 --- /dev/null +++ b/APPLICATIONS/SPRING-BOOT-ELASIC-MQ/springboot-elastic-mq-server/src/test/java/com/espark/adarsh/SpringbootElasicmqApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootElasicmqApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/.gitignore new file mode 100644 index 00000000..780dc9cf --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +/*.DS_Store +*.DS_Store +*/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/README.md b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/README.md new file mode 100644 index 00000000..6d28d1e0 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/README.md @@ -0,0 +1,16 @@ + +# spring boot h2-db + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/pom.xml new file mode 100644 index 00000000..409c4ae9 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-h2-db + 0.0.1-SNAPSHOT + springboot-h2-db + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..57a3e3de --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..5a452947 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.exception; + +public class EmployeeNotFoundException extends RuntimeException{ + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..59a2bf6a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/application.properties new file mode 100644 index 00000000..cc398596 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/application.properties @@ -0,0 +1,12 @@ + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/data.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-h2-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/document/help.txt new file mode 100644 index 00000000..7e07d6b8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/document/help.txt @@ -0,0 +1,8 @@ +# to build the app +$ mvn clean package + +#to execute the app +$ mvn spring-boot:run + +# to test the url +$ curl http://localhost:8080/api/employees \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/pom.xml new file mode 100644 index 00000000..11e65dce --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-hikari-connection-pool + 0.0.1-SNAPSHOT + springboot-hikari-connection-pool + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.apache.tomcat + tomcat-jdbc + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + com.zaxxer + HikariCP + 3.3.1 + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/.DS_Store new file mode 100644 index 00000000..b6e3c7ab Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/.DS_Store new file mode 100644 index 00000000..2bca5fb2 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/.DS_Store new file mode 100644 index 00000000..df639e6b Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..01142280 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/HikariConnectionPoolApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/HikariConnectionPoolApplicationMain.java new file mode 100644 index 00000000..6b5d230d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/HikariConnectionPoolApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HikariConnectionPoolApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(HikariConnectionPoolApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..4f7c25dc --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.entity; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; +import java.io.Serializable; +import java.util.Date; + +@Setter +@Getter +@Entity +@Table(name = "employee") +public class Employee implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @NotNull + @Size(max = 65) + @Column(name = "first_name") + protected String firstName; + + @Size(max = 65) + @Column(name = "last_name") + protected String lastName; + + @NotNull + @Email + @Size(max = 100) + @Column(unique = true) + protected String email; + + @Temporal(TemporalType.DATE) + @Column(name = "dob") + protected Date dob; + + + public Employee() { + } + + public Employee(@NotNull @Size(max = 65) String firstName + , @Size(max = 65) String lastName + , @NotNull @Email @Size(max = 100) String email + , Date dob) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.dob = dob; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..4836b194 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..4e888dff --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public List getEmployees() { + return employeeRepository.findAll(); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/util/DatabaseInit.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/util/DatabaseInit.java new file mode 100644 index 00000000..0ee75368 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/util/DatabaseInit.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.Calendar; + +@Component +public class DatabaseInit { + + @Autowired + EmployeeRepository employeeRepository; + + + @PostConstruct + public void init(){ + Calendar adarshDob = Calendar.getInstance(); + adarshDob.set(2020, 1, 1); + Employee adarsh = new Employee("Adarsh" + , "Singh" + , "adarsh@espark" + , adarshDob.getTime()); + adarsh = employeeRepository.save(adarsh); + + Calendar radhaDob = Calendar.getInstance(); + radhaDob.set(2020, 1, 1); + Employee radha = new Employee("Radha" + , "Singh" + , "radha@espark" + , radhaDob.getTime()); + radha = employeeRepository.save(radha); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..1162714b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import java.util.List; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getEmployees() { + return this.employeeService.getEmployees(); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/resources/application.yml new file mode 100644 index 00000000..32e31a33 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/main/resources/application.yml @@ -0,0 +1,30 @@ +server: + port: 8080 + +spring: + application: + name: springboot-hikari + datasource: + url: jdbc:h2:mem:testdb + username: root + password: root + driver-class-name: org.h2.Driver + type: com.zaxxer.hikari.HikariDataSource + hikari: + connection-timeout: 20000 #maximum number of milliseconds that a client will wait for a connection + minimum-idle: 10 #minimum number of idle connections maintained by HikariCP in a connection pool + maximum-pool-size: 10 #maximum pool size + idle-timeout: 10000 #maximum idle time for connection + max-lifetime: 1000 # maximum lifetime in milliseconds of a connection in the pool after it is closed. + auto-commit: true #default auto-commit behavior. + h2: + console: + enabled: true + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/test/java/com/espark/adarsh/HikariConnectionPoolApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/test/java/com/espark/adarsh/HikariConnectionPoolApplicationMainTests.java new file mode 100644 index 00000000..c6c8fe76 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-hikari-connection-pool/src/test/java/com/espark/adarsh/HikariConnectionPoolApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class HikariConnectionPoolApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/document/help.txt new file mode 100644 index 00000000..1baca1ed --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/document/help.txt @@ -0,0 +1,12 @@ + +# to build +$ mvn clean package + +#to run +$ mvn spring-boot:run + +$ curl http://localhost:8080/api/employee +$ curl http://localhost:8080/api/employee-project + +## h2 db console url +http://localhost:8080/h2-console \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/pom.xml new file mode 100644 index 00000000..73f54793 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-many-to-many-bidirectional + 0.0.1-SNAPSHOT + springboot-jpa-many-to-many-bidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..553b283c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.Employee; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EmployeeBean extends Employee implements Serializable { + + private List projectsBeans; + + public EmployeeBean() { + } + + public EmployeeBean(Employee employee) { + this.id = employee.getId(); + this.firstName = employee.getFirstName(); + this.lastName = employee.getLastName(); + this.email = employee.getEmail(); + this.dob = employee.getDob(); + this.projectsBeans = null; + } + + public EmployeeBean(Employee employee, List list) { + this.id = employee.getId(); + this.firstName = employee.getFirstName(); + this.lastName = employee.getLastName(); + this.email = employee.getEmail(); + this.dob = employee.getDob(); + this.projectsBeans = list; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/ProjectsBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/ProjectsBean.java new file mode 100644 index 00000000..41dd1524 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/ProjectsBean.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.Projects; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ProjectsBean extends Projects + implements Serializable { + + List employeeBeanList; + + public ProjectsBean() { + } + + public ProjectsBean(Projects projects) { + this.id = projects.getId(); + this.phoneNumber = projects.getPhoneNumber(); + this.start = projects.getStart(); + this.end = projects.getEnd(); + this.address1 = projects.getAddress1(); + this.address2 = projects.getAddress2(); + this.street = projects.getStreet(); + this.city = projects.getCity(); + this.state = projects.getState(); + this.country = projects.getCountry(); + this.zipCode = projects.getZipCode(); + } + + public ProjectsBean(Projects projects, List employee) { + this.id = projects.getId(); + this.phoneNumber = projects.getPhoneNumber(); + this.start = projects.getStart(); + this.end = projects.getEnd(); + this.address1 = projects.getAddress1(); + this.address2 = projects.getAddress2(); + this.street = projects.getStreet(); + this.city = projects.getCity(); + this.state = projects.getState(); + this.country = projects.getCountry(); + this.zipCode = projects.getZipCode(); + this.employeeBeanList = employee; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java new file mode 100644 index 00000000..e4a3c3df --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java @@ -0,0 +1,78 @@ +package com.espark.adarsh.entities; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; +import java.io.Serializable; +import java.util.Arrays; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +@Setter +@Getter +@Entity +@Table(name = "employee") +public class Employee implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @NotNull + @Size(max = 65) + @Column(name = "first_name") + protected String firstName; + + @Size(max = 65) + @Column(name = "last_name") + protected String lastName; + + @Enumerated(EnumType.STRING) + @Column(length = 10) + protected Gender gender; + + @NotNull + @Email + @Size(max = 100) + @Column(unique = true) + protected String email; + + @Temporal(TemporalType.DATE) + @Column(name = "dob") + protected Date dob; + + @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) + @JoinTable( + name = "employee_project", + joinColumns = {@JoinColumn(name = "employee_id")}, + inverseJoinColumns = {@JoinColumn(name = "project_id")} + ) + private List projects = new LinkedList<>(); + + public Employee() { + } + + public Employee(@NotNull @Size(max = 65) String firstName + , @Size(max = 65) String lastName + , Gender gender + , @NotNull @Email @Size(max = 100) String email + , Date dob) { + this.firstName = firstName; + this.lastName = lastName; + this.gender = gender; + this.email = email; + this.dob = dob; + } + + public void setProject(Projects project) { + if (this.projects != null) { + projects.add(project); + } else { + this.projects = Arrays.asList(project); + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java new file mode 100644 index 00000000..71f78d64 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.entities; + +public enum Gender { + MALE, + FEMALE +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Projects.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Projects.java new file mode 100644 index 00000000..9d4cbfec --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Projects.java @@ -0,0 +1,98 @@ +package com.espark.adarsh.entities; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Arrays; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +@Setter +@Getter +@Entity +@Table(name = "projects") +public class Projects implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @Size(max = 100) + protected String name; + + @Column(name = "phone_number") + @Size(max = 15) + protected String phoneNumber; + + @Temporal(TemporalType.DATE) + @Column(name = "start") + protected Date start; + + @Temporal(TemporalType.DATE) + @Column(name = "end") + protected Date end; + + @Size(max = 100) + protected String address1; + + @Size(max = 100) + protected String address2; + + @Size(max = 100) + protected String street; + + @Size(max = 100) + protected String city; + + @Size(max = 100) + protected String state; + + @Size(max = 100) + protected String country; + + @Column(name = "zip_code") + @Size(max = 32) + protected String zipCode; + + @ManyToMany(mappedBy = "projects", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) + private List employees = new LinkedList<>(); + + public Projects() { + + } + + public Projects(@Size(max = 100) String name + , @Size(max = 15) String phoneNumber + , Date start + , Date end + , @Size(max = 100) String address1 + , @Size(max = 100) String address2 + , @Size(max = 100) String street + , @Size(max = 100) String city + , @Size(max = 100) String state + , @Size(max = 100) String country + , @Size(max = 32) String zipCode) { + this.name = name; + this.phoneNumber = phoneNumber; + this.start = start; + this.end = end; + this.address1 = address1; + this.address2 = address2; + this.street = street; + this.city = city; + this.state = state; + this.country = country; + this.zipCode = zipCode; + } + + public void setEmployee(Employee employees) { + if (this.employees != null) { + this.employees.add(employees); + } else { + this.employees = Arrays.asList(employees); + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..9e2ffbc2 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/ProjectsRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/ProjectsRepository.java new file mode 100644 index 00000000..de8544a3 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/ProjectsRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.Projects; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ProjectsRepository extends JpaRepository { + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java new file mode 100644 index 00000000..7a310c0f --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java @@ -0,0 +1,107 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entities.Gender; +import com.espark.adarsh.entities.Employee; +import com.espark.adarsh.entities.Projects; +import com.espark.adarsh.respository.ProjectsRepository; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; +import java.util.Arrays; +import java.util.Calendar; + +@Service +public class DbInitService { + + + @Autowired + DataSource dataSource; + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + ProjectsRepository projectsRepository; + + @PostConstruct + public void init() { + + Calendar proj1Start = Calendar.getInstance(); + proj1Start.set(2001, 1, 1); + Calendar proj1End = Calendar.getInstance(); + proj1End.set(2010, 1, 1); + Projects projectsOne = new Projects( + "project1" + , "+1-1122334455" + , proj1Start.getTime() + , proj1End.getTime() + , "" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + + Calendar proj2Start = Calendar.getInstance(); + proj2Start.set(2010, 1, 1); + Calendar proj2End = Calendar.getInstance(); + proj2End.set(2020, 1, 1); + Projects projectsTwo = new Projects( + "project2" + , "+1-1122334455" + , proj2Start.getTime() + , proj2End.getTime() + , "" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + projectsOne = this.projectsRepository.save(projectsOne); + projectsTwo = this.projectsRepository.save(projectsTwo); + + Calendar adarshDob = Calendar.getInstance(); + adarshDob.set(2020, 1, 1); + Employee adarsh = new Employee("Adarsh" + , "Singh" + , Gender.MALE + , "adarsh@espark" + , adarshDob.getTime()); + adarsh = employeeRepository.save(adarsh); + + + Calendar radhaDob = Calendar.getInstance(); + radhaDob.set(2020, 1, 1); + Employee radha = new Employee("Radha" + , "Singh" + , Gender.MALE + , "radha@espark" + , radhaDob.getTime()); + radha = employeeRepository.save(radha); + + projectsOne.setEmployee(adarsh); + projectsOne.setEmployee(radha); + this.projectsRepository.save(projectsOne); + + projectsTwo.setEmployee(adarsh); + projectsTwo.setEmployee(radha); + this.projectsRepository.save(projectsTwo); + + adarsh.setProject(projectsOne); + adarsh.setProject(projectsTwo); + this.employeeRepository.save(adarsh); + radha.setProject(projectsOne); + radha.setProject(projectsTwo); + this.employeeRepository.save(radha); + + + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java new file mode 100644 index 00000000..4bc01be8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.bean.ProjectsBean; +import com.espark.adarsh.respository.ProjectsRepository; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class EmployeeInfoService { + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + ProjectsRepository projectsRepository; + + public List getEmployee() { + List employeeBeans = new LinkedList<>(); + this.employeeRepository + .findAll() + .forEach(employee -> employeeBeans.add(new EmployeeBean(employee, + employee.getProjects() + .stream() + .map(employeeExperience -> + new ProjectsBean(employeeExperience) + ).collect(Collectors.toList())))); + return employeeBeans; + } + + public List getEmployeeExperience() { + List projectsBeans = new LinkedList<>(); + this.projectsRepository + .findAll() + .forEach(projects -> + projectsBeans.add(new ProjectsBean(projects + , projects.getEmployees() + .stream() + .map(employee -> new EmployeeBean(employee)) + .collect(Collectors.toList()))) + ); + return projectsBeans; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..b921aa18 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.bean.ProjectsBean; +import com.espark.adarsh.service.EmployeeInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + EmployeeInfoService employeeInfoService; + + @GetMapping("/employee") + public List getEmployees() { + return this.employeeInfoService.getEmployee(); + } + + @GetMapping("/employee-project") + public List getEmployeeProjects() { + return this.employeeInfoService.getEmployeeExperience(); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..34b624d2 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/main/resources/application.yml @@ -0,0 +1,32 @@ +logging: + level: + root: DEBUG + org: + hibernate: + SQL: DEBUG + type: + descriptor: + sql: + BasicBinder: TRACE + +spring: + application: + name: one-to-one-bidirectional + h2: + console: + enabled: true + datasource: + url: jdbc:h2:mem:testdb + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-many-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/document/help.txt new file mode 100644 index 00000000..0c020cd3 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/document/help.txt @@ -0,0 +1,12 @@ + +# to build +$ mvn clean package + +#to run +$ mvn spring-boot:run + +$ curl http://localhost:8080/api/employee +$ curl http://localhost:8080/api/employee-experience + +## h2 db console url +http://localhost:8080/h2-console \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/pom.xml new file mode 100644 index 00000000..83815047 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-one-to-many-bidirectional + 0.0.1-SNAPSHOT + springboot-jpa-one-to-many-bidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..3af14e2a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.Employee; +import com.espark.adarsh.entities.EmployeeExperience; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EmployeeBean extends Employee implements Serializable { + + private List employeeExperienceBeans; + + public EmployeeBean() { + } + + public EmployeeBean(Employee employee) { + this.id = employee.getId(); + this.firstName = employee.getFirstName(); + this.lastName = employee.getLastName(); + this.email = employee.getEmail(); + this.dob = employee.getDob(); + this.employeeExperienceBeans = null; + } + + public EmployeeBean(Employee employee, List list) { + this.id = employee.getId(); + this.firstName = employee.getFirstName(); + this.lastName = employee.getLastName(); + this.email = employee.getEmail(); + this.dob = employee.getDob(); + this.employeeExperienceBeans = list; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeExperienceBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeExperienceBean.java new file mode 100644 index 00000000..f06c0b51 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/bean/EmployeeExperienceBean.java @@ -0,0 +1,47 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.EmployeeExperience; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EmployeeExperienceBean extends EmployeeExperience + implements Serializable { + + EmployeeBean employeeBean; + + public EmployeeExperienceBean() { + } + + public EmployeeExperienceBean(EmployeeExperience employeeExperience) { + this.id = employeeExperience.getId(); + this.phoneNumber = employeeExperience.getPhoneNumber(); + this.start = employeeExperience.getStart(); + this.end = employeeExperience.getEnd(); + this.address1 = employeeExperience.getAddress1(); + this.address2 = employeeExperience.getAddress2(); + this.street = employeeExperience.getStreet(); + this.city = employeeExperience.getCity(); + this.state = employeeExperience.getState(); + this.country = employeeExperience.getCountry(); + this.zipCode = employeeExperience.getZipCode(); + } + + public EmployeeExperienceBean(EmployeeExperience employeeExperience, EmployeeBean employee) { + this.id = employeeExperience.getId(); + this.phoneNumber = employeeExperience.getPhoneNumber(); + this.start = employeeExperience.getStart(); + this.end = employeeExperience.getEnd(); + this.address1 = employeeExperience.getAddress1(); + this.address2 = employeeExperience.getAddress2(); + this.street = employeeExperience.getStreet(); + this.city = employeeExperience.getCity(); + this.state = employeeExperience.getState(); + this.country = employeeExperience.getCountry(); + this.zipCode = employeeExperience.getZipCode(); + this.employeeBean = employee; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java new file mode 100644 index 00000000..47487204 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Employee.java @@ -0,0 +1,65 @@ +package com.espark.adarsh.entities; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +@Setter +@Getter +@Entity +@Table(name = "employee") +public class Employee implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @NotNull + @Size(max = 65) + @Column(name = "first_name") + protected String firstName; + + @Size(max = 65) + @Column(name = "last_name") + protected String lastName; + + @Enumerated(EnumType.STRING) + @Column(length = 10) + protected Gender gender; + + @NotNull + @Email + @Size(max = 100) + @Column(unique = true) + protected String email; + + @Temporal(TemporalType.DATE) + @Column(name = "dob") + protected Date dob; + + @OneToMany(mappedBy = "employee" + , cascade = CascadeType.ALL + , orphanRemoval = true) + private List employeeExperience; + + public Employee() { + } + + public Employee(@NotNull @Size(max = 65) String firstName + , @Size(max = 65) String lastName + , Gender gender + , @NotNull @Email @Size(max = 100) String email + , Date dob) { + this.firstName = firstName; + this.lastName = lastName; + this.gender = gender; + this.email = email; + this.dob = dob; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/EmployeeExperience.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/EmployeeExperience.java new file mode 100644 index 00000000..e7bc75e0 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/EmployeeExperience.java @@ -0,0 +1,87 @@ +package com.espark.adarsh.entities; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Date; + +@Setter +@Getter +@Entity +@Table(name = "employee_experience") +public class EmployeeExperience implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @Size(max = 100) + protected String coyName; + + @Column(name = "phone_number") + @Size(max = 15) + protected String phoneNumber; + + @Temporal(TemporalType.DATE) + @Column(name = "start") + protected Date start; + + @Temporal(TemporalType.DATE) + @Column(name = "end") + protected Date end; + + @Size(max = 100) + protected String address1; + + @Size(max = 100) + protected String address2; + + @Size(max = 100) + protected String street; + + @Size(max = 100) + protected String city; + + @Size(max = 100) + protected String state; + + @Size(max = 100) + protected String country; + + @Column(name = "zip_code") + @Size(max = 32) + protected String zipCode; + + @ManyToOne(fetch = FetchType.LAZY) + private Employee employee; + + public EmployeeExperience() { + + } + + public EmployeeExperience(@Size(max = 100) String coyName + , @Size(max = 15) String phoneNumber + , Date start + , Date end + , @Size(max = 100) String address1 + , @Size(max = 100) String address2 + , @Size(max = 100) String street + , @Size(max = 100) String city + , @Size(max = 100) String state + , @Size(max = 100) String country + , @Size(max = 32) String zipCode) { + this.coyName = coyName; + this.phoneNumber = phoneNumber; + this.start = start; + this.end = end; + this.address1 = address1; + this.address2 = address2; + this.street = street; + this.city = city; + this.state = state; + this.country = country; + this.zipCode = zipCode; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java new file mode 100644 index 00000000..71f78d64 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.entities; + +public enum Gender { + MALE, + FEMALE +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeExperienceRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeExperienceRepository.java new file mode 100644 index 00000000..b38effe1 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeExperienceRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.EmployeeExperience; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeExperienceRepository extends JpaRepository { + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..9e2ffbc2 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java new file mode 100644 index 00000000..81ce17cb --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java @@ -0,0 +1,133 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entities.Gender; +import com.espark.adarsh.entities.Employee; +import com.espark.adarsh.entities.EmployeeExperience; +import com.espark.adarsh.respository.EmployeeExperienceRepository; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; +import java.util.Arrays; +import java.util.Calendar; + +@Service +public class DbInitService { + + + @Autowired + DataSource dataSource; + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + EmployeeExperienceRepository employeeExperienceRepository; + + @PostConstruct + public void init() { + Calendar adarshDob = Calendar.getInstance(); + adarshDob.set(2020, 1, 1); + Employee adarsh = new Employee("Adarsh" + , "Singh" + , Gender.MALE + , "adarsh@espark" + , adarshDob.getTime()); + + Calendar adarshCoy1Start = Calendar.getInstance(); + adarshCoy1Start.set(2001, 1, 1); + Calendar adarshCoy1End = Calendar.getInstance(); + adarshCoy1End.set(2010, 1, 1); + EmployeeExperience adarshCoy1 = new EmployeeExperience( + "coy1" + ,"+1-1122334455" + , adarshCoy1Start.getTime() + , adarshCoy1End.getTime() + ,"" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + + Calendar adarshCoy2Start = Calendar.getInstance(); + adarshCoy2Start.set(2010, 1, 1); + Calendar adarshCoy2End = Calendar.getInstance(); + adarshCoy2End.set(2020, 1, 1); + EmployeeExperience adarshCoy2 = new EmployeeExperience( + "coy2" + ,"+1-1122334455" + , adarshCoy2Start.getTime() + , adarshCoy2End.getTime() + ,"" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + adarsh.setEmployeeExperience(Arrays.asList(adarshCoy1,adarshCoy2)); + adarshCoy1.setEmployee(adarsh); + adarshCoy2.setEmployee(adarsh); + employeeRepository.save(adarsh); + + + Calendar radhaDob = Calendar.getInstance(); + radhaDob.set(2020, 1, 1); + Employee radha = new Employee("Radha" + , "Singh" + , Gender.MALE + , "radha@espark" + , radhaDob.getTime()); + + Calendar radhaCoy1Start = Calendar.getInstance(); + radhaCoy1Start.set(2001, 1, 1); + Calendar radhaCoy1End = Calendar.getInstance(); + radhaCoy1End.set(2010, 1, 1); + EmployeeExperience radhaCoy1 = new EmployeeExperience( + "coy1" + ,"+1-55226688" + , radhaCoy1Start.getTime() + , radhaCoy1End.getTime() + ,"" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + + Calendar radhaCoy2Start = Calendar.getInstance(); + radhaCoy2Start.set(2010, 1, 1); + Calendar radhaCoy2End = Calendar.getInstance(); + radhaCoy2End.set(2020, 1, 1); + EmployeeExperience radhaCoy2 = new EmployeeExperience( + "coy2" + ,"+1-1122334455" + , radhaCoy2Start.getTime() + , radhaCoy2End.getTime() + ,"" + , "Indian Point" + , "Indian Street" + , "Dallas" + , "TX" + , "US" + , "347571"); + + radha.setEmployeeExperience(Arrays.asList(radhaCoy1,radhaCoy2)); + radhaCoy1.setEmployee(radha); + radhaCoy2.setEmployee(radha); + employeeRepository.save(radha); + + /* Resource initSchema = new ClassPathResource("db.sql_bkp"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource);*/ + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java new file mode 100644 index 00000000..707708ce --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/service/EmployeeInfoService.java @@ -0,0 +1,47 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.bean.EmployeeExperienceBean; +import com.espark.adarsh.respository.EmployeeExperienceRepository; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class EmployeeInfoService { + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + EmployeeExperienceRepository employeeExperienceRepository; + + public List getEmployee() { + List employeeBeans = new LinkedList<>(); + this.employeeRepository + .findAll() + .forEach(employee -> employeeBeans.add(new EmployeeBean(employee, + employee.getEmployeeExperience() + .stream() + .map(employeeExperience -> + new EmployeeExperienceBean(employeeExperience) + ).collect(Collectors.toList())))); + return employeeBeans; + } + + public List getEmployeeExperience() { + List employeeExperienceBeans = new LinkedList<>(); + this.employeeExperienceRepository + .findAll() + .forEach(employeeExperience -> + employeeExperienceBeans.add(new EmployeeExperienceBean(employeeExperience + , new EmployeeBean(employeeExperience.getEmployee()))) + ); + return employeeExperienceBeans; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..16e9382c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.bean.EmployeeExperienceBean; +import com.espark.adarsh.service.EmployeeInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + EmployeeInfoService employeeInfoService; + + @GetMapping("/employee") + public List getEmployees() { + return this.employeeInfoService.getEmployee(); + } + + @GetMapping("/employee-experience") + public List getEmployeeExperience() { + return this.employeeInfoService.getEmployeeExperience(); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..34b624d2 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/main/resources/application.yml @@ -0,0 +1,32 @@ +logging: + level: + root: DEBUG + org: + hibernate: + SQL: DEBUG + type: + descriptor: + sql: + BasicBinder: TRACE + +spring: + application: + name: one-to-one-bidirectional + h2: + console: + enabled: true + datasource: + url: jdbc:h2:mem:testdb + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-many-bidirectional/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/db.sql_bkp b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/db.sql_bkp new file mode 100644 index 00000000..f193d13c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/db.sql_bkp @@ -0,0 +1,69 @@ + + + + + drop table user_profiles if exists; + + create table user_profiles ( + id bigint generated by default as identity, + address1 varchar(100), + address2 varchar(100), + city varchar(100), + country varchar(100), + dob date, + gender varchar(10), + phone_number varchar(15), + state varchar(100), + street varchar(100), + zip_code varchar(32), + user_id bigint not null, + primary key (id) +); + + drop table users if exists; + + create table users ( + id bigint generated by default as identity, + email varchar(100) not null, + first_name varchar(65) not null, + last_name varchar(65), + password varchar(128) not null, + primary key (id) + ); + + alter table user_profiles add constraint UK_user_id_key unique (user_id); + + alter table users add constraint UK_email_key unique (email); + + alter table user_profiles add constraint FK_user_id_users_key foreign key (user_id) references users; + + + + insert + into + users + (id, email, first_name, last_name, password) + values + (1, 'adarsh@kumar', 'adarsh', 'kumar', '@123@abc') + + insert + into + user_profiles + (id, address1, address2, city, country, dob, gender, phone_number, state, street, user_id, zip_code) + values + (1, 'indiian place', 'indian point', 'dallas', 'usa', '2020-02-01', 'MALE', '+122334455', 'tx', 'india street', '1', '75034') + + + insert + into + users + (id, email, first_name, last_name, password) + values + (2, 'radha@singh', 'radha', 'singh', '@123@abc') + + insert + into + user_profiles + (id, address1, address2, city, country, dob, gender, phone_number, state, street, user_id, zip_code) + values + (1, 'indiian place', 'indian point', 'dallas', 'usa', '2020-02-01', 'MALE', '+122334455', 'tx', 'india street', '2', '75034') diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/help.txt new file mode 100644 index 00000000..2d7bb50e --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/document/help.txt @@ -0,0 +1,12 @@ + +# to build +$ mvn clean package + +#to run +$ mvn spring-boot:run + +$ curl http://localhost:8080/api/users +$ curl http://localhost:8080/api/userprofiles + +## h2 db console url +http://localhost:8080/h2-console \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/pom.xml new file mode 100644 index 00000000..1dbe02a8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-one-to-one-bidirectional + 0.0.1-SNAPSHOT + springboot-jpa-one-to-one-bidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMain.java new file mode 100644 index 00000000..ed164ec5 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JpaOneToOneBidirectionalApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(JpaOneToOneBidirectionalApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserBean.java new file mode 100644 index 00000000..993fc711 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserBean.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.User; +import com.espark.adarsh.entities.UserProfile; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UserBean implements Serializable { + + private Long id; + + private String firstName; + + private String lastName; + + private String email; + + private String password; + + private UserProfileBean userProfile; + + public UserBean() { + } + + public UserBean(User user) { + this.id = user.getId(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.email = user.getEmail(); + this.password = user.getPassword(); + this.userProfile = null; + } + + public UserBean(User user, UserProfile userProfile) { + this.id = user.getId(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.email = user.getEmail(); + this.password = user.getPassword(); + this.userProfile = new UserProfileBean(userProfile); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserProfileBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserProfileBean.java new file mode 100644 index 00000000..2720757d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/bean/UserProfileBean.java @@ -0,0 +1,72 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entities.Gender; +import com.espark.adarsh.entities.User; +import com.espark.adarsh.entities.UserProfile; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UserProfileBean implements Serializable { + + private Long id; + + private String phoneNumber; + + private Gender gender; + + private Date dateOfBirth; + + private String address1; + + private String address2; + + private String street; + + private String city; + + private String state; + + private String country; + + private String zipCode; + + private UserBean user; + + public UserProfileBean() { + } + + public UserProfileBean(UserProfile userProfile) { + this.id = userProfile.getId(); + this.phoneNumber = userProfile.getPhoneNumber(); + this.gender = userProfile.getGender(); + this.dateOfBirth = userProfile.getDateOfBirth(); + this.address1 = userProfile.getAddress1(); + this.address2 = userProfile.getAddress2(); + this.street = userProfile.getStreet(); + this.city = userProfile.getCity(); + this.state = userProfile.getState(); + this.country = userProfile.getCountry(); + this.zipCode = userProfile.getZipCode(); + this.user = null; + } + + public UserProfileBean(UserProfile userProfile, User user) { + this.id = userProfile.getId(); + this.phoneNumber = userProfile.getPhoneNumber(); + this.gender = userProfile.getGender(); + this.dateOfBirth = userProfile.getDateOfBirth(); + this.address1 = userProfile.getAddress1(); + this.address2 = userProfile.getAddress2(); + this.street = userProfile.getStreet(); + this.city = userProfile.getCity(); + this.state = userProfile.getState(); + this.country = userProfile.getCountry(); + this.zipCode = userProfile.getZipCode(); + this.user = new UserBean(user); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java new file mode 100644 index 00000000..71f78d64 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/Gender.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.entities; + +public enum Gender { + MALE, + FEMALE +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/User.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/User.java new file mode 100644 index 00000000..3737cb4d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/User.java @@ -0,0 +1,57 @@ +package com.espark.adarsh.entities; + +import com.fasterxml.jackson.annotation.JsonManagedReference; +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; +import java.io.Serializable; + +@Setter +@Getter +@Entity +@Table(name = "users") +public class User implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotNull + @Size(max = 65) + @Column(name = "first_name") + private String firstName; + + @Size(max = 65) + @Column(name = "last_name") + private String lastName; + + @NotNull + @Email + @Size(max = 100) + @Column(unique = true) + private String email; + + @NotNull + @Size(max = 128) + private String password; + + @JsonManagedReference + @OneToOne(fetch = FetchType.LAZY, + cascade = CascadeType.ALL, + mappedBy = "user") + private UserProfile userProfile; + + public User() { + } + + public User(String firstName, String lastName, String email, String password) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.password = password; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/UserProfile.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/UserProfile.java new file mode 100644 index 00000000..99970e31 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/entities/UserProfile.java @@ -0,0 +1,79 @@ +package com.espark.adarsh.entities; + +import com.fasterxml.jackson.annotation.JsonBackReference; +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Date; + +@Setter +@Getter +@Entity +@Table(name = "user_profiles") +public class UserProfile implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "phone_number") + @Size(max = 15) + private String phoneNumber; + + @Enumerated(EnumType.STRING) + @Column(length = 10) + private Gender gender; + + @Temporal(TemporalType.DATE) + @Column(name = "dob") + private Date dateOfBirth; + + @Size(max = 100) + private String address1; + + @Size(max = 100) + private String address2; + + @Size(max = 100) + private String street; + + @Size(max = 100) + private String city; + + @Size(max = 100) + private String state; + + @Size(max = 100) + private String country; + + @Column(name = "zip_code") + @Size(max = 32) + private String zipCode; + + @JsonBackReference + @OneToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + public UserProfile() { + + } + + public UserProfile(String phoneNumber, Gender gender, Date dateOfBirth, + String address1, String address2, String street, String city, + String state, String country, String zipCode) { + this.phoneNumber = phoneNumber; + this.gender = gender; + this.dateOfBirth = dateOfBirth; + this.address1 = address1; + this.address2 = address2; + this.street = street; + this.city = city; + this.state = state; + this.country = country; + this.zipCode = zipCode; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserProfileRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserProfileRepository.java new file mode 100644 index 00000000..bfe546dd --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserProfileRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.UserProfile; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserProfileRepository extends JpaRepository { + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserRepository.java new file mode 100644 index 00000000..1e14b012 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/respository/UserRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entities.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java new file mode 100644 index 00000000..76af20e0 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/DbInitService.java @@ -0,0 +1,86 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entities.Gender; +import com.espark.adarsh.entities.User; +import com.espark.adarsh.entities.UserProfile; +import com.espark.adarsh.respository.UserProfileRepository; +import com.espark.adarsh.respository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; +import java.util.Calendar; + +@Service +public class DbInitService { + + + @Autowired + DataSource dataSource; + + @Autowired + UserRepository userRepository; + + @Autowired + UserProfileRepository userProfileRepository; + + @PostConstruct + public void init() { + User adarsh = new User("Adarsh" + , "Singh" + , "adarsh@espark" + , "@123@123"); + + Calendar adarshDob = Calendar.getInstance(); + adarshDob.set(2020, 1, 1); + UserProfile adarshProfile = new UserProfile("+1-1122334455" + , Gender.MALE + , adarshDob.getTime() + , "111" + , "Indian Street" + , "Indian Point" + , "Dallas" + , "TX" + , "US" + , "347571"); + + adarsh.setUserProfile(adarshProfile); + adarshProfile.setUser(adarsh); + userRepository.save(adarsh); + + + User radha = new User("Radha" + , "Singh" + , "radha@espak" + , "@123@123"); + + Calendar radhaDob = Calendar.getInstance(); + radhaDob.set(2020, 1, 1); + UserProfile radhaProfile = new UserProfile("+1-55443322" + , Gender.MALE + , radhaDob.getTime() + , "111" + , "Indian Street" + , "Indian Point" + , "Dallas" + , "TX" + , "US" + , "347571"); + + radha.setUserProfile(radhaProfile); + radhaProfile.setUser(radha); + userRepository.save(radha); + + + /* Resource initSchema = new ClassPathResource("db.sql_bkp"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource);*/ + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/UsersInfoService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/UsersInfoService.java new file mode 100644 index 00000000..2f1d133f --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/service/UsersInfoService.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.UserBean; +import com.espark.adarsh.bean.UserProfileBean; +import com.espark.adarsh.entities.User; +import com.espark.adarsh.entities.UserProfile; +import com.espark.adarsh.respository.UserProfileRepository; +import com.espark.adarsh.respository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import java.util.LinkedList; +import java.util.List; + +@Service +public class UsersInfoService { + + @Autowired + UserRepository userRepository; + + @Autowired + UserProfileRepository userProfileRepository; + + public List getUsers() { + List users = new LinkedList<>(); + this.userRepository + .findAll() + .forEach(user -> users.add(new UserBean(user, user.getUserProfile()))); + return users; + } + + public List getUserProfiles() { + List userProfiles = new LinkedList<>(); + this.userProfileRepository + .findAll() + .forEach(userProfile -> userProfiles.add(new UserProfileBean(userProfile, userProfile.getUser()))); + return userProfiles; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..93a265e6 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.UserBean; +import com.espark.adarsh.bean.UserProfileBean; +import com.espark.adarsh.entities.UserProfile; +import com.espark.adarsh.service.UsersInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + UsersInfoService usersInfoService; + + @GetMapping("/users") + public List getUsers() { + return this.usersInfoService.getUsers(); + } + + @GetMapping("/userprofiles") + public List getUserProfiles() { + return this.usersInfoService.getUserProfiles(); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..34b624d2 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/main/resources/application.yml @@ -0,0 +1,32 @@ +logging: + level: + root: DEBUG + org: + hibernate: + SQL: DEBUG + type: + descriptor: + sql: + BasicBinder: TRACE + +spring: + application: + name: one-to-one-bidirectional + h2: + console: + enabled: true + datasource: + url: jdbc:h2:mem:testdb + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/test/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/test/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMainTests.java new file mode 100644 index 00000000..fcaa37dd --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one-bidirectional/src/test/java/com/espark/adarsh/JpaOneToOneBidirectionalApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JpaOneToOneBidirectionalApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/document/help.txt new file mode 100644 index 00000000..6305453e --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/document/help.txt @@ -0,0 +1,9 @@ +#to build the application +$ mvn clean package + +$ mvn spring-boot:run + +#log into the homepage of db +http://localhost:8080/h2-console + +username, pwd , dburl and db driver class is mentioned in application.properties file \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/pom.xml new file mode 100644 index 00000000..46fa3f28 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-one-to-one + 0.0.1-SNAPSHOT + springboot-jpa-one-to-one + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/db/DataInitializer.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/db/DataInitializer.java new file mode 100644 index 00000000..a2883dbe --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/db/DataInitializer.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.db; + +import com.espark.adarsh.entity.Address; +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.repository.AddressRepository; +import com.espark.adarsh.repository.CustomerRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class DataInitializer { + + @Autowired + CustomerRepository repository; + + @Autowired + AddressRepository addressRepository; + + @PostConstruct + public void init() { + addressRepository.save(new Address()); + repository.save(new Customer("Radha", "Singh")); + repository.save(new Customer("Adarsh", "kumar")); + repository.save(new Customer("Amit", "kumar")); + repository.save(new Customer("Chloe", "O'Brian")); + repository.save(new Customer("Kim", "Bauer")); + repository.save(new Customer("David", "Palmer")); + repository.save(new Customer("Michelle", "Dessler")); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Address.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Address.java new file mode 100644 index 00000000..db3d8725 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Address.java @@ -0,0 +1,51 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + String street; + String city; + + @OneToOne(mappedBy = "address") + private Customer customer; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public Customer getCustomer() { + return customer; + } + + public void setCustomer(Customer customer) { + this.customer = customer; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Customer.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Customer.java new file mode 100644 index 00000000..38a37931 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/entity/Customer.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.entity; + +import lombok.*; + +import javax.persistence.*; + +@Data +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ToString +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id", referencedColumnName = "id") + private Address address; + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/AddressRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/AddressRepository.java new file mode 100644 index 00000000..8d46f07e --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/AddressRepository.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Address; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +public interface AddressRepository extends CrudRepository { + + List
findByLastName(String lastName); + + Address findById(long id); +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/CustomerRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/CustomerRepository.java new file mode 100644 index 00000000..1f8fdb41 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/repository/CustomerRepository.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.repository; + +import java.util.List; + +import com.espark.adarsh.entity.Customer; +import org.springframework.data.repository.CrudRepository; + +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); + + Customer findById(long id); +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/service/CustomerService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/service/CustomerService.java new file mode 100644 index 00000000..7622e94c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/service/CustomerService.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.repository.CustomerRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class CustomerService { + + @Autowired + CustomerRepository customerRepository; + + public Customer getCustomer(Long id) { + return customerRepository.findById(id).get(); + } + + public List getAllCustomer() { + List customerList = new LinkedList<>(); + customerRepository + .findAll() + .forEach(customer -> customerList.add(customer)); + return customerList; + } + + public Customer createCustomer(Customer customer) { + return this.customerRepository.save(customer); + } + + public Customer updateCustomer(Customer customer) { + return this.customerRepository.save(customer); + } + + public Customer deleteCustomer(Long id) { + Customer customer = customerRepository.findById(id).get(); + customerRepository.delete(customer); + return customer; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/we/CustomerController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/we/CustomerController.java new file mode 100644 index 00000000..63ba9468 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/java/com/espark/adarsh/we/CustomerController.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.we; + +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.service.CustomerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class CustomerController { + + @Autowired + CustomerService customerService; + + @GetMapping("/customers") + public List getAll() { + return this.customerService.getAllCustomer(); + } + + @GetMapping("/customer/{id}") + public Customer getCustomer(@PathVariable("id") Long id) { + return this.customerService.getCustomer(id); + } + + @PutMapping("/customer/{id}") + public Customer getCustomer(@PathVariable("id") Long id, @RequestBody Customer customer) { + return this.customerService.updateCustomer(customer); + } + + @DeleteMapping("/customer/{id}") + public Customer deleteCustomer(@PathVariable("id") Long id) { + return this.customerService.deleteCustomer(id); + } + + @PostMapping("/customer") + public Customer getCustomer(@RequestBody Customer customer) { + return this.customerService.createCustomer(customer); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/resources/application.properties new file mode 100644 index 00000000..0a2b5d21 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/main/resources/application.properties @@ -0,0 +1,22 @@ + +spring.datasource.type=com.zaxxer.hikari.HikariDataSource +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true + +spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider + +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.poolName=SpringBootJPAHikariCP +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 + + +logging.level.org.hibernate.SQL=DEBUG +logging.level.com.zaxxer.hikari.HikariConfig=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java new file mode 100644 index 00000000..70857b78 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-one-to-one/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootJpaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/document/help.txt new file mode 100644 index 00000000..1315fe26 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/document/help.txt @@ -0,0 +1,29 @@ +#to build +$ mvn clean package + +$ mvn spring-boot:run + +# To test +$ curl localhost:8080/api/employee/adarsh@espark +$ curl localhost:8080/api/employees + + + + +DROP PROCEDURE IF EXISTS `GET_ALL_EMPLOYEES` ; +DELIMITER // +CREATE PROCEDURE `GET_ALL_EMPLOYEES`() +BEGIN + SELECT * FROM employee ORDER BY id; +END // + + + +DROP procedure IF EXISTS `GET_EMPLOYEE_BY_EMAIL`; +DELIMITER // +CREATE PROCEDURE GET_EMPLOYEE_BY_EMAIL(IN employeeEmail VARCHAR(100)) +BEGIN + SELECT * FROM employee WHERE email = employeeEmail ORDER BY id; +END // + +CALL GET_EMPLOYEE_BY_EMAIL('adarsh@espark'); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/pom.xml new file mode 100644 index 00000000..9205a496 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-stored-procedure + 0.0.1-SNAPSHOT + springboot-jpa-stored-procedure + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/JpaStoredProcedureApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/JpaStoredProcedureApplicationMain.java new file mode 100644 index 00000000..fe53d450 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/JpaStoredProcedureApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JpaStoredProcedureApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(JpaStoredProcedureApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..ce8638d3 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,54 @@ +package com.espark.adarsh.entity; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.validation.constraints.Email; +import java.io.Serializable; +import java.util.Date; + +@Setter +@Getter +@Entity +@Table(name = "employee") +public class Employee implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @NotNull + @Size(max = 65) + @Column(name = "first_name") + protected String firstName; + + @Size(max = 65) + @Column(name = "last_name") + protected String lastName; + + @NotNull + @Email + @Size(max = 100) + @Column(unique = true) + protected String email; + + @Temporal(TemporalType.DATE) + @Column(name = "dob") + protected Date dob; + + public Employee() { + } + + public Employee(@NotNull @Size(max = 65) String firstName + , @Size(max = 65) String lastName + , @NotNull @Email @Size(max = 100) String email + , Date dob) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.dob = dob; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..18a5e559 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + + +@Repository +public interface EmployeeRepository extends JpaRepository { + + @Query(nativeQuery = true, value = "call GET_EMPLOYEE_BY_EMAIL(:employeeEmail)") + Employee getEmployeeByEmail(@Param("employeeEmail") String employeeEmail); + + + + @Query(nativeQuery = true, value = "call GET_ALL_EMPLOYEES") + List getAllEmployees(); +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/DbInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/DbInitService.java new file mode 100644 index 00000000..d878c582 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/DbInitService.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Calendar; + +@Service +public class DbInitService { + + @Autowired + EmployeeRepository employeeRepository; + + @PostConstruct + public void init(){ + + Calendar adarshDob = Calendar.getInstance(); + adarshDob.set(2020, 1, 1); + Employee adarsh = new Employee("Adarsh" + , "Singh" + , "adarsh@espark" + , adarshDob.getTime()); + adarsh = employeeRepository.save(adarsh); + + Calendar radhaDob = Calendar.getInstance(); + radhaDob.set(2020, 1, 1); + Employee radha = new Employee("Radha" + , "Singh" + , "radha@espark" + , radhaDob.getTime()); + radha = employeeRepository.save(radha); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..4be055b6 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public List getEmployees() { + return employeeRepository.getAllEmployees(); + } + + public Employee getEmployeeByEmail(String email) { + return this.employeeRepository.getEmployeeByEmail(email); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..9796f592 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getEmployees() { + return this.employeeService.getEmployees(); + } + + @GetMapping("/employee/{email}") + public Employee getEmployeeByEmail(@PathVariable("email") String email) { + return this.employeeService.getEmployeeByEmail(email); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/application.yml new file mode 100644 index 00000000..494e77dc --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/application.yml @@ -0,0 +1,19 @@ + +server: + port: 8080 + +spring: + application: + name: sprinboot-jpa + datasource: + url: jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC + username: root + password: root1234 + jpa: + hibernate: + ddl-auto: 'create-drop' + properties: + hibernate: + format-sql: true + generate-ddl: true + show-sql: true \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/employee.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/employee.sql new file mode 100644 index 00000000..0701b764 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/main/resources/employee.sql @@ -0,0 +1,47 @@ + + +-- +-- Table structure for table `employee` +-- + +DROP TABLE IF EXISTS `employee`; +CREATE TABLE `employee` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `dob` date DEFAULT NULL, + `email` varchar(100) NOT NULL, + `first_name` varchar(65) NOT NULL, + `last_name` varchar(65) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_fopic1oh5oln2khj8eat6ino0` (`email`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- +-- Dumping data for table `employee` +-- + +LOCK TABLES `employee` WRITE; +INSERT INTO `employee` + VALUES (1,'2020-02-01','adarsh@espark','Adarsh','Singh') + ,(2,'2020-02-01','radha@espark','Radha','Singh'); +UNLOCK TABLES; + +-- +-- Dumping routines for database 'testdb' +-- + +DROP PROCEDURE IF EXISTS `GET_EMPLOYEE_BY_EMAIL` ; +DELIMITER ;; +CREATE PROCEDURE `GET_EMPLOYEE_BY_EMAIL`(IN employeeEmail VARCHAR(100)) +BEGIN + SELECT * FROM employee WHERE email = employeeEmail ORDER BY id; +END ;; +DELIMITER ; + + +DROP PROCEDURE IF EXISTS `GET_ALL_EMPLOYEES` ; +DELIMITER ;; +CREATE PROCEDURE `GET_ALL_EMPLOYEES`() +BEGIN + SELECT * FROM employee ORDER BY id; +END ;; +DELIMITER ; diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/test/java/com/espark/adarsh/JpaStoredProcedureApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/test/java/com/espark/adarsh/JpaStoredProcedureApplicationMainTests.java new file mode 100644 index 00000000..a469aaf1 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa-stored-procedure/src/test/java/com/espark/adarsh/JpaStoredProcedureApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class JpaStoredProcedureApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/document/help.txt new file mode 100644 index 00000000..6305453e --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/document/help.txt @@ -0,0 +1,9 @@ +#to build the application +$ mvn clean package + +$ mvn spring-boot:run + +#log into the homepage of db +http://localhost:8080/h2-console + +username, pwd , dburl and db driver class is mentioned in application.properties file \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/pom.xml new file mode 100644 index 00000000..8de3c5d9 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa + 0.0.1-SNAPSHOT + springboot-jpa + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/.DS_Store new file mode 100644 index 00000000..3edf4233 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/.DS_Store new file mode 100644 index 00000000..404d1a49 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/.DS_Store new file mode 100644 index 00000000..735d9370 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..a49ab89f Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/.DS_Store new file mode 100644 index 00000000..fdfd6026 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/db/DataInitializer.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/db/DataInitializer.java new file mode 100644 index 00000000..fc6b416c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/db/DataInitializer.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.db; + +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.repository.CustomerRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class DataInitializer { + + + @Autowired + CustomerRepository repository; + + @PostConstruct + public void init() { + repository.save(new Customer("Radha", "Singh")); + repository.save(new Customer("Adarsh", "kumar")); + repository.save(new Customer("Amit", "kumar")); + repository.save(new Customer("Chloe", "O'Brian")); + repository.save(new Customer("Kim", "Bauer")); + repository.save(new Customer("David", "Palmer")); + repository.save(new Customer("Michelle", "Dessler")); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/entity/Customer.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/entity/Customer.java new file mode 100644 index 00000000..cd9a1c2f --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/entity/Customer.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.entity; + +import lombok.*; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@ToString +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + + private String lastName; + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/repository/CustomerRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/repository/CustomerRepository.java new file mode 100644 index 00000000..1f8fdb41 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/repository/CustomerRepository.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.repository; + +import java.util.List; + +import com.espark.adarsh.entity.Customer; +import org.springframework.data.repository.CrudRepository; + +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); + + Customer findById(long id); +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/service/CustomerService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/service/CustomerService.java new file mode 100644 index 00000000..7622e94c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/service/CustomerService.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.repository.CustomerRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class CustomerService { + + @Autowired + CustomerRepository customerRepository; + + public Customer getCustomer(Long id) { + return customerRepository.findById(id).get(); + } + + public List getAllCustomer() { + List customerList = new LinkedList<>(); + customerRepository + .findAll() + .forEach(customer -> customerList.add(customer)); + return customerList; + } + + public Customer createCustomer(Customer customer) { + return this.customerRepository.save(customer); + } + + public Customer updateCustomer(Customer customer) { + return this.customerRepository.save(customer); + } + + public Customer deleteCustomer(Long id) { + Customer customer = customerRepository.findById(id).get(); + customerRepository.delete(customer); + return customer; + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/we/CustomerController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/we/CustomerController.java new file mode 100644 index 00000000..63ba9468 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/java/com/espark/adarsh/we/CustomerController.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.we; + +import com.espark.adarsh.entity.Customer; +import com.espark.adarsh.service.CustomerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class CustomerController { + + @Autowired + CustomerService customerService; + + @GetMapping("/customers") + public List getAll() { + return this.customerService.getAllCustomer(); + } + + @GetMapping("/customer/{id}") + public Customer getCustomer(@PathVariable("id") Long id) { + return this.customerService.getCustomer(id); + } + + @PutMapping("/customer/{id}") + public Customer getCustomer(@PathVariable("id") Long id, @RequestBody Customer customer) { + return this.customerService.updateCustomer(customer); + } + + @DeleteMapping("/customer/{id}") + public Customer deleteCustomer(@PathVariable("id") Long id) { + return this.customerService.deleteCustomer(id); + } + + @PostMapping("/customer") + public Customer getCustomer(@RequestBody Customer customer) { + return this.customerService.createCustomer(customer); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/resources/application.properties new file mode 100644 index 00000000..0a2b5d21 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/main/resources/application.properties @@ -0,0 +1,22 @@ + +spring.datasource.type=com.zaxxer.hikari.HikariDataSource +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.h2.console.enabled=true + +spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider + +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.poolName=SpringBootJPAHikariCP +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 + + +logging.level.org.hibernate.SQL=DEBUG +logging.level.com.zaxxer.hikari.HikariConfig=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java new file mode 100644 index 00000000..70857b78 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-jpa/src/test/java/com/espark/adarsh/SpringbootJpaApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootJpaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/document/help.txt new file mode 100644 index 00000000..fb551872 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/document/help.txt @@ -0,0 +1,13 @@ +#to build the application +$ mvn clean package + +$ mvn spring-boot:run + +#log into the homepage of db +http://localhost:8080/h2-console +username, pwd , dburl and db driver class is mentioned in application.yml file + +# To Fetch Data +$ curl -v localhost:8080/employees + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/pom.xml new file mode 100644 index 00000000..d2f4685a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-many-to-many-unidirectional + 0.0.1-SNAPSHOT + springboot-many-to-many-unidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/.DS_Store new file mode 100644 index 00000000..41d8ef29 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/.DS_Store new file mode 100644 index 00000000..31ed979c Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/.DS_Store new file mode 100644 index 00000000..23164e0b Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..3a722e50 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Contact.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Contact.java new file mode 100644 index 00000000..622286be --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Contact.java @@ -0,0 +1,58 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "contact") +public class Contact { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "contact_id") + private Long id; + private String street; + private String state; + private String country; + + public Contact() { + } + + public Contact(String street, String state, String country) { + this.street = street; + this.state = state; + this.country = country; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..021024ac --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,89 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "employee_id") + private Long id; + private String firstName; + private String lastName; + private String career; + + + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable(name = "employee_contact", + joinColumns = { @JoinColumn(name = "employee_id") }, + inverseJoinColumns = { @JoinColumn(name = "contact_id") }) + private List contact; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + + public Employee(String firstName, String lastName, String career, List contact) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.contact = contact; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public List getContact() { + return contact; + } + + public void setContact(List contact) { + this.contact = contact; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..81f9430d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,45 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Contact; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; +import java.util.Arrays; + +@Service +public class DataInitService { + + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + /* + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + */ + + /* employeeRepository.save(new Employee("adarsh", "kumar", "It", + Arrays.asList(new Contact("bang street", "mp", "in")))); + employeeRepository.save(new Employee("radha", "singh", "It", + Arrays.asList(new Contact("hyd street", "ap", "in")))); + employeeRepository.save(new Employee("sonu", "singh", "IT", + Arrays.asList(new Contact("ald street", "up", "in")))); + employeeRepository.save(new Employee("amit", "kumar", "Finance", + Arrays.asList(new Contact("delhi street", "delhi", "in"))));*/ + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.properties new file mode 100644 index 00000000..702da713 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.properties @@ -0,0 +1,9 @@ +logging.level.root=DEBUG +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type=TRACE + + + +spring.h2.console.path=/h2-console +spring.h2.console.settings.trace=false +spring.h2.console.settings.web-allow-others=false \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..54da917c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/application.yml @@ -0,0 +1,24 @@ + +server: + port: 8080 + +spring: + application: + name: springboot-one-one-mapping + datasource: + url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + format-sql: true + h2: + console: + enabled: true + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/data.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/data.sql new file mode 100644 index 00000000..279d91f8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/main/resources/data.sql @@ -0,0 +1,46 @@ + +drop table IF EXISTS contact; + +create table contact ( +contact_id bigint generated by default as identity +, country varchar(255) +, state varchar(255) +, street varchar(255) +, primary key (contact_id)); + +drop table IF EXISTS employee; + +create table employee ( +employee_id bigint generated by default as identity +, career varchar(255) +, first_name varchar(255) +, last_name varchar(255) +, primary key (employee_id)); + +drop table IF EXISTS employee_contact; + +create table employee_contact ( +employee_id bigint not null +, contact_id bigint not null); + +alter table employee_contact add constraint FK_contact_id_contact foreign key (contact_id) references contact; +alter table employee_contact add constraint FK_employee_id_employee foreign key (employee_id) references employee; + + +insert into contact (contact_id,street, state, country) values + (10,'bang street', 'mp', 'in'), + (20,'hyd street', 'ap', 'in'), + (30,'ald street', 'up', 'in'), + (40,'delhi street', 'delhi', 'in'); + +insert into employee (employee_id,first_name, last_name, career) values + (10,'adarsh', 'kumar', 'It'), + (20,'radha', 'singh', 'IT'), + (30,'sonu', 'singh', 'IT'), + (40,'amit', 'kumar', 'Finance'); + +insert into employee_contact(employee_id,contact_id) values +(10,10), +(20,20), +(30,30), +(40,40); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-many-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/.gitignore new file mode 100644 index 00000000..a29b8e6d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/.gitignore @@ -0,0 +1,31 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/HELP.md b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/HELP.md new file mode 100644 index 00000000..47cda201 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/HELP.md @@ -0,0 +1,18 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/maven-plugin/) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) +* [Spring Data JPA](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-jpa-and-spring-data) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) +* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/document/help.txt new file mode 100644 index 00000000..fb551872 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/document/help.txt @@ -0,0 +1,13 @@ +#to build the application +$ mvn clean package + +$ mvn spring-boot:run + +#log into the homepage of db +http://localhost:8080/h2-console +username, pwd , dburl and db driver class is mentioned in application.yml file + +# To Fetch Data +$ curl -v localhost:8080/employees + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/pom.xml new file mode 100644 index 00000000..01b3efbf --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-one-to-many-unidirectional + 0.0.1-SNAPSHOT + springboot-one-to-many-unidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/.DS_Store new file mode 100644 index 00000000..41d8ef29 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/.DS_Store new file mode 100644 index 00000000..31ed979c Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/.DS_Store new file mode 100644 index 00000000..23164e0b Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..3a722e50 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Department.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Department.java new file mode 100644 index 00000000..2bd20a76 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Department.java @@ -0,0 +1,68 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "department") +public class Department { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + private String name; + private String street; + private String state; + private String country; + + public Department() { + } + + public Department(String name, String street, String state, String country) { + this.name = name; + this.street = street; + this.state = state; + this.country = country; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..1b4721f1 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,85 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + private String firstName; + private String lastName; + private String career; + + + @ManyToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "department_id") + private Department department; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(String firstName, String lastName, String career, Department address) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.department = address; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..7b67c370 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.properties new file mode 100644 index 00000000..702da713 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.properties @@ -0,0 +1,9 @@ +logging.level.root=DEBUG +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type=TRACE + + + +spring.h2.console.path=/h2-console +spring.h2.console.settings.trace=false +spring.h2.console.settings.web-allow-others=false \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..54da917c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/application.yml @@ -0,0 +1,24 @@ + +server: + port: 8080 + +spring: + application: + name: springboot-one-one-mapping + datasource: + url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + format-sql: true + h2: + console: + enabled: true + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/data.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/data.sql new file mode 100644 index 00000000..4caa172f --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/main/resources/data.sql @@ -0,0 +1,34 @@ + +drop table IF EXISTS department; + +create table department ( +id bigint generated by default as identity +, name VARCHAR(255) +, country VARCHAR(255) +, state VARCHAR(255) +, street VARCHAR(255) +, primary key (id)); + +drop table IF EXISTS employee; + +create table employee ( +id bigint generated by default as identity +, career VARCHAR(255) +, first_name VARCHAR(255) +, last_name VARCHAR(255) +, department_id bigint +, primary key (id)); + +alter table employee add constraint FK_department_id foreign key (department_id) references department; + +insert into department (id,name,street, state, country) values + (10,'it','bang street', 'mp', 'in'), + (20,'it','hyd street', 'ap', 'in'), + (30,'it','ald street', 'up', 'in'), + (40,'fa','delhi street', 'delhi', 'in'); + +insert into employee (id,first_name, last_name, career,department_id) values + (10,'adarsh', 'kumar', 'It',10), + (20,'radha', 'singh', 'IT',20), + (30,'sonu', 'singh', 'IT',30), + (40,'amit', 'kumar', 'Finance',40); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-many-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/document/help.txt new file mode 100644 index 00000000..fb551872 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/document/help.txt @@ -0,0 +1,13 @@ +#to build the application +$ mvn clean package + +$ mvn spring-boot:run + +#log into the homepage of db +http://localhost:8080/h2-console +username, pwd , dburl and db driver class is mentioned in application.yml file + +# To Fetch Data +$ curl -v localhost:8080/employees + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/pom.xml new file mode 100644 index 00000000..55cbe8c1 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-one-to-one-unidirectional + 0.0.1-SNAPSHOT + springboot-one-to-one-unidirectional + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/.DS_Store new file mode 100644 index 00000000..41d8ef29 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/.DS_Store new file mode 100644 index 00000000..31ed979c Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/.DS_Store new file mode 100644 index 00000000..23164e0b Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..3a722e50 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Address.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Address.java new file mode 100644 index 00000000..6bd88c42 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Address.java @@ -0,0 +1,58 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + private String street; + private String state; + private String country; + + public Address() { + } + + public Address( String street, String state, String country) { + this.street = street; + this.state = state; + this.country = country; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..6af38952 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,85 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + private String firstName; + private String lastName; + private String career; + + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id") + private Address address; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(String firstName, String lastName, String career, Address address) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.address = address; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..2893f202 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,42 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Address; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + + /* employeeRepository.save(new Employee("adarsh", "kumar", "It", + new Address("bang street", "mp", "in"))); + employeeRepository.save(new Employee("radha", "singh", "It", + new Address("hyd street", "ap", "in"))); + employeeRepository.save(new Employee("sonu", "singh", "IT", + new Address("ald street", "up", "in"))); + employeeRepository.save(new Employee("amit", "kumar", "Finance", + new Address("delhi street", "delhi", "in")));*/ + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.properties new file mode 100644 index 00000000..702da713 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.properties @@ -0,0 +1,9 @@ +logging.level.root=DEBUG +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type=TRACE + + + +spring.h2.console.path=/h2-console +spring.h2.console.settings.trace=false +spring.h2.console.settings.web-allow-others=false \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.yml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.yml new file mode 100644 index 00000000..54da917c --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/application.yml @@ -0,0 +1,24 @@ + +server: + port: 8080 + +spring: + application: + name: springboot-one-one-mapping + datasource: + url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + format-sql: true + h2: + console: + enabled: true + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/data.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/data.sql new file mode 100644 index 00000000..5a1ebdd5 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/main/resources/data.sql @@ -0,0 +1,33 @@ + +drop table IF EXISTS address; + +create table address ( +id bigint generated by default as identity +, country VARCHAR(255) +, state VARCHAR(255) +, street VARCHAR(255) +, primary key (id)); + +drop table IF EXISTS employee; + +create table employee ( +id bigint generated by default as identity +, career VARCHAR(255) +, first_name VARCHAR(255) +, last_name VARCHAR(255) +, address_id bigint +, primary key (id)); + +alter table employee add constraint FK_address_id foreign key (address_id) references address; + +insert into address (id,street, state, country) values + (10,'bang street', 'mp', 'in'), + (20,'hyd street', 'ap', 'in'), + (30,'ald street', 'up', 'in'), + (40,'delhi street', 'delhi', 'in'); + +insert into employee (id,first_name, last_name, career,address_id) values + (10,'adarsh', 'kumar', 'It',10), + (20,'radha', 'singh', 'IT',20), + (30,'sonu', 'singh', 'IT',30), + (40,'amit', 'kumar', 'Finance',40); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-one-to-one-unidirectional/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/README.md b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/README.md new file mode 100644 index 00000000..bd49b427 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/README.md @@ -0,0 +1,10 @@ +# SPRINGBOOT JPA ORACLE DB + +--- + +### To Build Code +* mvn clean package + + +### [step by step guide for oracle xe db docker image cration ](oracle-db-xe-docker-image-building-process.md) + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/oracle-db-xe-docker-image-building-process.md b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/oracle-db-xe-docker-image-building-process.md new file mode 100644 index 00000000..44b20d4b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/oracle-db-xe-docker-image-building-process.md @@ -0,0 +1,111 @@ + + +# https://www.codesanook.com/setup-oracle-xe-database-on-docker-container-and-connect-with-dbeaver + +## Clone the github from oralce +* git clone git@github.com:oracle/docker-images.git + +## move to the docker file directory +* $ cd docker-images/OracleDatabase/SingleInstance/dockerfiles + +# list the supported version +* $ ls +``` +11.2.0.2 12.2.0.1 18.4.0 21.3.0 +12.1.0.2 18.3.0 19.3.0 buildContainerImage.sh +``` + +## url to download the verion of oracle zip +* https://www.oracle.com/database/technologies/xe18c-downloads.html +* copy into the same directtoy of the version in ls cmd + +## Build the docker iamge +* $ sh buildContainerImage.sh -v 18.4.0 -x + +``` +Oracle Database container image for 'xe' version 18.4.0 is ready to be extended: + + --> oracle/database:18.4.0-xe + + Build completed in 510 seconds. +``` + +## db client opernsource +* https://dbeaver.io/download/ + +## lauch the db +* $ docker run --name OracleXE \ +--shm-size=1g \ +-p 1521:1521 \ +-p 8081:8080 \ +-e ORACLE_PWD=12345 \ +-v oracle-data:/u01/app/oracle/oradata \ +oracle/database:18.4.0-xe + +``` +ORACLE PASSWORD FOR SYS AND SYSTEM: 12345 +Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts: +Confirm the password: +Configuring Oracle Listener. +Listener configuration succeeded. +Configuring Oracle Database XE. +Enter SYS user password: +****** +Enter SYSTEM user password: +***** +Enter PDBADMIN User Password: +***** +Prepare for db operation +7% complete +Copying database files +29% complete +Creating and starting Oracle instance +Completing Database Creation +47% complete +50% complete +Creating Pluggable Databases +54% complete +71% complete +Executing Post Configuration Actions +93% complete +Running Custom Scripts +100% complete +Database creation complete. For details check the logfiles at: + /opt/oracle/cfgtoollogs/dbca/XE. +Database Information: +Global Database Name:XE +System Identifier(SID):XE +Look at the log file "/opt/oracle/cfgtoollogs/dbca/XE/XE.log" for further details. + +Connect to Oracle Database using one of the connect strings: + Pluggable database: 2f7354fc4ee1/XEPDB1 + Multitenant container database: 2f7354fc4ee1 +Use https://localhost:5500/em to access Oracle Enterprise Manager for Oracle Database XE +The Oracle base remains unchanged with value /opt/oracle +######################### +DATABASE IS READY TO USE! +######################### +The following output is now a tail of the alert.log: +2021-10-05T23:03:43.054971+00:00 +XEPDB1(3):Resize operation completed for file# 10, old size 358400K, new size 368640K +2021-10-05T23:03:56.975470+00:00 +XEPDB1(3):CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):Completed: CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):ALTER DATABASE DEFAULT TABLESPACE "USERS" +XEPDB1(3):Completed: ALTER DATABASE DEFAULT TABLESPACE "USERS" +2021-10-05T23:04:03.318085+00:00 +ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE +Completed: ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE + +``` + +## Connect to db +``` +Host: localhost +Port: 1521 +Database: XE +Use SID +User name: SYS +Role: SYSDBA +Password: 12345 +``` \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/pom.xml new file mode 100644 index 00000000..fdd9bed8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-oracle-db + 0.0.1-SNAPSHOT + springboot-oracle-db + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.oracle.database.jdbc + ojdbc10 + 19.3.0.0 + + + + com.zaxxer + HikariCP + 2.6.0 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/.DS_Store new file mode 100644 index 00000000..8813de11 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/.DS_Store new file mode 100644 index 00000000..e8e05c2d Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/.DS_Store new file mode 100644 index 00000000..3705dc35 Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..08d27d3d Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/.DS_Store b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/.DS_Store new file mode 100644 index 00000000..35af2b5e Binary files /dev/null and b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/.DS_Store differ diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..bea6c6b4 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long empId; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long empId, String firstName, String lastName, String career) { + this.empId = empId; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getEmpId() { + return empId; + } + + public void setEmpId(Long empId) { + this.empId = empId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/application.properties new file mode 100644 index 00000000..0affdca6 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/application.properties @@ -0,0 +1,23 @@ + + + + +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE +spring.datasource.username=SYSTEM +spring.datasource.password=12345 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=create-drop + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/data.sql b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/data.sql new file mode 100644 index 00000000..f4af5504 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/main/resources/data.sql @@ -0,0 +1,5 @@ + +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (100,'adarsh', 'kumar', 'It'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (200,'radha', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(300,'sonu', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(400,'amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/.gitignore b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/document/help.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/document/help.txt new file mode 100644 index 00000000..388ee345 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/document/help.txt @@ -0,0 +1,63 @@ +$ mvn clean package +$ mvn spring-boot:run + +########################################## +Post +http://localhost:9090/api/employee +========================================== +{ + "name":"adarsh" + ,"email":"adarsh@kumar" +} +========================================== +{ + "name":"radha" + ,"email":"radha@singh" +} +========================================== + +########################################## +Get +http://localhost:9090/api/employee + +[ + { + "id": 1, + "name": "adarsh", + "email": "adarsh@kumar", + "createdDate": "2018-04-07T03:03:16.000+0000", + "updatedDate": "2018-04-07T03:03:16.000+0000" + }, + { + "id": 2, + "name": "radha", + "email": "radha@singh", + "createdDate": "2018-04-07T03:03:31.000+0000", + "updatedDate": "2018-04-07T03:03:31.000+0000" + } +] + +########################################## +PUT +http://localhost:9090/api/employee/1 +{ + "id": 1, + "name": "adarsh", + "email": "adarsh@kumar.singh" +} + +########################################## +DElETE +http://localhost:9090/api/employee/3 + +########################################## +GET +SEARCH API +http://localhost:9090/api/search +http://localhost:9090/api/search?searchOr=name::radha,id::2 +http://localhost:9090/api/search?searchAnd=name::radha,id>1&searchOr=name::adarsh +http://localhost:9090/api/search?searchAnd=name::radha,id<1&searchOr=name::adarsh +Number search between +http://localhost:9090/api/search?searchBt=id:bt:0::1::false::true +Date search between +http://localhost:9090/api/search?searchBt=createdDate:bt:2016-04-14 00:00:00::2019-04-14 00:00:00::true::false \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/pom.xml b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/pom.xml new file mode 100644 index 00000000..66d8b7ce --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + springboot2-jpa + springboot2-jpa + 0.0.1-SNAPSHOT + jar + + springboot2-jpa + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + + + mysql + mysql-connector-java + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + commons-lang + commons-lang + 2.6 + + + + org.projectlombok + lombok + 1.16.0 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..e435adb0 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,14 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@EnableJpaAuditing +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/InBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/InBean.java new file mode 100644 index 00000000..ab853885 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/InBean.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.bean; + +import java.util.LinkedList; +import java.util.List; + +public class InBean { + + private List data=new LinkedList<>(); + private String fieldName; + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/RangeCriteria.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/RangeCriteria.java new file mode 100644 index 00000000..6656e95e --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/RangeCriteria.java @@ -0,0 +1,62 @@ +package com.espark.adarsh.bean; + +public class RangeCriteria{ + + private String fieldName; + private Object lowerRange; + private Object upperRange; + private boolean date; + private boolean number; + + + public RangeCriteria() { + } + + public RangeCriteria(String fieldName, Object lowerRange, Object upperRange, boolean date, boolean number) { + this.fieldName = fieldName; + this.lowerRange = lowerRange; + this.upperRange = upperRange; + this.date = date; + this.number = number; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public Object getLowerRange() { + return lowerRange; + } + + public void setLowerRange(Object lowerRange) { + this.lowerRange = lowerRange; + } + + public Object getUpperRange() { + return upperRange; + } + + public void setUpperRange(Object upperRange) { + this.upperRange = upperRange; + } + + public boolean isDate() { + return date; + } + + public void setDate(boolean date) { + this.date = date; + } + + public boolean isNumber() { + return number; + } + + public void setNumber(boolean number) { + this.number = number; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchBean.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchBean.java new file mode 100644 index 00000000..25069114 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchBean.java @@ -0,0 +1,80 @@ +package com.espark.adarsh.bean; + +import java.util.LinkedList; +import java.util.List; + +public class SearchBean { + + private Class classType; + + private List andSearchCriteria = new LinkedList<>(); + + private List orSearchCriteria = new LinkedList<>(); + + private List rangeCriteria = new LinkedList<>(); + + private List inList=new LinkedList<>(); + + private Integer pageNumber; + + private Integer pageSize; + + public SearchBean() { + } + + public Class getClassType() { + return classType; + } + + public void setClassType(Class classType) { + this.classType = classType; + } + + public List getAndSearchCriteria() { + return andSearchCriteria; + } + + public void setAndSearchCriteria(List andSearchCriteria) { + this.andSearchCriteria = andSearchCriteria; + } + + public List getOrSearchCriteria() { + return orSearchCriteria; + } + + public void setOrSearchCriteria(List orSearchCriteria) { + this.orSearchCriteria = orSearchCriteria; + } + + public List getRangeCriteria() { + return rangeCriteria; + } + + public void setRangeCriteria(List rangeCriteria) { + this.rangeCriteria = rangeCriteria; + } + + public Integer getPageNumber() { + return pageNumber; + } + + public void setPageNumber(Integer pageNumber) { + this.pageNumber = pageNumber; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public List getInList() { + return inList; + } + + public void setInList(List inList) { + this.inList = inList; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchCriteria.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchCriteria.java new file mode 100644 index 00000000..7f4ecbfb --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/bean/SearchCriteria.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.bean; + +public class SearchCriteria { + + private String key; + private String operation; + private Object value; + + public SearchCriteria() { + } + + public SearchCriteria(String key, String operation, Object value) { + this.key = key; + this.operation = operation; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/EmployeeController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/EmployeeController.java new file mode 100644 index 00000000..c0728ad5 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/EmployeeController.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + // Get a all Employee + @GetMapping("/employee") + public List getAllEmployee() { + return employeeService.getAllEmployee(); + } + + // Create a new Employee + @PostMapping("/employee") + public Employee createEmployee(@Valid @RequestBody Employee employee) { + return employeeService.createEmployee(employee); + } + + + // Get a Single Employee + @GetMapping("/employee/{id}") + public Employee getEmployeeById(@PathVariable(value = "id") Long empId) { + return this.employeeService.getEmployeeById(empId); + } + + // Update a Employee + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable(value = "id") Long empId, + @Valid @RequestBody Employee employeeDetails) { + return this.employeeService.updateEmployee(empId, employeeDetails); + } + + // Delete a Employee + @DeleteMapping("/employee/{id}") + public ResponseEntity deleteEmployee(@PathVariable(value = "id") Long empId) { + Employee employee = this.employeeService.deleteEmployee(empId); + return ResponseEntity.ok().body(employee); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/SearchController.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/SearchController.java new file mode 100644 index 00000000..2e11d4be --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/controller/SearchController.java @@ -0,0 +1,67 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.RangeCriteria; +import com.espark.adarsh.bean.SearchBean; +import com.espark.adarsh.bean.SearchCriteria; +import com.espark.adarsh.entity.DbEntity; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.GenericRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@RestController +@RequestMapping("/api") +public class SearchController { + + @Autowired + private GenericRepository genericRepository; + + @RequestMapping(method = RequestMethod.POST, value = "/search") + @ResponseBody + public List search(@RequestBody SearchBean search) throws Exception { + return genericRepository.search(search); + } + + @RequestMapping(method = RequestMethod.GET, value = "/search") + @ResponseBody + public List search(@RequestParam(value = "searchAnd", required = false) String searchAnd + ,@RequestParam(value = "searchOr", required = false) String searchOr + ,@RequestParam(value = "searchBt", required = false) String searchBt) throws Exception { + Pattern pattern = Pattern.compile("(\\w+?)(::|<|>|>=|=<|:eq:|:neq:|:lk:|:bt:)(\\w+?),"); + List searchAndCriteria = new ArrayList(); + if (searchAnd != null) { + Matcher matcher = pattern.matcher(searchAnd + ","); + while (matcher.find()) { + searchAndCriteria.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); + } + } + List searchOrCriteria = new ArrayList(); + if (searchOr != null) { + Matcher matcher = pattern.matcher(searchOr + ","); + while (matcher.find()) { + searchOrCriteria.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); + } + } + + List rangeCriteria=new ArrayList<>(); + if(searchBt!=null){ + Pattern patternBetween = Pattern.compile("(\\w+?)(:bt:)(\\d{4}-[01]\\d-[0-3]\\d\\s\\d{2}:\\d{2}:\\d{2})(::)(\\d{4}-[01]\\d-[0-3]\\d\\s\\d{2}:\\d{2}:\\d{2})(::)(\\w+?)(::)(\\w+?),"); + Matcher matcher = patternBetween.matcher(searchBt + ","); + while (matcher.find()) { + rangeCriteria.add(new RangeCriteria(matcher.group(1), matcher.group(3), matcher.group(5) + ,Boolean.valueOf(matcher.group(7)),Boolean.valueOf(matcher.group(9)))); + } + } + SearchBean searchBean =new SearchBean(); + searchBean.setClassType(Employee.class); + searchBean.setAndSearchCriteria(searchAndCriteria); + searchBean.setOrSearchCriteria(searchOrCriteria); + searchBean.setRangeCriteria(rangeCriteria); + return genericRepository.search(searchBean); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/DbEntity.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/DbEntity.java new file mode 100644 index 00000000..4d9dccb7 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/DbEntity.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.entity; + +import java.io.Serializable; + +public interface DbEntity extends Serializable{ +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..2dd5a2a9 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,87 @@ +package com.espark.adarsh.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import java.util.Date; + +@Entity +@Table(name = "employee") +@EntityListeners(AuditingEntityListener.class) +@JsonIgnoreProperties(value = {"createdDate", "updatedDate"}, + allowGetters = true) +public class Employee implements DbEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotBlank + private String name; + + @NotBlank + private String email; + + @Column(nullable = false, updatable = false) + @Temporal(TemporalType.TIMESTAMP) + @CreatedDate + private Date createdDate; + + @Column(nullable = false) + @Temporal(TemporalType.TIMESTAMP) + @LastModifiedDate + private Date updatedDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getUpdatedDate() { + return updatedDate; + } + + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + ", email='" + email + '\'' + + ", createdDate=" + createdDate + + ", updatedDate=" + updatedDate + + '}'; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..41539399 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + private String resourceName; + private String fieldName; + private Object fieldValue; + + public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) { + super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); + this.resourceName = resourceName; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + } + + public String getResourceName() { + return resourceName; + } + + public String getFieldName() { + return fieldName; + } + + public Object getFieldValue() { + return fieldValue; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..3c17d285 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepository.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepository.java new file mode 100644 index 00000000..550e677d --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.bean.SearchBean; +import com.espark.adarsh.entity.DbEntity; + +import java.text.ParseException; +import java.util.List; + +public interface GenericRepository { + List search(SearchBean searchBean) throws Exception; +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepositoryImpl.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepositoryImpl.java new file mode 100644 index 00000000..cdae3966 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/repository/GenericRepositoryImpl.java @@ -0,0 +1,169 @@ +package com.espark.adarsh.repository; + + +import com.espark.adarsh.bean.InBean; +import com.espark.adarsh.bean.RangeCriteria; +import com.espark.adarsh.bean.SearchBean; +import com.espark.adarsh.bean.SearchCriteria; +import com.espark.adarsh.entity.DbEntity; +import com.espark.adarsh.entity.Employee; +import org.apache.commons.lang.time.DateUtils; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.*; +import java.text.ParseException; +import java.util.Date; +import java.util.List; + +@Repository +public class GenericRepositoryImpl implements GenericRepository{ + + @Autowired + private EntityManager entityManager; + + + @Override + public List search(SearchBean searchBean) throws Exception { + List andSearchCriteria=searchBean.getAndSearchCriteria(); + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery builderQuery = builder.createQuery(searchBean.getClassType()); + Root root = builderQuery.from(searchBean.getClassType()); + Predicate predicate = builder.conjunction(); + for (SearchCriteria param : andSearchCriteria) { + if (param.getOperation().equalsIgnoreCase(">")) { + predicate = builder.and(predicate, + builder.greaterThan(root.get(param.getKey()), + param.getValue().toString())); + }else if (param.getOperation().equalsIgnoreCase(">=")) { + predicate = builder.and(predicate, + builder.greaterThanOrEqualTo(root.get(param.getKey()), + param.getValue().toString())); + }else if (param.getOperation().equalsIgnoreCase("<")) { + predicate = builder.and(predicate, + builder.lessThan(root.get(param.getKey()), + param.getValue().toString())); + }else if (param.getOperation().equalsIgnoreCase("=<")) { + predicate = builder.and(predicate, + builder.lessThanOrEqualTo(root.get(param.getKey()), + param.getValue().toString())); + }else if (param.getOperation().equalsIgnoreCase(":lk:")|| + param.getOperation().equalsIgnoreCase("::")) { + if (root.get(param.getKey()).getJavaType() == String.class) { + predicate = builder.and(predicate, + builder.like(root.get(param.getKey()), + "%" + param.getValue() + "%")); + } else { + predicate = builder.and(predicate, + builder.equal(root.get(param.getKey()), param.getValue())); + } + } else if(param.getOperation().equalsIgnoreCase(":neq:")){ + predicate = builder.and(predicate, + builder.notEqual(root.get(param.getKey()), + param.getValue().toString())); + }else if(param.getOperation().equalsIgnoreCase(":eq:")){ + predicate = builder.and(predicate, + builder.equal(root.get(param.getKey()), + param.getValue().toString())); + } + } + List orSearchCriteria=searchBean.getOrSearchCriteria(); + for (SearchCriteria param : orSearchCriteria) { + if (param.getOperation().equalsIgnoreCase(">")) { + predicate = builder.or(predicate, + builder.greaterThanOrEqualTo(root.get(param.getKey()), + param.getValue().toString())); + } else if (param.getOperation().equalsIgnoreCase("<")) { + predicate = builder.or(predicate, + builder.lessThanOrEqualTo(root.get(param.getKey()), + param.getValue().toString())); + } else if (param.getOperation().equalsIgnoreCase("lk")|| + param.getOperation().equalsIgnoreCase("::")) { + if (root.get(param.getKey()).getJavaType() == String.class) { + predicate = builder.or(predicate, + builder.like(root.get(param.getKey()), + "%" + param.getValue() + "%")); + } else { + predicate = builder.or(predicate, + builder.equal(root.get(param.getKey()), param.getValue())); + } + }else if(param.getOperation().equalsIgnoreCase("neq")){ + predicate = builder.and(predicate, + builder.notEqual(root.get(param.getKey()), + param.getValue().toString())); + }else if(param.getOperation().equalsIgnoreCase("eq")){ + predicate = builder.and(predicate, + builder.equal(root.get(param.getKey()), + param.getValue().toString())); + } + } + + List rangeCriteria = searchBean.getRangeCriteria(); + for (RangeCriteria criteria : rangeCriteria) { + if (criteria.isDate()) { + predicate = builder.between(root.get(criteria.getFieldName()) + , this.getDate(criteria.getLowerRange()) + , this.getDate(criteria.getUpperRange())); + } + if (criteria.isNumber()) { + predicate = builder.between(root.get(criteria.getFieldName()) + , Long.valueOf(criteria.getLowerRange().toString()) + , Long.valueOf(criteria.getUpperRange().toString())); + } + } + + + List inList=searchBean.getInList(); + for(InBean inBean:inList) { + final String fieldName=inBean.getFieldName(); + CriteriaBuilder.In inPredicate = builder.in(root.get(fieldName)); + for(Object value :inBean.getData()) { + inPredicate.value(value); + } + } + + builderQuery.where(predicate); + Query query =entityManager.createQuery(builderQuery); + if(searchBean.getPageNumber()!=null && searchBean.getPageSize()!=null) { + query.setFirstResult((searchBean.getPageNumber() - 1) * searchBean.getPageSize()); + query.setMaxResults(searchBean.getPageSize()); + } + List result = query.getResultList(); + return result; + } + + + // 2018-04-14 00:00:00 + private Date getDate(Object planPubTime) throws ParseException { + Date planPubDate = null; + if (!StringUtils.isEmpty(planPubTime)) { + planPubDate = DateUtils.parseDate(planPubTime.toString(), new String[]{"yyyy-MM-dd HH:mm:ss"}); + } + return planPubDate; + } + + public List getAllEmployee() { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery q = cb.createQuery(Employee.class); + Root c = q.from(Employee.class); + q.select(c); + TypedQuery query = entityManager.createQuery(q); + List results = query.getResultList(); + return results; + } + + Employee getStudentByName(String name){ + Criteria crit = entityManager.unwrap(Session.class).createCriteria(Employee.class); + crit.add(Restrictions.eq("name", name)); + List students = crit.list(); + return students.get(0); + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..454d0236 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import java.util.List; + +public interface EmployeeService { + + List getAllEmployee(); + + Employee createEmployee(Employee employee); + + Employee getEmployeeById(Long empId); + + Employee updateEmployee(Long empId, Employee employeeDetails); + + Employee deleteEmployee( Long empId); +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java new file mode 100644 index 00000000..5106f9fe --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.ResourceNotFoundException; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import java.util.List; + +@Service +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Override + public List getAllEmployee() { + return employeeRepository.findAll(); + } + + @Override + public Employee createEmployee(Employee employee) { + return employeeRepository.save(employee); + } + + @Override + public Employee getEmployeeById(Long empId) { + return employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + } + + @Override + public Employee updateEmployee(Long empId, Employee employeeDetails) { + Employee employee = employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + employee.setName(employeeDetails.getName()); + employee.setEmail(employeeDetails.getEmail()); + Employee updatedEmployee = employeeRepository.save(employee); + return updatedEmployee; + } + + @Override + public Employee deleteEmployee(Long empId) { + Employee employee = employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + employeeRepository.delete(employee); + return employee; + } +} diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/application.properties b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/application.properties new file mode 100644 index 00000000..1ef2f02b --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/application.properties @@ -0,0 +1,14 @@ +## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) +spring.datasource.url = jdbc:mysql://localhost:3306/espark?useSSL=false +spring.datasource.username = root +spring.datasource.password = root + + +## Hibernate Properties +# The SQL dialect makes Hibernate generate better SQL for the chosen database +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect + +# Hibernate ddl auto (create, create-drop, validate, update) +spring.jpa.hibernate.ddl-auto = update + +server.port=9090 \ No newline at end of file diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/banner.txt b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/banner.txt new file mode 100644 index 00000000..7d69f3c7 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/main/resources/banner.txt @@ -0,0 +1,11 @@ + + + + _____ _ _ _ _ + | ____| ___ _ __ __ _ _ __ | | __ / \ __| | __ _ _ __ ___ | |__ + | _| / __| | '_ \ / _` | | '__| | |/ / / _ \ / _` | / _` | | '__| / __| | '_ \ + | |___ \__ \ | |_) | | (_| | | | | < / ___ \ | (_| | | (_| | | | \__ \ | | | | + |_____| |___/ | .__/ \__,_| |_| |_|\_\ /_/ \_\ \__,_| \__,_| |_| |___/ |_| |_| + |_| + + diff --git a/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..e9e19a18 --- /dev/null +++ b/APPLICATIONS/SPRINGBOOT-JPA-SAMPLES/springboot2-jpa/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,60 @@ +package com.espark.adarsh; + +import com.espark.adarsh.bean.SearchBean; +import com.espark.adarsh.bean.SearchCriteria; +import com.espark.adarsh.entity.DbEntity; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.GenericRepositoryImpl; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; + +@Slf4j +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationMainTests { + + @Autowired + GenericRepositoryImpl genericRepository; + + @Test + public void contextLoads() { + List employees= this.genericRepository.getAllEmployee(); + log.info(employees.toString()); + + } + + //[Employee{id=1, name='adarsh', email='adarsh@kumar.singh', createdAt=2018-04-06 22:03:16.0, updatedAt=2018-04-06 22:06:19.0} + // , Employee{id=2, name='radha', email='radha@singh', createdAt=2018-04-06 22:03:31.0, updatedAt=2018-04-06 22:03:31.0}] + + @Test + public void searchEntity()throws Exception{ + List andSearchCriteria = new ArrayList(); + andSearchCriteria.add(new SearchCriteria("name", "::", "adarsh")); + andSearchCriteria.add(new SearchCriteria("email", "::", "adarsh@kumar.singh")); + SearchBean searchBean=new SearchBean<>(); + searchBean.setClassType(Employee.class); + searchBean.setAndSearchCriteria(andSearchCriteria); + List list= genericRepository.search(searchBean); + log.info(list.toString()); + } + + @Test + public void andSearchCriteria() throws Exception { + List andSearchCriteria = new ArrayList(); + andSearchCriteria.add(new SearchCriteria("id", ">", "0")); + andSearchCriteria.add(new SearchCriteria("id", "<", "2")); + SearchBean searchBean=new SearchBean<>(); + searchBean.setClassType(Employee.class); + searchBean.setAndSearchCriteria(andSearchCriteria); + List list= genericRepository.search(searchBean); + log.info(list.toString()); + } + + } diff --git a/APPLICATIONS/SpringBootAopExample/pom.xml b/APPLICATIONS/SpringBootAopExample/pom.xml new file mode 100644 index 00000000..033c2431 --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/pom.xml @@ -0,0 +1,128 @@ + + + 4.0.0 + + SpringBootAopExample + SpringBootAopExample + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-parent + 1.3.1.RELEASE + + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + SpringBootAopExample + UTF-8 + 1.7 + 4.13.1 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter-aop + + + + org.springframework.boot + spring-boot-starter-test + test + + + + junit + junit + ${junit.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/AopApplicationDriver.java b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/AopApplicationDriver.java new file mode 100644 index 00000000..c14f1353 --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/AopApplicationDriver.java @@ -0,0 +1,25 @@ +package com.espark.adarsh; + +import com.espark.adarsh.service.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class AopApplicationDriver implements CommandLineRunner { + + @Autowired + private MessageService messageService; + + @Override + public void run(String... args) { + System.out.println(this.messageService.getMessage()); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(AopApplicationDriver.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/monitor/ServiceMonitor.java b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/monitor/ServiceMonitor.java new file mode 100644 index 00000000..70648b8f --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/monitor/ServiceMonitor.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.monitor; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class ServiceMonitor { + + @AfterReturning("execution(* com..*Service.*(..))") + public void logServiceAccess(JoinPoint joinPoint) { + System.out.println("Completed: " + joinPoint); + } +} diff --git a/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageService.java b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageService.java new file mode 100644 index 00000000..34f7dfc5 --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageService.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.service; + +/** + * Created by Adarsh on 1/30/16. + */ +public interface MessageService { + String getMessage(); +} diff --git a/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageServiceImpl.java b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageServiceImpl.java new file mode 100644 index 00000000..c61a6eec --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/src/main/java/com/espark/adarsh/service/MessageServiceImpl.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service("messageService") +public class MessageServiceImpl implements MessageService{ + + @Value("${message:welcome}") + private String message; + + @Override + public String getMessage() { + return this.message+" "+System.getProperty("user.name"); + } +} diff --git a/APPLICATIONS/SpringBootAopExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootAopExample/src/main/resources/application.properties new file mode 100644 index 00000000..580c573b --- /dev/null +++ b/APPLICATIONS/SpringBootAopExample/src/main/resources/application.properties @@ -0,0 +1,10 @@ +message=welcome to the Spring Boot Aop + +# Log levels severity mapping. +logging.file=application.log +logging.path=\\log +logging.level.*= DEBUG +logging.level.org.springframework=ERROR + +app.route.key=espark +app.route.queue=espark \ No newline at end of file diff --git a/SpringBootBasicExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootAopExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootBasicExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootAopExample/src/main/resources/log4j.xml diff --git a/APPLICATIONS/SpringBootBasicExample/README.md b/APPLICATIONS/SpringBootBasicExample/README.md new file mode 100644 index 00000000..6ad11e38 --- /dev/null +++ b/APPLICATIONS/SpringBootBasicExample/README.md @@ -0,0 +1,19 @@ +# 1.x SpringBootBasicExample with Mock Test + +--- + +### To Build the application +* >mvn clean package + +### To Execute the Application +* >mvn spring-boot:run +* >java -jar target/SpringBootBasicExample.jar + +### To Build and Run together +* > mvn package && -jar target/SpringBootBasicExample.jar + +### To get the output +* url http://localhost:8080/api/welcome + +### To exit from Execution +* ctrl-c diff --git a/SpringBootBasicExample/doc/help.txt b/APPLICATIONS/SpringBootBasicExample/doc/help.txt similarity index 100% rename from SpringBootBasicExample/doc/help.txt rename to APPLICATIONS/SpringBootBasicExample/doc/help.txt diff --git a/SpringBootBasicExample/pom.xml b/APPLICATIONS/SpringBootBasicExample/pom.xml similarity index 98% rename from SpringBootBasicExample/pom.xml rename to APPLICATIONS/SpringBootBasicExample/pom.xml index 59455a5a..e2288298 100644 --- a/SpringBootBasicExample/pom.xml +++ b/APPLICATIONS/SpringBootBasicExample/pom.xml @@ -63,7 +63,7 @@ SpringBootBasicExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 diff --git a/SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java b/APPLICATIONS/SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java similarity index 98% rename from SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java rename to APPLICATIONS/SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java index 7d45a2dd..13e603bd 100644 --- a/SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java +++ b/APPLICATIONS/SpringBootBasicExample/src/main/java/com/espark/adarsh/SpringBootController.java @@ -47,7 +47,7 @@ */ @RestController @EnableAutoConfiguration -@RequestMapping("/application") +@RequestMapping("/api") @PropertySource("classpath:application.properties") public class SpringBootController { diff --git a/SpringBootBasicExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootBasicExample/src/main/resources/application.properties similarity index 100% rename from SpringBootBasicExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootBasicExample/src/main/resources/application.properties diff --git a/SpringBootJerseyExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootBasicExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootJerseyExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootBasicExample/src/main/resources/log4j.xml diff --git a/SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java b/APPLICATIONS/SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java similarity index 96% rename from SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java rename to APPLICATIONS/SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java index b99cf653..df0e51f3 100644 --- a/SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java +++ b/APPLICATIONS/SpringBootBasicExample/src/test/java/com/espark/adarsh/SpringBootControllerTest.java @@ -68,7 +68,7 @@ public void setUp() throws Exception { @Test public void getHello() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/application/welcome").accept(MediaType.APPLICATION_JSON)) + mvc.perform(MockMvcRequestBuilders.get("/api/welcome").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello " + System.getProperty("user.name")))); } diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/pom.xml b/APPLICATIONS/SpringBootCasandraBasicExample/pom.xml new file mode 100644 index 00000000..3574bf1d --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/pom.xml @@ -0,0 +1,127 @@ + + + + 4.0.0 + + SpringBootCasandraBasicExample + SpringBootCasandraBasicExample + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.2.5.RELEASE + + + SpringBootCasandraBasicExample + http://maven.apache.org + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + + + SpringBootCasandraBasicExample + UTF-8 + 1.8 + 4.11 + + + + + + org.springframework.boot + spring-boot-starter-web + 1.3.3.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-cassandra + 1.3.3.RELEASE + + + + org.springframework.boot + spring-boot-starter-test + 1.3.3.RELEASE + test + + + + + + + + + + + + ${project.name} + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/help.txt b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/help.txt new file mode 100644 index 00000000..e87972a9 --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/help.txt @@ -0,0 +1,19 @@ +#after installation go to this location and start the batch file +C:\Program Files\DataStax-DDC\apache-cassandra\bin\cassandra.bat + +#use the cassandra shell + +#create a file with the name db.cql +CREATE KEYSPACE IF NOT EXISTS espark WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true; +CREATE TABLE IF NOT EXISTS espark.greetings ( + user text, + id timeuuid, + greet text, + creation_date timestamp, + PRIMARY KEY (user, id) +) WITH CLUSTERING ORDER BY (id DESC); + +open cassandra shell and type this command +>cqlsh -f db.cql + + >DESCRIBE TABLE espark.greetings \ No newline at end of file diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..0101f4e2 --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,11 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/configuration/CassandraConfiguration.java b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/configuration/CassandraConfiguration.java new file mode 100644 index 00000000..00a0614f --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/configuration/CassandraConfiguration.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.configuration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.cassandra.config.CassandraClusterFactoryBean; +import org.springframework.data.cassandra.config.CassandraSessionFactoryBean; +import org.springframework.data.cassandra.config.SchemaAction; +import org.springframework.data.cassandra.convert.CassandraConverter; +import org.springframework.data.cassandra.convert.MappingCassandraConverter; +import org.springframework.data.cassandra.core.CassandraOperations; +import org.springframework.data.cassandra.core.CassandraTemplate; +import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; +import org.springframework.data.cassandra.mapping.CassandraMappingContext; +import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; +@Configuration +@PropertySource(value = {"classpath:cassandra.properties"}) +@EnableCassandraRepositories(basePackages = {"com.espark.adarsh"}) +public class CassandraConfiguration { + + private static final Logger LOGGER = LoggerFactory.getLogger(CassandraConfiguration.class); + + @Autowired + private Environment environment; + + @Bean + public CassandraClusterFactoryBean cluster() { + CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); + cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); + cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); + cluster.setUsername("cassandra"); + cluster.setPassword("cassandra"); + return cluster; + } + + @Bean + public CassandraMappingContext mappingContext() { + return new BasicCassandraMappingContext(); + } + @Bean + public CassandraConverter converter() { + return new MappingCassandraConverter(mappingContext()); + } + @Bean + public CassandraSessionFactoryBean session() throws Exception { + CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); + session.setCluster(cluster().getObject()); + session.setKeyspaceName(environment.getProperty("cassandra.keyspace")); + session.setConverter(converter()); + session.setSchemaAction(SchemaAction.NONE); + return session; + } + @Bean + public CassandraTemplate cassandraTemplate() throws Exception { + return new CassandraTemplate(session().getObject()); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/controller/GreetingController.java b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/controller/GreetingController.java new file mode 100644 index 00000000..1a9b9809 --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/controller/GreetingController.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.entites.Greeting; +import com.espark.adarsh.repository.GreetRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@RestController +public class GreetingController { + @Autowired + private GreetRepository greetRepository; + + @RequestMapping(value = "/greeting", method = RequestMethod.GET) + @ResponseBody + public List greeting() { + List greetings = new ArrayList(); + greetRepository.findAll().forEach(e -> greetings.add(e)); + return greetings; + } + + @RequestMapping(value = "/greeting/{user}/", method = RequestMethod.GET) + @ResponseBody + public List greetingUserLimit(@PathVariable String user, Integer limit) { + List greetings = new ArrayList<>(); + greetRepository.findByUser(user, limit).forEach(e -> greetings.add(e)); + return greetings; + } + + @RequestMapping(value = "/greeting", method = RequestMethod.POST) + @ResponseBody + public String saveGreeting(@RequestBody Greeting greeting) { + greeting.setCreationDate(new Date()); + greetRepository.save(greeting); + return "OK"; + } +} diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/entites/Greeting.java b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/entites/Greeting.java new file mode 100644 index 00000000..8bcf0dd9 --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/entites/Greeting.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.entites; + +import com.datastax.driver.core.utils.UUIDs; +import org.springframework.cassandra.core.PrimaryKeyType; +import org.springframework.data.cassandra.mapping.Column; +import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; +import org.springframework.data.cassandra.mapping.Table; +import java.util.Date; +import java.util.UUID; +@Table(value = "greetings") +public class Greeting { + @PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.CLUSTERED) + private UUID id = UUIDs.timeBased(); + @PrimaryKeyColumn(name="user",ordinal = 0,type = PrimaryKeyType.PARTITIONED) + private String user; + @Column(value = "greet") + private String greet; + @Column(value = "creation_date") + private Date creationDate; + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + public Date getCreationDate() { + return creationDate; + } + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + public String getUser() { + return user; + } + public void setUser(String user) { + this.user = user; + } + public String getGreet() { + return greet; + } + public void setGreet(String greet) { + this.greet = greet; + } +} diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/repository/GreetRepository.java b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/repository/GreetRepository.java new file mode 100644 index 00000000..cc3081d7 --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/java/com/espark/adarsh/repository/GreetRepository.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entites.Greeting; +import org.springframework.data.cassandra.repository.CassandraRepository; +import org.springframework.data.cassandra.repository.Query; + +import java.util.UUID; + +public interface GreetRepository extends CassandraRepository { + + @Query("SELECT*FROM greetings WHERE user=?0 LIMIT ?1") + Iterable findByUser(String user, Integer limit); + + @Query("SELECT*FROM greetings WHERE user=?0 AND id findByUserFrom(String user, UUID from, Integer limit); +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootCasandraBasicExample/src/main/resources/cassandra.properties b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/resources/cassandra.properties new file mode 100644 index 00000000..ba64d3db --- /dev/null +++ b/APPLICATIONS/SpringBootCasandraBasicExample/src/main/resources/cassandra.properties @@ -0,0 +1,4 @@ +cassandra.contactpoints=127.0.0.1 +cassandra.port=9042 +cassandra.keyspace=espark +spring.data.cassandra.connect-timeout-millis=1000000 \ No newline at end of file diff --git a/SpringBootEmbeddedLdapExample/pom.xml b/APPLICATIONS/SpringBootEmbeddedLdapExample/pom.xml similarity index 100% rename from SpringBootEmbeddedLdapExample/pom.xml rename to APPLICATIONS/SpringBootEmbeddedLdapExample/pom.xml diff --git a/SpringBootEmbeddedLdapExample/src/main/doc/help.txt b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/doc/help.txt similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/doc/help.txt rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/doc/help.txt diff --git a/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/Application.java diff --git a/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java diff --git a/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/application.properties similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/application.properties diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/espark.ldif b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/espark.ldif similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/espark.ldif rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/espark.ldif diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/log4j.xml diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.css b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.css similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.css rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.css diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/css/espark.css b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/espark.css similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/css/espark.css rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/css/espark.css diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.css b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.css similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.css rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.css diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.min.css b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.min.css similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.min.css rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/css/font-awesome.min.css diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/bordered-pulled.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/bordered-pulled.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/bordered-pulled.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/bordered-pulled.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/core.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/core.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/core.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/core.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/fixed-width.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/fixed-width.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/fixed-width.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/fixed-width.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/font-awesome.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/font-awesome.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/font-awesome.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/font-awesome.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/icons.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/icons.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/icons.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/icons.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/larger.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/larger.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/larger.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/larger.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/list.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/list.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/list.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/list.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/mixins.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/mixins.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/mixins.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/mixins.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/path.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/path.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/path.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/path.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/rotated-flipped.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/rotated-flipped.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/rotated-flipped.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/rotated-flipped.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/spinning.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/spinning.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/spinning.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/spinning.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/stacked.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/stacked.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/stacked.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/stacked.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/variables.less b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/variables.less similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/variables.less rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/less/variables.less diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_core.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_core.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_core.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_core.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_fixed-width.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_fixed-width.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_fixed-width.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_fixed-width.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_icons.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_icons.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_icons.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_icons.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_larger.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_larger.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_larger.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_larger.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_list.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_list.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_list.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_list.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_mixins.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_mixins.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_mixins.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_mixins.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_path.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_path.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_path.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_path.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_spinning.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_spinning.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_spinning.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_spinning.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_stacked.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_stacked.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_stacked.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_stacked.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_variables.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_variables.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_variables.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/_variables.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/font-awesome.scss b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/font-awesome.scss similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/font-awesome.scss rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/font/scss/font-awesome.scss diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.js b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.js similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.js rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.js diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkHome.html b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkHome.html similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkHome.html rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkHome.html diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkLoginPage.html b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkLoginPage.html similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkLoginPage.html rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkLoginPage.html diff --git a/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkUserPage.html b/APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkUserPage.html similarity index 100% rename from SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkUserPage.html rename to APPLICATIONS/SpringBootEmbeddedLdapExample/src/main/resources/templates/esparkUserPage.html diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/pom.xml b/APPLICATIONS/SpringBootEmbidedKafkaExample/pom.xml new file mode 100644 index 00000000..64cd5526 --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + SpringBootEmbidedKafkaExample + SpringBootEmbidedKafkaExample + 1.0-SNAPSHOT + + SpringBootEmbidedKafkaExample + Spring Kafka - Spring Boot Example + adarshkumarsingh83.blogspot.in + + + 1.8 + 1.2.2.RELEASE + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.kafka + spring-kafka + ${spring-kafka.version} + + + org.springframework.kafka + spring-kafka-test + ${spring-kafka.version} + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/SpringKafkaApplication.java b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/SpringKafkaApplication.java new file mode 100644 index 00000000..e63e3247 --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/SpringKafkaApplication.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringKafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringKafkaApplication.class, args); + } +} diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/consumer/Receiver.java b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/consumer/Receiver.java new file mode 100644 index 00000000..b6932a82 --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/consumer/Receiver.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.consumer; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +import java.util.concurrent.CountDownLatch; + +@Component +public class Receiver { + + private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class); + + private CountDownLatch latch = new CountDownLatch(1); + + public CountDownLatch getLatch() { + return latch; + } + + @KafkaListener(topics = "${kafka.topic.boot}") + public void receive(ConsumerRecord consumerRecord) { + LOGGER.info("received payload='{}'", consumerRecord.toString()); + latch.countDown(); + } +} diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/producer/Sender.java b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/producer/Sender.java new file mode 100644 index 00000000..2b3de7cf --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/java/com/espark/adarsh/producer/Sender.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.producer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +@Component +public class Sender { + + private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class); + + @Autowired + private KafkaTemplate kafkaTemplate; + + public void send(String topic, String payload) { + LOGGER.info("sending payload='{}' to topic='{}'", payload, topic); + kafkaTemplate.send(topic, payload); + } +} diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/application.yml b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/application.yml new file mode 100644 index 00000000..6263edfa --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/application.yml @@ -0,0 +1,9 @@ +spring: + kafka: + consumer: + auto-offset-reset: earliest + group-id: boot + +kafka: + topic: + boot: boot.t diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/logback.xml b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/logback.xml new file mode 100644 index 00000000..3f5020c6 --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/java/com/espark/adarsh/test/SpringKafkaApplicationTest.java b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/java/com/espark/adarsh/test/SpringKafkaApplicationTest.java new file mode 100644 index 00000000..cf0510df --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/java/com/espark/adarsh/test/SpringKafkaApplicationTest.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.test; + + +import com.espark.adarsh.consumer.Receiver; +import com.espark.adarsh.producer.Sender; + +import java.util.concurrent.TimeUnit; + +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.test.rule.KafkaEmbedded; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringKafkaApplicationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(SpringKafkaApplicationTest.class); + + private static String BOOT_TOPIC = "boot.t"; + + @Autowired + private Sender sender; + + @Autowired + private Receiver receiver; + + @ClassRule + public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, BOOT_TOPIC); + + @Test + public void testSendAndReceive() throws Exception { + LOGGER.info("Method Execution Start()"); + for (int i = 0; i < 10; i++) { + sender.send(BOOT_TOPIC, "Hello Kafka From Spring boot " + i); + + receiver.getLatch().await(10000, TimeUnit.MILLISECONDS); + assertThat(receiver.getLatch().getCount()).isEqualTo(0); + } + LOGGER.info("Method Execution End()"); + } +} diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/application.yml b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/application.yml new file mode 100644 index 00000000..4edf4d18 --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/application.yml @@ -0,0 +1,10 @@ +spring: + kafka: + bootstrap-servers: ${spring.embedded.kafka.brokers} + consumer: + auto-offset-reset: earliest + group-id: boot + +kafka: + topic: + boot: boot.t diff --git a/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/logback.xml b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/logback.xml new file mode 100644 index 00000000..a67fe11c --- /dev/null +++ b/APPLICATIONS/SpringBootEmbidedKafkaExample/src/test/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + diff --git a/SpringBootExternalLdapExample/pom.xml b/APPLICATIONS/SpringBootExternalLdapExample/pom.xml similarity index 100% rename from SpringBootExternalLdapExample/pom.xml rename to APPLICATIONS/SpringBootExternalLdapExample/pom.xml diff --git a/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/Application.java diff --git a/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java b/APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java similarity index 100% rename from SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java diff --git a/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java b/APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java similarity index 100% rename from SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/java/com/espark/adarsh/configuration/web/WbMvcConfiguration.java diff --git a/SpringBootExternalLdapExample/src/main/resources/ESPARK_LDAP.ldif b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/ESPARK_LDAP.ldif similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/ESPARK_LDAP.ldif rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/ESPARK_LDAP.ldif diff --git a/SpringBootExternalLdapExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/application.properties similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/application.properties diff --git a/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/espark.ldif b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/espark.ldif new file mode 100644 index 00000000..133e60a5 --- /dev/null +++ b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/espark.ldif @@ -0,0 +1,96 @@ +version: 1 + +dn: ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: organizationalUnit +ou: groups + +dn: ou=people,dc=springframework,dc=org +objectclass: top +objectclass: organizationalUnit +ou: people + +dn: uid=adarsh,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Adarsh Kumar +sn: Kumar +uid: adarsh +userPassword: adarsh + +dn: uid=radha,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Radha Singh +sn: Singh +uid: radha +userPassword: radha + +dn: uid=amit,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Amit Kumar +sn: Kumar +uid: amit +userPassword: amit + +dn: uid=user,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: User Kumar +sn: Kumar +uid: user +userPassword: user + +dn: uid=admin,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Admin Kumar +sn: Kumar +uid: admin +userPassword: admin + +dn: uid=sadmin,ou=people,dc=springframework,dc=org +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: SuperAdmin Kumar +sn: Kumar +uid: sadmin +userPassword: sadmin + +dn: cn=users,ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: groupOfNames +cn: users +ou: users +uniqueMember: uid=user,ou=people,dc=springframework,dc=org + + +dn: cn=admin,ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: groupOfNames +cn: admin +ou: admin +uniqueMember: uid=admin,ou=people,dc=springframework,dc=org +uniqueMember: uid=radha,ou=people,dc=springframework,dc=org +uniqueMember: uid=amit,ou=people,dc=springframework,dc=org + +dn: cn=superadmin,ou=groups,dc=springframework,dc=org +objectclass: top +objectclass: groupOfNames +cn: superadmin +ou: superadmin +uniqueMember: uid=sadmin,ou=people,dc=springframework,dc=org +uniqueMember: uid=adarsh,ou=people,dc=springframework,dc=org diff --git a/SpringBootExternalLdapExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/log4j.xml diff --git a/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.css b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.css similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.css rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.css diff --git a/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootExternalLdapExample/src/main/resources/static/css/espark.css b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/espark.css similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/css/espark.css rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/css/espark.css diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.css b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.css similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.css rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.css diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.min.css b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.min.css similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.min.css rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/css/font-awesome.min.css diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/FontAwesome.otf diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/bordered-pulled.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/bordered-pulled.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/bordered-pulled.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/bordered-pulled.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/core.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/core.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/core.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/core.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/fixed-width.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/fixed-width.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/fixed-width.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/fixed-width.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/font-awesome.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/font-awesome.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/font-awesome.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/font-awesome.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/icons.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/icons.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/icons.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/icons.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/larger.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/larger.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/larger.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/larger.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/list.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/list.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/list.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/list.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/mixins.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/mixins.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/mixins.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/mixins.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/path.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/path.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/path.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/path.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/rotated-flipped.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/rotated-flipped.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/rotated-flipped.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/rotated-flipped.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/spinning.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/spinning.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/spinning.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/spinning.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/stacked.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/stacked.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/stacked.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/stacked.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/less/variables.less b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/variables.less similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/less/variables.less rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/less/variables.less diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_bordered-pulled.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_core.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_core.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_core.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_core.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_fixed-width.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_fixed-width.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_fixed-width.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_fixed-width.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_icons.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_icons.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_icons.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_icons.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_larger.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_larger.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_larger.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_larger.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_list.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_list.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_list.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_list.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_mixins.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_mixins.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_mixins.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_mixins.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_path.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_path.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_path.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_path.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_rotated-flipped.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_spinning.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_spinning.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_spinning.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_spinning.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_stacked.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_stacked.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_stacked.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_stacked.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_variables.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_variables.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/_variables.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/_variables.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/font/scss/font-awesome.scss b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/font-awesome.scss similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/font/scss/font-awesome.scss rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/font/scss/font-awesome.scss diff --git a/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.js b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.js similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.js rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.js diff --git a/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootExternalLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/static/js/jquery-1.10.2.min.js diff --git a/SpringBootExternalLdapExample/src/main/resources/templates/esparkHome.html b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkHome.html similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/templates/esparkHome.html rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkHome.html diff --git a/SpringBootExternalLdapExample/src/main/resources/templates/esparkLoginPage.html b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkLoginPage.html similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/templates/esparkLoginPage.html rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkLoginPage.html diff --git a/SpringBootExternalLdapExample/src/main/resources/templates/esparkUserPage.html b/APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkUserPage.html similarity index 100% rename from SpringBootExternalLdapExample/src/main/resources/templates/esparkUserPage.html rename to APPLICATIONS/SpringBootExternalLdapExample/src/main/resources/templates/esparkUserPage.html diff --git a/SpringBootFileUploadExample/doc/help.txt b/APPLICATIONS/SpringBootFileUploadExample/doc/help.txt similarity index 100% rename from SpringBootFileUploadExample/doc/help.txt rename to APPLICATIONS/SpringBootFileUploadExample/doc/help.txt diff --git a/SpringBootFileUploadExample/pom.xml b/APPLICATIONS/SpringBootFileUploadExample/pom.xml similarity index 98% rename from SpringBootFileUploadExample/pom.xml rename to APPLICATIONS/SpringBootFileUploadExample/pom.xml index 6dd961de..440d2dfc 100644 --- a/SpringBootFileUploadExample/pom.xml +++ b/APPLICATIONS/SpringBootFileUploadExample/pom.xml @@ -64,7 +64,7 @@ SpringBootFileUploadExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 diff --git a/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootFileUploadExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/Application.java diff --git a/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/controllers/ApplicationUploadController.java b/APPLICATIONS/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/controllers/ApplicationUploadController.java similarity index 100% rename from SpringBootFileUploadExample/src/main/java/com/espark/adarsh/controllers/ApplicationUploadController.java rename to APPLICATIONS/SpringBootFileUploadExample/src/main/java/com/espark/adarsh/controllers/ApplicationUploadController.java diff --git a/SpringBootFileUploadExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/application.properties similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/application.properties diff --git a/SpringBootFileUploadExample/src/main/resources/espark.txt b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/espark.txt similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/espark.txt rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/espark.txt diff --git a/SpringBootFileUploadExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/log4j.xml diff --git a/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap-theme.min.css diff --git a/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootFileUploadExample/src/main/resources/static/index.html b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/index.html similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/index.html rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/index.html diff --git a/SpringBootFileUploadExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootFileUploadExample/src/main/resources/static/js/espark.js b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/espark.js similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/js/espark.js rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/espark.js diff --git a/SpringBootFileUploadExample/src/main/resources/static/js/jquery.min.js b/APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/jquery.min.js similarity index 100% rename from SpringBootFileUploadExample/src/main/resources/static/js/jquery.min.js rename to APPLICATIONS/SpringBootFileUploadExample/src/main/resources/static/js/jquery.min.js diff --git a/APPLICATIONS/SpringBootHibernateExample/pom.xml b/APPLICATIONS/SpringBootHibernateExample/pom.xml new file mode 100644 index 00000000..6121309f --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/pom.xml @@ -0,0 +1,138 @@ + + + 4.0.0 + + SpringBootHibernateExample + SpringBootHibernateExample + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.3.1.RELEASE + + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + SpringBootHibernateExample + UTF-8 + 1.7 + 4.13.1 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + mysql + mysql-connector-java + 5.1.31 + + + + org.springframework.boot + spring-boot-starter-test + + + + junit + junit + ${junit.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootHibernateExample/src/doc/delete user.png b/APPLICATIONS/SpringBootHibernateExample/src/doc/delete user.png new file mode 100644 index 00000000..c92a6a83 Binary files /dev/null and b/APPLICATIONS/SpringBootHibernateExample/src/doc/delete user.png differ diff --git a/APPLICATIONS/SpringBootHibernateExample/src/doc/get all user list .png b/APPLICATIONS/SpringBootHibernateExample/src/doc/get all user list .png new file mode 100644 index 00000000..e42866df Binary files /dev/null and b/APPLICATIONS/SpringBootHibernateExample/src/doc/get all user list .png differ diff --git a/APPLICATIONS/SpringBootHibernateExample/src/doc/get by email.png b/APPLICATIONS/SpringBootHibernateExample/src/doc/get by email.png new file mode 100644 index 00000000..41957ddc Binary files /dev/null and b/APPLICATIONS/SpringBootHibernateExample/src/doc/get by email.png differ diff --git a/APPLICATIONS/SpringBootHibernateExample/src/doc/help.txt b/APPLICATIONS/SpringBootHibernateExample/src/doc/help.txt new file mode 100644 index 00000000..25ede3df --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/doc/help.txt @@ -0,0 +1,58 @@ +mvn clean install +mvn package +mvn spring-boot:run + +--------------------------------------------------------------------------------------- +http://localhost:8080/user/save +Content-Type:application/json +input +{ + "id": 2, + "email": "amit@kumar", + "name": "amit" +} +output +{ + "data": null, + "message": "User successfully saved!" +} +--------------------------------------------------------------------------------------- +http://localhost:8080/user/list +output +{ + "data": [ + { + "id": 1, + "email": "adarsh@kumar", + "name": "adarsh" + }, + { + "id": 2, + "email": "amit@kumar", + "name": "amit" + } + ], + "message": "User Found " +} +--------------------------------------------------------------------------------------- +http://localhost:8080/user/delete?id=2 +output +{ + "data": null, + "message": "User successfully deleted!" +} +--------------------------------------------------------------------------------------- +http://localhost:8080/user/get-by-email?email=adarsh@kumar +output +{ + "data": { + "id": 1, + "email": "adarsh@kumar", + "name": "adarsh" + }, + "message": null +} +--------------------------------------------------------------------------------------- + + + diff --git a/APPLICATIONS/SpringBootHibernateExample/src/doc/save.png b/APPLICATIONS/SpringBootHibernateExample/src/doc/save.png new file mode 100644 index 00000000..927a0af0 Binary files /dev/null and b/APPLICATIONS/SpringBootHibernateExample/src/doc/save.png differ diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..25bbbcfa --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java new file mode 100644 index 00000000..38a11c34 --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +/** + * Created by Adarsh on 1/28/16. + */ +public class ResponseBean implements Serializable{ + private T data; + private String message; + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/configuration/PersistenceConfigurations.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/configuration/PersistenceConfigurations.java new file mode 100644 index 00000000..62b623bc --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/configuration/PersistenceConfigurations.java @@ -0,0 +1,73 @@ +package com.espark.adarsh.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +@PropertySource("classpath:/application.properties") +public class PersistenceConfigurations { + + @Value("${db.driver}") + private String DB_DRIVER; + + @Value("${db.password}") + private String DB_PASSWORD; + + @Value("${db.url}") + private String DB_URL; + + @Value("${db.username}") + private String DB_USERNAME; + + @Value("${hibernate.dialect}") + private String HIBERNATE_DIALECT; + + @Value("${hibernate.show_sql}") + private String HIBERNATE_SHOW_SQL; + + @Value("${hibernate.hbm2ddl.auto}") + private String HIBERNATE_HBM2DDL_AUTO; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(DB_DRIVER); + dataSource.setUrl(DB_URL); + dataSource.setUsername(DB_USERNAME); + dataSource.setPassword(DB_PASSWORD); + return dataSource; + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); + sessionFactoryBean.setDataSource(dataSource()); + sessionFactoryBean.setPackagesToScan("com.espark.adarsh"); + Properties hibernateProperties = new Properties(); + hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT); + hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL); + hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO); + sessionFactoryBean.setHibernateProperties(hibernateProperties); + + return sessionFactoryBean; + } + + @Bean + public HibernateTransactionManager transactionManager() { + HibernateTransactionManager transactionManager = + new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/MainController.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/MainController.java new file mode 100644 index 00000000..61c4aa1a --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/MainController.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.controllers; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class MainController { + + @RequestMapping("/") + @ResponseBody + public String index() { + return "

WELCOME TO THE APPLICATION

"; + } + +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/UserController.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/UserController.java new file mode 100644 index 00000000..3d397a4d --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/controllers/UserController.java @@ -0,0 +1,76 @@ +package com.espark.adarsh.controllers; + +import com.espark.adarsh.bean.ResponseBean; +import com.espark.adarsh.entity.User; +import com.espark.adarsh.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import java.util.List; + +@Controller +@RequestMapping(value = "/user") +public class UserController { + + @Qualifier("userRepository") + @Autowired + private UserRepository userRepository; + + @RequestMapping(value = "/delete",method = RequestMethod.DELETE) + @ResponseBody + public ResponseBean delete(long id) { + final ResponseBean userResponseBean = new ResponseBean(); + try { + final User user = new User(id); + userRepository.delete(user); + userResponseBean.setMessage("User successfully deleted!"); + } catch (Exception ex) { + userResponseBean.setMessage(ex.getMessage()); + } + return userResponseBean; + } + + @RequestMapping(value = "/get-by-email",method = RequestMethod.GET) + @ResponseBody + public ResponseBean getByEmail(String email) { + final ResponseBean userResponseBean = new ResponseBean(); + try { + final User user = userRepository.getByEmail(email); + userResponseBean.setData(user); + } catch (Exception ex) { + userResponseBean.setMessage("User not found"); + } + return userResponseBean; + } + + @RequestMapping(value = "/save",method = RequestMethod.POST) + @ResponseBody + public ResponseBean create(@RequestBody User user) { + final ResponseBean userResponseBean = new ResponseBean(); + try { + userRepository.save(user); + userResponseBean.setMessage("User successfully saved!"); + } catch (Exception ex) { + userResponseBean.setMessage(ex.getMessage()); + } + return userResponseBean; + } + + @RequestMapping(value = "/list",method = RequestMethod.GET) + @ResponseBody + public ResponseBean getAllUser() { + final ResponseBean> userResponseBean = new ResponseBean>(); + try { + userResponseBean.setData(userRepository.getAll()); + userResponseBean.setMessage("User Found "); + } catch (Exception ex) { + userResponseBean.setMessage("User Not Found "); + } + return userResponseBean; + } + +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/entity/User.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/entity/User.java new file mode 100644 index 00000000..4a09ca6a --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/entity/User.java @@ -0,0 +1,58 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +@Entity +@Table(name="users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @NotNull + @Size(min = 3, max = 80) + private String email; + + @NotNull + @Size(min = 2, max = 80) + private String name; + + public User() { } + + public User(long id) { + this.id = id; + } + + public User(String email, String name) { + this.email = email; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long value) { + this.id = value; + } + + public String getEmail() { + return email; + } + + public void setEmail(String value) { + this.email = value; + } + + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + +} // class User diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepository.java new file mode 100644 index 00000000..45367a48 --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepository.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.User; + +import java.util.List; + +/** + * Created by Adarsh on 1/28/16. + */ +public interface UserRepository { + + void save(User user); + + void delete(User user); + + List getAll(); + + User getByEmail(String email); + + User getById(long id); + + void update(User user); +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java new file mode 100644 index 00000000..9743c270 --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java @@ -0,0 +1,59 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import javax.transaction.Transactional; +import java.util.List; + +@Repository("userRepository") +@Transactional +public class UserRepositoryImpl implements UserRepository { + + @Autowired + private SessionFactory _sessionFactory; + + private Session getSession() { + return _sessionFactory.getCurrentSession(); + } + + @Override + public void save(User user) { + getSession().save(user); + return; + } + + @Override + public void delete(User user) { + getSession().delete(user); + return; + } + + @Override + public List getAll() { + return getSession().createQuery("from User").list(); + } + + @Override + public User getByEmail(String email) { + return (User) getSession().createQuery( + "from User where email = :email") + .setParameter("email", email) + .uniqueResult(); + } + + @Override + public User getById(long id) { + return (User) getSession().load(User.class, id); + } + + @Override + public void update(User user) { + getSession().update(user); + return; + } + +} diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/java/sql/script.sql b/APPLICATIONS/SpringBootHibernateExample/src/main/java/sql/script.sql new file mode 100644 index 00000000..009d53ea --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/java/sql/script.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS `espark`.`users`; +CREATE TABLE `espark`.`users` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `email` varchar(80) NOT NULL, + `name` varchar(80) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +insert into users(id,email,name) +values(1,'adarsh@kumar','adarsh') +,(2,'amit@kumar','amit'); +,(3,'radha@singh','radha'); \ No newline at end of file diff --git a/APPLICATIONS/SpringBootHibernateExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootHibernateExample/src/main/resources/application.properties new file mode 100644 index 00000000..bbb5f878 --- /dev/null +++ b/APPLICATIONS/SpringBootHibernateExample/src/main/resources/application.properties @@ -0,0 +1,17 @@ +# Thymeleaf +spring.thymeleaf.cache=false + +# Database +db.driver=com.mysql.jdbc.Driver +db.url=jdbc:mysql://localhost:3306/espark +db.username=adarsh +db.password=adarsh + +# Hibernate +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate + + + + diff --git a/SpringBootJettySSLServerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootHibernateExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootJettySSLServerExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootHibernateExample/src/main/resources/log4j.xml diff --git a/SpringBootInMemoSecurityExample/pom.xml b/APPLICATIONS/SpringBootInMemoSecurityExample/pom.xml similarity index 98% rename from SpringBootInMemoSecurityExample/pom.xml rename to APPLICATIONS/SpringBootInMemoSecurityExample/pom.xml index 4eac975e..a20ca10a 100644 --- a/SpringBootInMemoSecurityExample/pom.xml +++ b/APPLICATIONS/SpringBootInMemoSecurityExample/pom.xml @@ -57,7 +57,7 @@ SpringBootInMemoSecurityExample UTF-8 1.7 - 4.11 + 4.13.1 diff --git a/SpringBootInMemoSecurityExample/src/doc/help.txt b/APPLICATIONS/SpringBootInMemoSecurityExample/src/doc/help.txt similarity index 100% rename from SpringBootInMemoSecurityExample/src/doc/help.txt rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/doc/help.txt diff --git a/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/Application.java diff --git a/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WbMvcConfiguration.java b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WbMvcConfiguration.java similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WbMvcConfiguration.java rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WbMvcConfiguration.java diff --git a/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WebSecurityConfiguration.java b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WebSecurityConfiguration.java similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WebSecurityConfiguration.java rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/java/com/espark/adarsh/configuration/WebSecurityConfiguration.java diff --git a/SpringBootInMemoSecurityExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/application.properties similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/application.properties diff --git a/SpringBootInMemoSecurityExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/log4j.xml diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.css b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.css similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.css rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.css diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/css/espark.css b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/espark.css similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/css/espark.css rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/css/espark.css diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.css b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.css similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.css rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.css diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.min.css b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.min.css similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.min.css rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/css/font-awesome.min.css diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/FontAwesome.otf b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/FontAwesome.otf similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/FontAwesome.otf rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/FontAwesome.otf diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/bordered-pulled.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/bordered-pulled.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/bordered-pulled.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/bordered-pulled.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/core.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/core.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/core.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/core.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/fixed-width.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/fixed-width.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/fixed-width.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/fixed-width.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/font-awesome.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/font-awesome.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/font-awesome.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/font-awesome.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/icons.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/icons.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/icons.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/icons.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/larger.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/larger.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/larger.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/larger.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/list.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/list.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/list.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/list.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/mixins.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/mixins.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/mixins.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/mixins.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/path.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/path.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/path.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/path.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/rotated-flipped.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/rotated-flipped.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/rotated-flipped.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/rotated-flipped.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/spinning.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/spinning.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/spinning.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/spinning.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/stacked.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/stacked.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/stacked.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/stacked.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/variables.less b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/variables.less similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/less/variables.less rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/less/variables.less diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_bordered-pulled.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_bordered-pulled.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_bordered-pulled.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_bordered-pulled.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_core.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_core.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_core.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_core.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_fixed-width.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_fixed-width.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_fixed-width.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_fixed-width.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_icons.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_icons.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_icons.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_icons.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_larger.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_larger.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_larger.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_larger.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_list.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_list.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_list.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_list.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_mixins.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_mixins.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_mixins.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_mixins.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_path.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_path.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_path.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_path.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_rotated-flipped.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_rotated-flipped.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_rotated-flipped.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_rotated-flipped.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_spinning.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_spinning.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_spinning.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_spinning.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_stacked.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_stacked.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_stacked.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_stacked.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_variables.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_variables.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_variables.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/_variables.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/font-awesome.scss b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/font-awesome.scss similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/font-awesome.scss rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/font/scss/font-awesome.scss diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.js b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.js similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.js rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.js diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootInMemoSecurityExample/src/main/resources/static/js/jquery-1.10.2.min.js b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/jquery-1.10.2.min.js similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/static/js/jquery-1.10.2.min.js rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/static/js/jquery-1.10.2.min.js diff --git a/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkHome.html b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkHome.html similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/templates/esparkHome.html rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkHome.html diff --git a/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkLoginPage.html b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkLoginPage.html similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/templates/esparkLoginPage.html rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkLoginPage.html diff --git a/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkUserPage.html b/APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkUserPage.html similarity index 100% rename from SpringBootInMemoSecurityExample/src/main/resources/templates/esparkUserPage.html rename to APPLICATIONS/SpringBootInMemoSecurityExample/src/main/resources/templates/esparkUserPage.html diff --git a/SpringBootJerseyExample/doc/help.txt b/APPLICATIONS/SpringBootJerseyExample/doc/help.txt similarity index 100% rename from SpringBootJerseyExample/doc/help.txt rename to APPLICATIONS/SpringBootJerseyExample/doc/help.txt diff --git a/SpringBootJerseyExample/pom.xml b/APPLICATIONS/SpringBootJerseyExample/pom.xml similarity index 98% rename from SpringBootJerseyExample/pom.xml rename to APPLICATIONS/SpringBootJerseyExample/pom.xml index b1251d4b..a19f4633 100644 --- a/SpringBootJerseyExample/pom.xml +++ b/APPLICATIONS/SpringBootJerseyExample/pom.xml @@ -63,7 +63,7 @@ SpringBootJerseyExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 @@ -91,7 +91,7 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - 2.7.0 + 2.7.8 diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/entity/User.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/entity/User.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/entity/User.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/entity/User.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/Application.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/Application.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/Application.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/Application.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/ApplicationConfig.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/ApplicationConfig.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/ApplicationConfig.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/main/ApplicationConfig.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseService.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseService.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseService.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseService.java diff --git a/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java b/APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java similarity index 100% rename from SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java rename to APPLICATIONS/SpringBootJerseyExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java diff --git a/SpringBootJerseyExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJerseyExample/src/main/resources/application.properties similarity index 100% rename from SpringBootJerseyExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootJerseyExample/src/main/resources/application.properties diff --git a/SpringBootJettyServerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJerseyExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootJettyServerExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootJerseyExample/src/main/resources/log4j.xml diff --git a/SpringBootJettySSLServerExample/pom.xml b/APPLICATIONS/SpringBootJettySSLServerExample/pom.xml similarity index 98% rename from SpringBootJettySSLServerExample/pom.xml rename to APPLICATIONS/SpringBootJettySSLServerExample/pom.xml index 2779c8be..b7985272 100644 --- a/SpringBootJettySSLServerExample/pom.xml +++ b/APPLICATIONS/SpringBootJettySSLServerExample/pom.xml @@ -63,7 +63,7 @@ SpringBootJettySSLServerExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 diff --git a/SpringBootJettySSLServerExample/src/main/help/help.txt b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/help/help.txt similarity index 100% rename from SpringBootJettySSLServerExample/src/main/help/help.txt rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/help/help.txt diff --git a/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java similarity index 100% rename from SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java diff --git a/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java similarity index 100% rename from SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java diff --git a/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java similarity index 100% rename from SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java diff --git a/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java similarity index 100% rename from SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java diff --git a/SpringBootJettySSLServerExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/application.properties similarity index 100% rename from SpringBootJettySSLServerExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/application.properties diff --git a/SpringBootJettySSLServerExample/src/main/resources/espark.key b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/espark.key similarity index 100% rename from SpringBootJettySSLServerExample/src/main/resources/espark.key rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/espark.key diff --git a/SpringBootJpaExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootJpaExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootJettySSLServerExample/src/main/resources/log4j.xml diff --git a/SpringBootJettySSLServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java b/APPLICATIONS/SpringBootJettySSLServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java similarity index 100% rename from SpringBootJettySSLServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java rename to APPLICATIONS/SpringBootJettySSLServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java diff --git a/SpringBootJettyServerExample/pom.xml b/APPLICATIONS/SpringBootJettyServerExample/pom.xml similarity index 98% rename from SpringBootJettyServerExample/pom.xml rename to APPLICATIONS/SpringBootJettyServerExample/pom.xml index a596668a..4e760aa1 100644 --- a/SpringBootJettyServerExample/pom.xml +++ b/APPLICATIONS/SpringBootJettyServerExample/pom.xml @@ -63,7 +63,7 @@ SpringBootJettyServerExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 diff --git a/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java b/APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java similarity index 100% rename from SpringBootJettyServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java rename to APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/JettyApplicationDriver.java diff --git a/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootJettyServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java b/APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java similarity index 100% rename from SpringBootJettyServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java rename to APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java diff --git a/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishService.java similarity index 100% rename from SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishService.java rename to APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishService.java diff --git a/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java b/APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java similarity index 100% rename from SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java rename to APPLICATIONS/SpringBootJettyServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java diff --git a/SpringBootJettyServerExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJettyServerExample/src/main/resources/application.properties similarity index 100% rename from SpringBootJettyServerExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootJettyServerExample/src/main/resources/application.properties diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJettyServerExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootJettyServerExample/src/main/resources/log4j.xml diff --git a/SpringBootJettyServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java b/APPLICATIONS/SpringBootJettyServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java similarity index 100% rename from SpringBootJettyServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java rename to APPLICATIONS/SpringBootJettyServerExample/src/test/java/com/espark/adarsh/test/JettyApplicationTests.java diff --git a/SpringBootJpaExample/doc/help.txt b/APPLICATIONS/SpringBootJpaExample/doc/help.txt similarity index 100% rename from SpringBootJpaExample/doc/help.txt rename to APPLICATIONS/SpringBootJpaExample/doc/help.txt diff --git a/SpringBootJpaExample/pom.xml b/APPLICATIONS/SpringBootJpaExample/pom.xml similarity index 98% rename from SpringBootJpaExample/pom.xml rename to APPLICATIONS/SpringBootJpaExample/pom.xml index 84043714..91e417c6 100644 --- a/SpringBootJpaExample/pom.xml +++ b/APPLICATIONS/SpringBootJpaExample/pom.xml @@ -63,7 +63,7 @@ SpringBootJpaExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 @@ -106,7 +106,7 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - 2.7.0 + 2.7.8 diff --git a/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..344e3687 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @RequestMapping(value="/") + public String welcome() { + return "index"; + } +} + + diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/driver/Application.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/driver/Application.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/driver/Application.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/driver/Application.java diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/entities/Employee.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/entities/Employee.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/entities/Employee.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/entities/Employee.java diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeService.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeService.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeService.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeService.java diff --git a/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeServiceImpl.java b/APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeServiceImpl.java similarity index 100% rename from SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeServiceImpl.java rename to APPLICATIONS/SpringBootJpaExample/src/main/java/com/espark/adarsh/services/EmployeeServiceImpl.java diff --git a/SpringBootJpaExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJpaExample/src/main/resources/application.properties similarity index 100% rename from SpringBootJpaExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootJpaExample/src/main/resources/application.properties diff --git a/APPLICATIONS/SpringBootJpaExample/src/main/resources/data.sql b/APPLICATIONS/SpringBootJpaExample/src/main/resources/data.sql new file mode 100644 index 00000000..c13091f1 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaExample/src/main/resources/data.sql @@ -0,0 +1,5 @@ +INSERT INTO Employee(employeeId,employeeFirstName,employeeLastName,employeeEmail,employeeSalary) VALUES (100,'Adarsh','Kumar','adarsh@kumar', 500); +INSERT INTO Employee(employeeId,employeeFirstName,employeeLastName,employeeEmail,employeeSalary) VALUES (101,'Amit','Kumar','amit@kumar', 500); +INSERT INTO Employee(employeeId,employeeFirstName,employeeLastName,employeeEmail,employeeSalary) VALUES (103,'Radha','Singh','radha@singh', 500); +INSERT INTO Employee(employeeId,employeeFirstName,employeeLastName,employeeEmail,employeeSalary) VALUES (104,'Sonu','Singh','sonu@singh', 500); +INSERT INTO Employee(employeeId,employeeFirstName,employeeLastName,employeeEmail,employeeSalary) VALUES (105,'Monu','Singh','monu@singh', 500); \ No newline at end of file diff --git a/SpringBootJpaExample/src/main/resources/esaprk.sql b/APPLICATIONS/SpringBootJpaExample/src/main/resources/esaprk.sql similarity index 100% rename from SpringBootJpaExample/src/main/resources/esaprk.sql rename to APPLICATIONS/SpringBootJpaExample/src/main/resources/esaprk.sql diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJpaExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootJpaExample/src/main/resources/log4j.xml diff --git a/APPLICATIONS/SpringBootJpaExample/src/main/resources/schema.sql b/APPLICATIONS/SpringBootJpaExample/src/main/resources/schema.sql new file mode 100644 index 00000000..710022f1 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaExample/src/main/resources/schema.sql @@ -0,0 +1,9 @@ +DROP TABLE IF EXISTS `employee`; +CREATE TABLE `employee` ( + `employeeId` int(11) NOT NULL, + `employeeFirstName` varchar(50) NOT NULL, + `employeeLastName` varchar(50) NOT NULL, + `employeeEmail` varchar(50) NOT NULL, + `employeeSalary` int(15) DEFAULT NULL, + PRIMARY KEY (`employeeId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/SpringBootJpaExample/src/main/webapp/WEB-INF/web.xml b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from SpringBootJpaExample/src/main/webapp/WEB-INF/web.xml rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/WEB-INF/web.xml diff --git a/SpringBootJpaExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootJpaExample/src/main/webapp/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/css/bootstrap-theme.min.css diff --git a/SpringBootJpaExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/css/bootstrap.min.css similarity index 100% rename from SpringBootJpaExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/css/bootstrap.min.css diff --git a/SpringBootJpaExample/src/main/webapp/index.jsp b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/index.jsp similarity index 100% rename from SpringBootJpaExample/src/main/webapp/index.jsp rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/index.jsp diff --git a/SpringBootJpaExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/js/bootstrap.min.js similarity index 100% rename from SpringBootJpaExample/src/main/webapp/js/bootstrap.min.js rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/js/bootstrap.min.js diff --git a/SpringBootJpaExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootJpaExample/src/main/webapp/js/jquery.min.js similarity index 100% rename from SpringBootJpaExample/src/main/webapp/js/jquery.min.js rename to APPLICATIONS/SpringBootJpaExample/src/main/webapp/js/jquery.min.js diff --git a/APPLICATIONS/SpringBootJpaMongoExample/pom.xml b/APPLICATIONS/SpringBootJpaMongoExample/pom.xml new file mode 100644 index 00000000..c4a9a421 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/pom.xml @@ -0,0 +1,130 @@ + + + 4.0.0 + + SpringBootJpaMongoExample + SpringBootJpaMongoExample + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.3.1.RELEASE + + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + SpringBootJpaMongoExample + UTF-8 + 1.7 + 4.13.1 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-test + test + + + + junit + junit + ${junit.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/SpringBootMongoApplicationDriver.java b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/SpringBootMongoApplicationDriver.java new file mode 100644 index 00000000..b7f22871 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/SpringBootMongoApplicationDriver.java @@ -0,0 +1,64 @@ +/* + * Copyright 2012-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.espark.adarsh; + +import com.espark.adarsh.entites.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootMongoApplicationDriver implements CommandLineRunner { + + @Autowired + private EmployeeRepository repository; + + @Override + public void run(String... args) throws Exception { + this.repository.deleteAll(); + + // save a couple of customers + this.repository.save(new Employee("Adarsh", "Kumar")); + this.repository.save(new Employee("Radha", "Singh")); + + // fetch all customers + System.out.println("Customers found with findAll():"); + System.out.println("-------------------------------"); + for (Employee employee : this.repository.findAll()) { + System.out.println(employee); + } + System.out.println(); + + // fetch an individual customer + System.out.println("Employee found with findByFirstName('Adarsh'):"); + System.out.println("--------------------------------"); + System.out.println(this.repository.findByFirstName("Adarsh")); + + System.out.println("Customers found with findByLastName('Singh'):"); + System.out.println("--------------------------------"); + for (Employee employee : this.repository.findByLastName("Singh")) { + System.out.println(employee); + } + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(SpringBootMongoApplicationDriver.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/entites/Employee.java b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/entites/Employee.java new file mode 100644 index 00000000..0ab753a2 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/entites/Employee.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.entites; + +import org.springframework.data.annotation.Id; + +public class Employee { + + @Id + private String id; + + private String firstName; + private String lastName; + + public Employee() { + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + @Override + public String toString() { + return String.format("Employee[id=%s, firstName='%s', lastName='%s']", id, + firstName, lastName); + } + +} diff --git a/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..e7d6ce75 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entites.Employee; +import org.springframework.data.mongodb.repository.MongoRepository; + +import java.util.List; + +public interface EmployeeRepository extends MongoRepository { + + public Employee findByFirstName(String firstName); + + public List findByLastName(String lastName); + +} diff --git a/APPLICATIONS/SpringBootJpaMongoExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJpaMongoExample/src/main/resources/application.properties new file mode 100644 index 00000000..a6c56d3d --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.data.mongodb.port=27017 \ No newline at end of file diff --git a/SpringBootTomcatServerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJpaMongoExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootTomcatServerExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootJpaMongoExample/src/main/resources/log4j.xml diff --git a/APPLICATIONS/SpringBootJpaMongoExample/src/test/java/com/espark/adarsh/SpringBootMongoApplicationTests.java b/APPLICATIONS/SpringBootJpaMongoExample/src/test/java/com/espark/adarsh/SpringBootMongoApplicationTests.java new file mode 100644 index 00000000..f4cc38a5 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaMongoExample/src/test/java/com/espark/adarsh/SpringBootMongoApplicationTests.java @@ -0,0 +1,28 @@ +package com.espark.adarsh; + +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.OutputCapture; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(SpringBootMongoApplicationDriver.class) +@IntegrationTest +public class SpringBootMongoApplicationTests { + + @ClassRule + public static OutputCapture outputCapture = new OutputCapture(); + + @Test + public void testDefaultSettings() throws Exception { + String output = SpringBootMongoApplicationTests.outputCapture.toString(); + assertTrue("Wrong output: " + output, + output.contains("firstName='Adarsh', lastName='Kumar'")); + } + +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/doc/help.txt b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/doc/help.txt new file mode 100644 index 00000000..0af1d7d3 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/doc/help.txt @@ -0,0 +1,138 @@ + + +------------------------------------------------------------- + http://localhost:8080/employee/list + Content-Type :application/json + "data": [ + { + "employeeId": 1, + "employeeName": "adarsh kumar", + "address": { + "addressId": 1, + "addressCountry": "india", + "addressCity": "bangalore", + "employee": null + } + }, + { + "employeeId": 2, + "employeeName": "radha singh", + "address": { + "addressId": 2, + "addressCountry": "india", + "addressCity": "hyderabad", + "employee": null + } + } + ], + "message": "Employees Found " +} + +------------------------------------------------------------- +http://localhost:8080/employee/get/1 +{ + "data": { + "employeeId": 1, + "employeeName": "adarsh kumar", + "address": { + "addressId": 1, + "addressCountry": "india", + "addressCity": "bangalore", + "employee": null + } + }, + "message": "Employees Found " +} +------------------------------------------------------------- +http://localhost:8080/employee/save + Content-Type :application/json + Accept :application/json + +{ + "employeeId": 3, + "employeeName": "sonu singh", + "address": { + "addressId": 2, + "addressCountry": "india", + "addressCity": "hyderabad" + } +} +------------------------------------------------------------- +http://localhost:8080/employee/delete/3 +{ + "data": { + "employeeId": 3, + "employeeName": "sonu singh", + "address": { + "addressId": 2, + "addressCountry": "india", + "addressCity": "hyderabad", + "employee": null + } + }, + "message": "Employees Deleted " +} +------------------------------------------------------------- +http://localhost:8080/address/list +{ + "data": [ + { + "addressId": 1, + "addressCountry": "india", + "addressCity": "bangalore", + "employee": { + "employeeId": 1, + "employeeName": "adarsh kumar", + "address": null + } + }, + { + "addressId": 2, + "addressCountry": "india", + "addressCity": "hyderabad", + "employee": { + "employeeId": 2, + "employeeName": "radha singh", + "address": null + } + } + ], + "message": "AddressBean Found " +} +------------------------------------------------------------- +http://localhost:8080/address/get/1 +{ + "data": { + "addressId": 1, + "addressCountry": "india", + "addressCity": "bangalore", + "employee": { + "employeeId": 1, + "employeeName": "adarsh kumar", + "address": null + } + }, + "message": "AddressBean Found " +} +------------------------------------------------------------- +http://localhost:8080/address/save + Content-Type :application/json + Accept :application/json + { + "addressId": 3, + "addressCountry": "india", + "addressCity": "hyderabad" + } +------------------------------------------------------------- +http://localhost:8080/address/delete/3 + +{ + "data": { + "addressId": 3, + "addressCountry": "india", + "addressCity": "hyderabad", + "employee": null + }, + "message": "AddressBean Deleted " +} +------------------------------------------------------------- diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/pom.xml b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/pom.xml new file mode 100644 index 00000000..37aad020 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/pom.xml @@ -0,0 +1,143 @@ + + + 4.0.0 + + SpringBootJpaOneToOneMappingExample + SpringBootJpaOneToOneMappingExample + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.3.1.RELEASE + + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + SpringBootJpaOneToOneMappingExample + UTF-8 + 1.7 + 4.13.1 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-starter-test + test + + + + junit + junit + ${junit.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/sql/script.sql b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/sql/script.sql new file mode 100644 index 00000000..aa5c06bb --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/sql/script.sql @@ -0,0 +1,25 @@ +DROP TABLE IF EXISTS `espark`.`address`; +CREATE TABLE `espark`.`address` ( + `address_id` int(11) NOT NULL, + `address_city` varchar(255) DEFAULT NULL, + `address_country` varchar(255) DEFAULT NULL, + PRIMARY KEY (`address_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO ADDRESS(address_id, address_city,address_country ) +VALUES (1,'BANGALORE','INDIA') +,(2,'HYDERABAD','INDIA'); + +DROP TABLE IF EXISTS `espark`.`employee`; +CREATE TABLE `espark`.`employee` ( + `employee_id` int(11) NOT NULL, + `employee_name` varchar(255) NOT NULL, + `address_id` int(11) DEFAULT NULL, + PRIMARY KEY (`employee_id`), + KEY `FK_qrbsk9ljmhfje93me0n7xwdxq` (`address_id`), + CONSTRAINT `FK_qrbsk9ljmhfje93me0n7xwdxq` FOREIGN KEY (`address_id`) REFERENCES `address` (`address_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO EMPLOYEE(employee_id,employee_name,address_id) +VALUES(1,'ADARSH KUMAR',1) + ,(2,'RADHA SINGH',2); diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..25bbbcfa --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/AddressBean.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/AddressBean.java new file mode 100644 index 00000000..f65c9816 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/AddressBean.java @@ -0,0 +1,45 @@ +package com.espark.adarsh.bean; + + +import java.io.Serializable; + +public class AddressBean implements Serializable { + + private int addressId; + private String addressCountry; + private String addressCity; + + private EmployeeBean employee; + + public EmployeeBean getEmployee() { + return employee; + } + + public void setEmployee(EmployeeBean employee) { + this.employee = employee; + } + + public int getAddressId() { + return addressId; + } + + public void setAddressId(int addressId) { + this.addressId = addressId; + } + + public String getAddressCountry() { + return addressCountry; + } + + public void setAddressCountry(String addressCountry) { + this.addressCountry = addressCountry; + } + + public String getAddressCity() { + return addressCity; + } + + public void setAddressCity(String addressCity) { + this.addressCity = addressCity; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..ef6ab015 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public class EmployeeBean implements Serializable { + + private Integer employeeId; + + private String employeeName; + + private AddressBean address; + + public AddressBean getAddress() { + return address; + } + + public void setAddress(AddressBean address) { + this.address = address; + } + + public Integer getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Integer employeeId) { + this.employeeId = employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java new file mode 100644 index 00000000..d0e12d2d --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +/** + * Created by Adarsh on 1/29/16. + */ +public class ResponseBean implements Serializable { + + private T data; + private String message; + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/AddressController.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/AddressController.java new file mode 100644 index 00000000..2db35a58 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/AddressController.java @@ -0,0 +1,97 @@ +package com.espark.adarsh.controllers; + +import com.espark.adarsh.bean.ResponseBean; +import com.espark.adarsh.persistence.entities.Address; +import com.espark.adarsh.persistence.entities.Employee; +import com.espark.adarsh.persistence.repository.AddressRepository; +import com.espark.adarsh.persistence.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@Controller +@RequestMapping(value = "/address") +public class AddressController { + + @Autowired + private AddressRepository addressRepository; + + @RequestMapping(value = "/save" + , method = RequestMethod.POST + , produces = {"application/json", "application/xml"} + , consumes = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean
createAddress(@RequestBody Address address) { + final ResponseBean
addressResponseBean = new ResponseBean
(); + try { + addressResponseBean.setData(this.addressRepository.save(address)); + addressResponseBean.setMessage("AddressBean Saved"); + } catch (Exception e) { + addressResponseBean.setMessage("AddressBean Not Saved " + e.getMessage()); + } + return addressResponseBean; + } + + + @RequestMapping(value = "/list" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean> getAllAddress() { + final ResponseBean> addressResponseBean = new ResponseBean>(); + try { + final List
addressList = (List
) this.addressRepository.findAll(); + for (Address address : addressList) { + address.getEmployee().setAddress(null); + } + addressResponseBean.setData(addressList); + addressResponseBean.setMessage("AddressBean Found "); + } catch (Exception e) { + addressResponseBean.setMessage("AddressBean Not Found " + e.getMessage()); + } + return addressResponseBean; + } + + @RequestMapping(value = "/delete/{addressId}" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean
deleteAddress(@PathVariable("addressId") String addressId) { + final ResponseBean
addressResponseBean = new ResponseBean
(); + try { + final Address address = this.addressRepository.findByAddressId(Integer.parseInt(addressId)); + address.getEmployee().setAddress(null); + addressResponseBean.setData(address); + this.addressRepository.delete(address); + addressResponseBean.setMessage("AddressBean Deleted "); + } catch (Exception e) { + addressResponseBean.setMessage("AddressBean Not Deleted " + e.getMessage()); + } + return addressResponseBean; + } + + + @RequestMapping(value = "/get/{addressId}" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean
getAddress(@PathVariable("addressId") String addressId) { + final ResponseBean
addressResponseBean = new ResponseBean
(); + try { + final Address address = this.addressRepository.findByAddressId(Integer.parseInt(addressId)); + address.getEmployee().setAddress(null); + addressResponseBean.setData(address); + addressResponseBean.setMessage("AddressBean Found "); + } catch (Exception e) { + addressResponseBean.setMessage("AddressBean Not Found " + e.getMessage()); + } + return addressResponseBean; + } +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/EmployeeController.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/EmployeeController.java new file mode 100644 index 00000000..d620cd69 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/controllers/EmployeeController.java @@ -0,0 +1,99 @@ +package com.espark.adarsh.controllers; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.bean.ResponseBean; +import com.espark.adarsh.persistence.entities.Employee; +import com.espark.adarsh.persistence.repository.AddressRepository; +import com.espark.adarsh.persistence.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@Controller +@RequestMapping(value = "/employee") +public class EmployeeController { + + @Autowired + private EmployeeRepository employeeRepository; + + @Autowired + private AddressRepository addressRepository; + + @RequestMapping(value = "/save" + , method = RequestMethod.POST + , produces = {"application/json", "application/xml"} + , consumes = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean createEmployee(@RequestBody Employee employee) { + final ResponseBean employeeResponseBean = new ResponseBean(); + try { + employeeResponseBean.setData(this.employeeRepository.save(employee)); + employeeResponseBean.setMessage("EmployeeBean Saved"); + } catch (Exception e) { + employeeResponseBean.setMessage("EmployeeBean Not Saved " + e.getMessage()); + } + return employeeResponseBean; + } + + @RequestMapping(value = "/list" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean> getAllEmployee() { + final ResponseBean> employeeResponseBean = new ResponseBean>(); + try { + final List employeeList=(List)this.employeeRepository.findAll(); + for(Employee e: employeeList){ + e.getAddress().setEmployee(null); + } + employeeResponseBean.setData(employeeList); + employeeResponseBean.setMessage("Employees Found "); + } catch (Exception e) { + employeeResponseBean.setMessage("Employees Not Found " + e.getMessage()); + } + return employeeResponseBean; + } + + @RequestMapping(value = "/delete/{employeeId}" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean deleteEmployee(@PathVariable("employeeId") String employeeId) { + final ResponseBean employeeResponseBean = new ResponseBean(); + try { + final Employee employee = this.employeeRepository.findByEmployeeId(Integer.parseInt(employeeId)); + employee.getAddress().setEmployee(null); + employeeResponseBean.setData(employee); + this.employeeRepository.delete(employee); + employeeResponseBean.setMessage("Employees Deleted "); + } catch (Exception e) { + employeeResponseBean.setMessage("Employees Not Deleted " + e.getMessage()); + } + return employeeResponseBean; + } + + + @RequestMapping(value = "/get/{employeeId}" + , method = RequestMethod.GET + , produces = {"application/json", "application/xml"}) + public + @ResponseBody + ResponseBean getEmployee(@PathVariable("employeeId") String employeeId) { + final ResponseBean employeeResponseBean = new ResponseBean(); + try { + final Employee employee = this.employeeRepository.findByEmployeeId(Integer.parseInt(employeeId)); + employee.getAddress().setEmployee(null); + employeeResponseBean.setData(employee); + employeeResponseBean.setMessage("Employees Found "); + } catch (Exception e) { + employeeResponseBean.setMessage("Employees Not Found " + e.getMessage()); + } + return employeeResponseBean; + } +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Address.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Address.java new file mode 100644 index 00000000..0312564e --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Address.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.persistence.entities; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Table(name = "address") +public class Address implements Serializable { + @Id + private int addressId; + private String addressCountry; + private String addressCity; + + @OneToOne(cascade = CascadeType.ALL, mappedBy = "address") + private Employee employee; + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public int getAddressId() { + return addressId; + } + + public void setAddressId(int addressId) { + this.addressId = addressId; + } + + public String getAddressCountry() { + return addressCountry; + } + + public void setAddressCountry(String addressCountry) { + this.addressCountry = addressCountry; + } + + public String getAddressCity() { + return addressCity; + } + + public void setAddressCity(String addressCity) { + this.addressCity = addressCity; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Employee.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Employee.java new file mode 100644 index 00000000..22f94c45 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/entities/Employee.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.persistence.entities; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Table(name = "employee") +public class Employee implements Serializable{ + + @Id + private Integer employeeId; + + @Basic(optional = false) + private String employeeName; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "AddressId") + private Address address; + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Integer getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Integer employeeId) { + this.employeeId = employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/AddressRepository.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/AddressRepository.java new file mode 100644 index 00000000..5875329d --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/AddressRepository.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.persistence.repository; + + + +import com.espark.adarsh.persistence.entities.Address; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AddressRepository extends CrudRepository { + + public Address findByAddressId(Integer id); +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/EmployeeRepository.java b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/EmployeeRepository.java new file mode 100644 index 00000000..d5c4cc26 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/java/com/espark/adarsh/persistence/repository/EmployeeRepository.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.persistence.repository; + + + +import com.espark.adarsh.persistence.entities.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { + + public Employee findByEmployeeId(Integer id); +} diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/application.properties new file mode 100644 index 00000000..96a82394 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/application.properties @@ -0,0 +1,11 @@ +# DataSource settings: set here configurations for the database connection +spring.datasource.url = jdbc:mysql://localhost:3306/espark +spring.datasource.username = adarsh +spring.datasource.password = adarsh + +# Show or not log for each sql query +spring.jpa.show-sql = true + +# Hibernate settings +spring.jpa.hibernate.ddl-auto = validate +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect diff --git a/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/log4j.xml new file mode 100644 index 00000000..defb8601 --- /dev/null +++ b/APPLICATIONS/SpringBootJpaOneToOneMappingExample/src/main/resources/log4j.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootJsonXmlRequestResponseExample/doc/get Request Json.png b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/get Request Json.png similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/doc/get Request Json.png rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/get Request Json.png diff --git a/SpringBootJsonXmlRequestResponseExample/doc/get Request Xml .png b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/get Request Xml .png similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/doc/get Request Xml .png rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/get Request Xml .png diff --git a/SpringBootJsonXmlRequestResponseExample/doc/help.txt b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/help.txt similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/doc/help.txt rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/help.txt diff --git a/SpringBootJsonXmlRequestResponseExample/doc/post request.png b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/post request.png similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/doc/post request.png rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/doc/post request.png diff --git a/SpringBootJsonXmlRequestResponseExample/pom.xml b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/pom.xml similarity index 98% rename from SpringBootJsonXmlRequestResponseExample/pom.xml rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/pom.xml index 280af16d..cd3994c1 100644 --- a/SpringBootJsonXmlRequestResponseExample/pom.xml +++ b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/pom.xml @@ -63,7 +63,7 @@ SpringBootJsonXmlRequestResponseExample UTF-8 1.7 - 4.11 + 4.13.1 1.6.1 1.2.17 @@ -85,7 +85,7 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - 2.7.0 + 2.7.8 diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/controller/ApplicationControllerImpl.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/entity/User.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/entity/User.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/entity/User.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/entity/User.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseService.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseService.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseService.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseService.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/java/com/espark/adarsh/service/DataBaseServiceImpl.java diff --git a/SpringBootJsonXmlRequestResponseExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/resources/application.properties similarity index 100% rename from SpringBootJsonXmlRequestResponseExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/resources/application.properties diff --git a/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/resources/log4j.xml new file mode 100644 index 00000000..defb8601 --- /dev/null +++ b/APPLICATIONS/SpringBootJsonXmlRequestResponseExample/src/main/resources/log4j.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspJettyExample/pom.xml b/APPLICATIONS/SpringBootJspJettyExample/pom.xml new file mode 100644 index 00000000..c21b4216 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/pom.xml @@ -0,0 +1,136 @@ + + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.2.8.RELEASE + + + SpringBootJspJettyExample + SpringBootJspJettyExample + 1.0-SNAPSHOT + + SpringBootJspJettyExample + https://github.com/adarshkumarsingh83 + war + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + repo.spring.io.milestone + Spring Maven Milestone Repository + https://repo.spring.io/libs-milestone + + + JBoss + https://repository.jboss.org/nexus/content/repositories/releases/ + + + + + SpringBootJspJettyExample + UTF-8 + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.apache.tomcat.embed + tomcat-embed-el + + + + + + + + + org.springframework.boot + spring-boot-starter-jetty + + + + javax.servlet + jstl + + + + org.eclipse.jetty + apache-jsp + 9.4.0.M0 + + + + org.springframework.boot + spring-boot-starter-test + + + + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..0f714979 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,23 @@ + + +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; + + +@SpringBootApplication +public class ApplicationMain extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(ApplicationMain.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/bean/ApplicationResponseBean.java b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/bean/ApplicationResponseBean.java new file mode 100644 index 00000000..7cc6e9c3 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/bean/ApplicationResponseBean.java @@ -0,0 +1,17 @@ + + +package com.espark.adarsh.bean; + +public class ApplicationResponseBean { + + private String message; + + public ApplicationResponseBean(String message) { + this.message = message; + } + + public String getMessage() { + return this.message; + } + +} diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/controller/MyException.java b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/controller/MyException.java new file mode 100644 index 00000000..3e390bc9 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/controller/MyException.java @@ -0,0 +1,11 @@ + + +package com.espark.adarsh.controller; + +public class MyException extends RuntimeException { + + public MyException(String message) { + super(message); + } + +} diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/exceptions/ApplicationsController.java b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/exceptions/ApplicationsController.java new file mode 100644 index 00000000..2b6626fb --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/java/com/espark/adarsh/exceptions/ApplicationsController.java @@ -0,0 +1,47 @@ + +package com.espark.adarsh.exceptions; + +import com.espark.adarsh.bean.ApplicationResponseBean; +import com.espark.adarsh.controller.MyException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import java.util.Date; +import java.util.Map; + +@Controller +public class ApplicationsController { + + @Value("${application.message:Hello World}") + private String message = "Hello World"; + + @RequestMapping("/") + public String welcome(Map model) { + model.put("time", new Date()); + model.put("message", this.message); + return "welcome"; + } + + @RequestMapping("/fail") + public String fail() { + throw new MyException("Oh dear!"); + } + + @RequestMapping("/fail2") + public String fail2() { + throw new IllegalStateException(); + } + + @ExceptionHandler(MyException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public @ResponseBody + ApplicationResponseBean handleMyRuntimeException(MyException exception) { + return new ApplicationResponseBean("Some data I want to send back to the client."); + } + +} diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJspJettyExample/src/main/resources/application.properties new file mode 100644 index 00000000..f18efd16 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp +application.message: Hello Spring Boot diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/main/webapp/WEB-INF/jsp/welcome.jsp b/APPLICATIONS/SpringBootJspJettyExample/src/main/webapp/WEB-INF/jsp/welcome.jsp new file mode 100644 index 00000000..3196dac6 --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/main/webapp/WEB-INF/jsp/welcome.jsp @@ -0,0 +1,18 @@ + + +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + + + + + Spring URL: ${springUrl} at ${time} +
+ JSTL URL: ${url} +
+ Message: ${message} + + + diff --git a/APPLICATIONS/SpringBootJspJettyExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java b/APPLICATIONS/SpringBootJspJettyExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java new file mode 100644 index 00000000..67956bbb --- /dev/null +++ b/APPLICATIONS/SpringBootJspJettyExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java @@ -0,0 +1,34 @@ + + +package com.espark.adarsh.test; + +import org.junit.Test; +import org.junit.runner.RunWith; +/*import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)*/ +import org.springframework.test.annotation.DirtiesContext; +@DirtiesContext +public class ApplicationTests { + + /*@LocalServerPort + private int port; + + @Test + public void testJspWithEl() throws Exception { + ResponseEntity entity = new TestRestTemplate() + .getForEntity("http://localhost:" + this.port, String.class); + *//*assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("/resources/text.txt");*//* + }*/ + +} diff --git a/APPLICATIONS/SpringBootJspTomcatExample/pom.xml b/APPLICATIONS/SpringBootJspTomcatExample/pom.xml new file mode 100644 index 00000000..b198e473 --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + SpringBootJspTomcatExample + SpringBootJspTomcatExample + 1.0-SNAPSHOT + + SpringBootJspTomcatExample + https://github.com/adarshkumarsingh83 + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + repo.spring.io.milestone + Spring Maven Milestone Repository + https://repo.spring.io/libs-milestone + + + JBoss + https://repository.jboss.org/nexus/content/repositories/releases/ + + + + + SpringBootJspTomcatExample + UTF-8 + 1.8 + 4.11 + 1.6.1 + 1.2.17 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + javax.servlet + jstl + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/main/doc/help.txt b/APPLICATIONS/SpringBootJspTomcatExample/src/main/doc/help.txt new file mode 100644 index 00000000..26ea4b87 --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/main/doc/help.txt @@ -0,0 +1,11 @@ +to compile and buld +/> mvn clean package + +to execute from jar file +/>java -jar target/SpringBootJspTomcatExample-1.0-SNAPSHOT.jar + +to execute +/> mvn spring-boot:run + + +http://localhost:8080 \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..95e60c3e --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,14 @@ + +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + //http://localhost:8080 + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..b9880363 --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class ApplicationController { + + @RequestMapping("/") + public String helloWorld(Model model) { + model.addAttribute("messages", "Welcome to the Espark "+System.getProperty("user.name")); + return "esparkHome"; + } + +} diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/META-INF/resources/WEB-INF/jsp/esparkHome.jsp b/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/META-INF/resources/WEB-INF/jsp/esparkHome.jsp new file mode 100644 index 00000000..b5f54095 --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/META-INF/resources/WEB-INF/jsp/esparkHome.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><% +response.setHeader("Cache-Control","no-cache"); +response.setHeader("Pragma","no-cache"); +response.setHeader("Expires","0"); + +%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> + +<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + +

Hello World - ${messages}

+ + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/application.properties new file mode 100644 index 00000000..3bf1cbfe --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.mvc.view.prefix=/WEB-INF/jsp/ +spring.mvc.view.suffix=.jsp \ No newline at end of file diff --git a/APPLICATIONS/SpringBootJspTomcatExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java b/APPLICATIONS/SpringBootJspTomcatExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java new file mode 100644 index 00000000..5d89e28f --- /dev/null +++ b/APPLICATIONS/SpringBootJspTomcatExample/src/test/java/com/espark/adarsh/test/ApplicationTests.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.test; + +import com.espark.adarsh.ApplicationMain; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = ApplicationMain.class) +@WebAppConfiguration +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/pom.xml b/APPLICATIONS/SpringBootMockitoExmaple/pom.xml new file mode 100644 index 00000000..62e93d17 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + SpringBootMockitoExmaple + SpringBootMockitoExmaple + 1.0-SNAPSHOT + + 1.7 + + + + + + org.springframework.boot + spring-boot-starter + 1.3.1.RELEASE + + + org.springframework.boot + spring-boot-starter-test + 1.3.1.RELEASE + test + + + org.mockito + mockito-core + 1.10.19 + + + + log4j + log4j + 1.2.17 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..0055475c --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/Permission.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/Permission.java new file mode 100644 index 00000000..babbc683 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/Permission.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.entities; + +/** + * Created by akumar6 on 8/2/16. + */ +public class Permission { + + private Integer permissionId; + private String permissionName; + + public Permission() { + } + + public Permission(Integer permissionId, String permissionName) { + this.permissionId = permissionId; + this.permissionName = permissionName; + } + + public Integer getPermissionId() { + return permissionId; + } + + public void setPermissionId(Integer permissionId) { + this.permissionId = permissionId; + } + + public String getPermissionName() { + return permissionName; + } + + public void setPermissionName(String permissionName) { + this.permissionName = permissionName; + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/User.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/User.java new file mode 100644 index 00000000..88a0da61 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/entities/User.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.entities; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +public class User { + + private Integer userId; + private String userName; + private List permissionList=new ArrayList(); + + public User() { + } + + public User(Integer userId, String userName, List permissionList) { + this.userId = userId; + this.userName = userName; + this.permissionList = permissionList; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public List getPermissionList() { + return permissionList; + } + + public void setPermission(Permission permission) { + this.permissionList.add(permission); + } + public void setPermissionList(List permissionList) { + this.permissionList = permissionList; + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepository.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepository.java new file mode 100644 index 00000000..187222f6 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepository.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entities.Permission; + +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +public interface PermissionRepository { + + public boolean savePermission(Permission permission); + + public boolean updatePermission(Permission permission); + + public boolean deletePermission(Integer permissionId); + + public Permission getPermission(Integer permissionId); + + public List getAllPermission(); +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepositoryImpl.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepositoryImpl.java new file mode 100644 index 00000000..ebd266a3 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/PermissionRepositoryImpl.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entities.Permission; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +@Repository("permissionRepository") +public class PermissionRepositoryImpl implements PermissionRepository { + + @Override + public boolean savePermission(Permission permission) { + return false; + } + + @Override + public boolean updatePermission(Permission permission) { + return false; + } + + @Override + public boolean deletePermission(Integer permissionId) { + return false; + } + + @Override + public Permission getPermission(Integer permissionId) { + return null; + } + + @Override + public List getAllPermission() { + return null; + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepository.java new file mode 100644 index 00000000..cf542528 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepository.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entities.User; + +import java.util.List; + +/** + * Created by akumar6 on 8/2/16.er + */ +public interface UserRepository { + + public boolean saveUser(User user); + + public boolean updateUser(User user); + + public boolean deleteUser(Integer userId); + + public User getUser(Integer userId); + + public List getAllUser(); + +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java new file mode 100644 index 00000000..fda7447d --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java @@ -0,0 +1,76 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entities.Permission; +import com.espark.adarsh.entities.User; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +@Repository("userRepository") +public class UserRepositoryImpl implements UserRepository { + + @Override + public boolean saveUser(User user) { + if (user != null) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @Override + public boolean updateUser(User user) { + if (user != null) { + return true; + } + return false; + } + + @Override + public boolean deleteUser(Integer userId) { + if (userId != null) { + return true; + } + return false; + } + + @Override + public User getUser(Integer userId) { + if (userId != null) { + return new User(){ + { + setUserId(100); + setUserName("Adarsh"); + setPermission(new Permission(100,"admin")); + } + }; + } + return null; + } + + @Override + public List getAllUser() { + return new ArrayList(){ + { + add( new User(){ + { + setUserId(100); + setUserName("Adarsh"); + setPermission(new Permission(100,"admin")); + } + }); + + add( new User(){ + { + setUserId(101); + setUserName("amit"); + setPermission(new Permission(101,"user")); + } + }); + } + }; + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserService.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserService.java new file mode 100644 index 00000000..656e7044 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserService.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entities.User; + +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +public interface UserService { + + public boolean saveUser(User user); + + public boolean updateUser(User user); + + public boolean deleteUser(Integer userId); + + public User getUser(Integer userId); + + public List getAllUser(); +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserServiceImpl.java b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserServiceImpl.java new file mode 100644 index 00000000..d1636683 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/java/com/espark/adarsh/service/UserServiceImpl.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entities.Permission; +import com.espark.adarsh.entities.User; +import com.espark.adarsh.repository.PermissionRepository; +import com.espark.adarsh.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created by akumar6 on 8/2/16. + */ +@Service("userService") +public class UserServiceImpl implements UserService { + + @Autowired + private UserRepository userRepository; + + @Autowired + private PermissionRepository permissionRepository; + + + @Override + public boolean saveUser(User user) { + final List permissionList=this.permissionRepository.getAllPermission(); + user.setPermissionList(permissionList); + return this.userRepository.saveUser(user); + } + + @Override + public boolean updateUser(User user) { + final List permissionList=this.permissionRepository.getAllPermission(); + user.setPermissionList(permissionList); + return this.userRepository.updateUser(user); + } + + @Override + public boolean deleteUser(Integer userId) { + return this.userRepository.deleteUser(userId); + } + + @Override + public User getUser(Integer userId) { + return this.userRepository.getUser(userId); + } + + @Override + public List getAllUser() { + return this.userRepository.getAllUser(); + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootMockitoExmaple/src/main/resources/log4j.xml new file mode 100644 index 00000000..d1abcec0 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/main/resources/log4j.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/TestConfiguration.java b/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/TestConfiguration.java new file mode 100644 index 00000000..aceb53f2 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/TestConfiguration.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.test; + +import com.espark.adarsh.repository.PermissionRepository; +import com.espark.adarsh.repository.PermissionRepositoryImpl; +import com.espark.adarsh.repository.UserRepository; +import com.espark.adarsh.repository.UserRepositoryImpl; +import com.espark.adarsh.service.UserService; +import com.espark.adarsh.service.UserServiceImpl; +import org.mockito.Mockito; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; + +@Profile("test") +@Configuration +public class TestConfiguration { + + @Bean + @Primary + public UserRepository getUserRepository() { + return Mockito.mock(UserRepositoryImpl.class); + } + + @Bean + @Primary + public PermissionRepository getPermissionRepository() { + return Mockito.mock(PermissionRepositoryImpl.class); + } + + @Bean + @Primary + public UserService getUserService() { + return Mockito.mock(UserServiceImpl.class); + } +} diff --git a/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/UserServiceTest.java b/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/UserServiceTest.java new file mode 100644 index 00000000..8f80d544 --- /dev/null +++ b/APPLICATIONS/SpringBootMockitoExmaple/src/test/java/com/espark/adarsh/test/UserServiceTest.java @@ -0,0 +1,60 @@ +package com.espark.adarsh.test; + +import com.espark.adarsh.ApplicationMain; +import com.espark.adarsh.entities.Permission; +import com.espark.adarsh.entities.User; +import com.espark.adarsh.service.UserService; +import junit.framework.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@ActiveProfiles("test") +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = ApplicationMain.class) +public class UserServiceTest { + + @Autowired + private UserService userService; + + + @Test + public void testSaveUser() { + final Permission permission = new Permission() { + { + setPermissionId(100); + setPermissionName("ADMIN"); + } + }; + final User user = new User() { + { + setUserId(100); + setUserName("adarsh"); + setPermission(permission); + } + }; + Mockito.when(userService.saveUser(user)).thenReturn(Boolean.TRUE); + boolean value=this.userService.saveUser(user); + Assert.assertEquals(value,true); + } + + @Test + public void testGetUser() { + final User user= new User(){ + { + setUserId(100); + setUserName("Adarsh"); + setPermission(new Permission(100,"admin")); + } + }; + Mockito.when(userService.getUser(100)).thenReturn(user); + final User user1=this.userService.getUser(100); + Assert.assertEquals(user1.getUserId(),user.getUserId()); + } + + +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/document/help.txt b/APPLICATIONS/SpringBootMultiContextExample/document/help.txt new file mode 100644 index 00000000..519261c9 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/document/help.txt @@ -0,0 +1,10 @@ +http://localhost:8080/emp/fetch/100 + +http://localhost:8080/api1-dev/emp/fetch/100 +http://localhost:8080/api2-dev/emp/fetch/100 +http://localhost:8080/api3-dev/emp/fetch/100 + + +http://localhost:8080/api1-prod/emp/fetch/100 +http://localhost:8080/api2-prod/emp/fetch/100 +http://localhost:8080/api3-prod/emp/fetch/100 \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMultiContextExample/pom.xml b/APPLICATIONS/SpringBootMultiContextExample/pom.xml new file mode 100644 index 00000000..1235eff3 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + spring-boot-multi-context + spring-boot-multi-context + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.7.RELEASE + + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..2f175913 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..0c88432a --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entity.EmployeeEntity; + +public class EmployeeBean { + + private String empId; + private String empName; + + + public EmployeeBean() { + } + + public EmployeeBean(String empId, String empName) { + this.empId = empId; + this.empName = empName; + } + + public EmployeeBean(EmployeeEntity employeeEntity) { + this.empId = employeeEntity.getEmpId(); + this.empName = employeeEntity.getEmpName(); + } + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/configuration/WebContextConfiguration.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/configuration/WebContextConfiguration.java new file mode 100644 index 00000000..92a9bd7a --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/configuration/WebContextConfiguration.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +@Configuration +public class WebContextConfiguration { + + + @Value("${environments.${spring.profiles.active}.url1}") + String apiUrl1; + + @Value("${environments.${spring.profiles.active}.url2}") + String apiUrl2; + + @Value("${environments.${spring.profiles.active}.url3}") + String apiUrl3; + + @Bean + public ServletRegistrationBean apiV() { + DispatcherServlet dispatcherServlet = new DispatcherServlet(); + + AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); + applicationContext.register(DispatcherServlet.class); + dispatcherServlet.setApplicationContext(applicationContext); + + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/"); + servletRegistrationBean.setName("api-v0"); + return servletRegistrationBean; + } + + @Bean + public ServletRegistrationBean apiV1() { + DispatcherServlet dispatcherServlet = new DispatcherServlet(); + + AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); + applicationContext.register(DispatcherServlet.class); + dispatcherServlet.setApplicationContext(applicationContext); + + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, apiUrl1); + servletRegistrationBean.setName("api-v1"); + return servletRegistrationBean; + } + + @Bean + public ServletRegistrationBean apiV2() { + DispatcherServlet dispatcherServlet = new DispatcherServlet(); + + AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); + applicationContext.register(DispatcherServlet.class); + dispatcherServlet.setApplicationContext(applicationContext); + + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, apiUrl2); + servletRegistrationBean.setName("api-v2"); + return servletRegistrationBean; + } + + @Bean + public ServletRegistrationBean apiV3() { + DispatcherServlet dispatcherServlet = new DispatcherServlet(); + + AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); + applicationContext.register(DispatcherServlet.class); + dispatcherServlet.setApplicationContext(applicationContext); + + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, apiUrl3); + servletRegistrationBean.setName("api-v3"); + return servletRegistrationBean; + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/entity/EmployeeEntity.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/entity/EmployeeEntity.java new file mode 100644 index 00000000..270204a8 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/entity/EmployeeEntity.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.entity; + +import com.espark.adarsh.bean.EmployeeBean; + +public class EmployeeEntity { + + private String empId; + private String empName; + + + public EmployeeEntity() { + } + + public EmployeeEntity(String empId, String empName) { + this.empId = empId; + this.empName = empName; + } + + public EmployeeEntity(EmployeeBean employee) { + this.empId = employee.getEmpId(); + this.empName = employee.getEmpName(); + } + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..d1f2b7f6 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.EmployeeEntity; + +public interface EmployeeRepository { + + public EmployeeEntity saveEmployee(EmployeeEntity employee); + + public EmployeeEntity getEmployee(String empId); +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepositoryImpl.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepositoryImpl.java new file mode 100644 index 00000000..c023f34a --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/repository/EmployeeRepositoryImpl.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.EmployeeEntity; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.Map; + +@Repository(value = "employeeRepository") +public class EmployeeRepositoryImpl implements EmployeeRepository { + + Map employeeStore=new HashMap(){ + { + put("100",new EmployeeEntity("100","test")); + } + }; + + @Override + public EmployeeEntity saveEmployee(EmployeeEntity employee) { + employeeStore.put(employee.getEmpId(),employee); + return employee; + } + + @Override + public EmployeeEntity getEmployee(String empId) { + return employeeStore.get(empId); + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..62017519 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.EmployeeBean; + +public interface EmployeeService { + + public EmployeeBean saveEmployee(EmployeeBean employee); + + public EmployeeBean getEmployee(String empId); + + +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java new file mode 100644 index 00000000..9591c0f3 --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.entity.EmployeeEntity; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service(value = "employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + private EmployeeRepository employeeRepository; + + @Override + public EmployeeBean saveEmployee(EmployeeBean employee) { + EmployeeEntity employeeEntity= this.employeeRepository.saveEmployee(new EmployeeEntity(employee)); + return new EmployeeBean(employeeEntity); + } + + @Override + public EmployeeBean getEmployee(String empId) { + EmployeeEntity employeeEntity= this.employeeRepository.getEmployee(empId); + return new EmployeeBean(employeeEntity); + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..06c19e7d --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.web; + + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/app") +public class ApplicationController { + + @Value("${environments.${spring.profiles.active}.name}") + private String profileName; + + @RequestMapping(value = "/profile",method = RequestMethod.GET) + public @ResponseBody + Map getApplicationProfile(){ + return new HashMap(){ + { + put("profile",profileName); + put("msg","welcome to the application"); + } + }; + } +} diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..3286678d --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/emp") +public class EmployeeController { + + @Autowired + private EmployeeService employeeService; + + @RequestMapping(value = "/save",method = RequestMethod.POST) + public @ResponseBody + EmployeeBean saveEmployee(@RequestBody EmployeeBean employee){ + return this.employeeService.saveEmployee(employee); + } + + @RequestMapping(value = "/fetch/{id}",method = RequestMethod.GET) + public @ResponseBody + EmployeeBean getEmployee(@PathVariable("id")String employeeId){ + return this.employeeService.getEmployee(employeeId); + } +} + + diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootMultiContextExample/src/main/resources/application.properties new file mode 100644 index 00000000..d173885d --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/main/resources/application.properties @@ -0,0 +1,12 @@ +#spring.profiles.active=dev +spring.profiles.active=prod + +environments.dev.name=Developer-Env +environments.dev.url1=/api1-dev/* +environments.dev.url2=/api2-dev/* +environments.dev.url3=/api3-dev/* + +environments.prod.name=Prod-Env +environments.prod.url1=/api1-prod/* +environments.prod.url2=/api2-prod/* +environments.prod.url3=/api3-prod/* diff --git a/APPLICATIONS/SpringBootMultiContextExample/src/test/java/com/espark/adarsh/test/EmployeeBeanTest.java b/APPLICATIONS/SpringBootMultiContextExample/src/test/java/com/espark/adarsh/test/EmployeeBeanTest.java new file mode 100644 index 00000000..e4dc90de --- /dev/null +++ b/APPLICATIONS/SpringBootMultiContextExample/src/test/java/com/espark/adarsh/test/EmployeeBeanTest.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.test; + + +import com.espark.adarsh.bean.EmployeeBean; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import java.net.URL; +import org.junit.Before; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.web.client.TestRestTemplate; +; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class EmployeeBeanTest { + + @LocalServerPort + private int port; + + private URL base; + + @Autowired + private TestRestTemplate template; + + @Before + public void setUp() throws Exception { + this.base = new URL("http://localhost:" + port + "/"); + } + + + @Test + public void saveEmployee() throws Exception { + ResponseEntity response = template.postForEntity(base.toString()+"/emp/save", + new EmployeeBean("200","radha singh"),EmployeeBean.class); + EmployeeBean employee = response.getBody(); + assertThat(employee.getEmpId(), equalTo("200")); + } + + @Test + public void getEmployee() throws Exception { + ResponseEntity response = template.getForEntity(base.toString()+"/emp/fetch/100", + EmployeeBean.class); + EmployeeBean employee = response.getBody(); + assertThat(employee.getEmpId(), equalTo("100")); + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/pom.xml b/APPLICATIONS/SpringBootMvcAndRestExample/pom.xml new file mode 100644 index 00000000..2112c851 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/pom.xml @@ -0,0 +1,182 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.3.RELEASE + + + SpringBootMvcAndRestExample + SpringBootMvcAndRestExample + 1.0-SNAPSHOT + + SpringBootMvcAndRestExample + https://github.com/adarshkumarsingh83 + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + repo.spring.io.milestone + Spring Maven Milestone Repository + https://repo.spring.io/libs-milestone + + + JBoss + https://repository.jboss.org/nexus/content/repositories/releases/ + + + + + SpringBootMvcAndRestExample + UTF-8 + 1.8 + 0.6.0 + 4.11 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.security + spring-security-config + + + + org.springframework.security + spring-security-taglibs + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + mysql + mysql-connector-java + 5.1.31 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + javax.servlet + jstl + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + io.jsonwebtoken + jjwt + ${jwt.version} + + + + joda-time + joda-time + 2.7 + + + + commons-lang + commons-lang + 2.6 + + + + commons-codec + commons-codec + 1.10 + + + + com.google.code.gson + gson + 2.6.2 + + + + net.sf.ehcache + ehcache-core + 2.6.9 + + + commons-logging + commons-logging + + + + + + + + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/doc/help.txt b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/doc/help.txt new file mode 100644 index 00000000..f82d9467 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/doc/help.txt @@ -0,0 +1,28 @@ +to compile and buld +/> mvn clean package + +to execute from jar file +/>java -jar target/SpringBootJspTomcatExample-1.0-SNAPSHOT.jar + +to execute +/> mvn spring-boot:run + +jsp page url +http://localhost:8080 + +rest end point url +http://localhost:8080/welcome + + +url=> http://localhost:8080/rest/authenticate/login + +Content-Type:application/json +{"username":"adarsh", "password":"adarsh"} + +------------------------------------------------------------------------------------ +url=> http://localhost:8080/rest/users +Accept:application/json +Authentication-token : YWRhcnNoISEhMTQ1ODgwNTQyODUxNyEhIUYEkvI7jEpLVfViLgOoX6s= +------------------------------------------------------------------------------------ +http://localhost:8080/rest/logout +Authentication-token : YWRhcnNoISEhMTQ1ODgwNTQyODUxNyEhIUYEkvI7jEpLVfViLgOoX6s= diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..cf5af0d0 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@SpringBootApplication +public class ApplicationMain { + + //http://localhost:8080 + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/persistance/PersistenceConfiguration.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/persistance/PersistenceConfiguration.java new file mode 100644 index 00000000..a47011ba --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/persistance/PersistenceConfiguration.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration.persistance; + +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@Configuration +@EnableTransactionManagement +@ComponentScan({"com.espark.adarsh.persistence.entities.*", "com.espark.adarsh.persistence.repositories.*"}) +@PropertySource({"classpath:properties/dataSource.properties","classpath:properties/hibernate.properties"}) +public class PersistenceConfiguration { + + @Value("${dataSource.driverClass}") + private String driverClassName; + @Value("${dataSource.url}") + private String url; + @Value("${dataSource.hostname}") + private String hostName; + @Value("${dataSource.portNumber}") + private String portNumber; + @Value("${dataSource.database}") + private String databaseName; + @Value("${dataSource.extraParam}") + private String extraPram; + @Value("${dataSource.username}") + private String userName; + @Value("${dataSource.password}") + private String userPwd; + + /*Hibenate properties */ + @Value("${hibernate.dialect}") + private String hibernateDialect; + @Value("${hibernate.hbm2ddl.auto}") + private String hibernateHbmDdlAuto; + @Value("${hibernate.max_fetch_depth}") + private String hibernateMaxFetchDepth; + @Value("${hibernate.batch_size}") + private String hibernateBatchSize; + @Value("${hibernate.jdbc.use_scrollable_resultset}") + private String hibernateScrollableResultSet; + @Value("${hibernate.generate_statistics}") + private String hibernateGenerateStatistics; + @Value("${hibernate.format_sql}") + private String hibernateFormatSql; + @Value("${hibernate.show_sql}") + private String hibernateShowSql; + + + @Bean(name = "sessionFactory") + public LocalSessionFactoryBean sessionFactory() { + LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(getDataSource()); + sessionFactory.setPackagesToScan(new String[]{"com.espark.adarsh.persistence.entities.*"}); + sessionFactory.setHibernateProperties(hibernateProperties()); + return sessionFactory; + } + + @Bean + public DataSource getDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(driverClassName); + dataSource.setUrl(url + hostName + portNumber + databaseName + extraPram); + dataSource.setUsername(userName); + dataSource.setPassword(userPwd); + DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource); + return dataSource; + } + + + private DatabasePopulator createDatabasePopulator() { + ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); + databasePopulator.setContinueOnError(true); + databasePopulator.addScript(new ClassPathResource("database/database.sql")); + return databasePopulator; + } + + + private Properties hibernateProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", hibernateDialect); + properties.put("hibernate.hbm2ddl.auto", hibernateHbmDdlAuto); + properties.put("hibernate.show_sql", hibernateShowSql); + properties.put("hibernate.format_sql", hibernateFormatSql); + return properties; + } + + + @Bean + @Autowired + public HibernateTransactionManager transactionManager(SessionFactory s) { + HibernateTransactionManager txManager = new HibernateTransactionManager(); + txManager.setSessionFactory(s); + return txManager; + } + + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/RestWebSecurityConfiguration.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/RestWebSecurityConfiguration.java new file mode 100644 index 00000000..b4acfd0a --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/RestWebSecurityConfiguration.java @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.configuration.security; + + +import com.espark.adarsh.security.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.encoding.Md5PasswordEncoder; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +@ComponentScan({"com.espark.adarsh.security.*"}) +public class RestWebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter { + + private static final String baseResource = "/static/**"; + private static final String cssHome = "*.css"; + private static final String jsHome = "*.js"; + private static final String imageHome = "*.ico"; + + @EnableGlobalMethodSecurity(prePostEnabled = true) + @Configuration + @Order(1) + public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { + + @Override + public void configure(WebSecurity webSecurity) throws Exception { + webSecurity.ignoring() + .antMatchers(baseResource) + .antMatchers(jsHome) + .antMatchers(cssHome) + .antMatchers(imageHome) + .antMatchers("/rest/authenticate/login"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/rest/*") + .csrf().disable() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers(baseResource).access("permitAll") + .antMatchers("/css/**").access("permitAll") + .antMatchers("/js/**").access("permitAll") + .antMatchers("/rest/authenticate/login").permitAll() + .antMatchers("/rest/welcome").hasAnyAuthority(new String[]{"ROLE_SUPERADMIN", "ROLE_ADMIN", "ROLE_USER"}) + .antMatchers("/rest/**").authenticated() + .anyRequest().authenticated() + .and() + .httpBasic().disable() + .formLogin().disable() + .rememberMe().disable() + .requestCache().disable() + .x509().disable() + .logout() + .logoutUrl("/rest/logout") + .logoutSuccessHandler(this.getRestLogoutSuccessHandler()) + .and() + //.anonymous().disable() + // add custom authentication filter + .addFilterBefore(this.getAuthenticationTokenProcessingFilter(), BasicAuthenticationFilter.class) + // register custom authentication exception handler + .exceptionHandling().authenticationEntryPoint(this.getEntryPointBean()) + .accessDeniedHandler(this.getAccessDeniedHandler()); + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(getRestApiAuthProvider()); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean(name = "authenticationProvider") + public AuthenticationProvider getRestApiAuthProvider() { + return new RestApiAuthProvider(); + } + + @Bean + public AuthenticationTokenProcessingFilter getAuthenticationTokenProcessingFilter() throws Exception { + return new AuthenticationTokenProcessingFilter(this.authenticationManager(), this.tokenService()); + } + + @Bean(name = "entryPoint") + public ApiServerAuthenticationEntryPoint getEntryPointBean() { + return new ApiServerAuthenticationEntryPoint(); + } + + @Bean(name = "accessDeniedHandler") + public RestAccessDeniedHandler getAccessDeniedHandler() { + return new RestAccessDeniedHandler(); + } + + @Bean(name = "restLogoutSuccessHandler") + public RestLogoutSuccessHandler getRestLogoutSuccessHandler() { + return new RestLogoutSuccessHandler(); + } + + @Bean(name = "md5PasswordEncoder") + public Md5PasswordEncoder getEncoder() { + return new Md5PasswordEncoder(); + } + + @Bean + public TokenService tokenService() { + return new TokenService(); + } + + } + + @EnableGlobalMethodSecurity(prePostEnabled = true) + @Configuration + @Order(2) + public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Autowired(required = true) + @Qualifier(value = "userDetailsService") + private UserDetailsService userDetailsService; + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring() + .antMatchers(baseResource) + .antMatchers(jsHome) + .antMatchers(cssHome) + .antMatchers(imageHome); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers(baseResource).access("permitAll") + .antMatchers("/css/**").access("permitAll") + .antMatchers("/js/**").access("permitAll") + .antMatchers("/login**").access("permitAll") + .antMatchers("/logout**").access("permitAll") + .antMatchers("/user/**").access("hasRole('ROLE_USER')or hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPERADMIN')") + .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPERADMIN')") + .antMatchers("/sadmin/**").access("hasRole('ROLE_SUPERADMIN')") + .anyRequest().authenticated() + .and() + .formLogin().loginPage("/login") + .defaultSuccessUrl("/welcome") + .failureUrl("/login?error") + .usernameParameter("username").passwordParameter("password") + .and() + .logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout").invalidateHttpSession(true) + .clearAuthentication(true) + .and() + .exceptionHandling().accessDeniedPage("/accessDenied"); + + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + // with encryption + //auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); + // without encryption + auth.userDetailsService(userDetailsService); + } + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/SpringSecurityInitializer.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/SpringSecurityInitializer.java new file mode 100644 index 00000000..1c766d4d --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/security/SpringSecurityInitializer.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration.security; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/SpringMvcInitializer.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/SpringMvcInitializer.java new file mode 100644 index 00000000..66897771 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/SpringMvcInitializer.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration.web; + +import com.espark.adarsh.configuration.persistance.PersistenceConfiguration; +import com.espark.adarsh.configuration.security.RestWebSecurityConfiguration; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] {PersistenceConfiguration.class,WebMvcConfiguration.class, RestWebSecurityConfiguration.class}; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java new file mode 100644 index 00000000..a7dd516a --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration.web; + +import com.espark.adarsh.configuration.persistance.PersistenceConfiguration; +import com.espark.adarsh.configuration.security.RestWebSecurityConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@EnableWebMvc +@Configuration +@ComponentScan({"com.espark.adarsh"}) +@Import({RestWebSecurityConfiguration.class, PersistenceConfiguration.class}) +public class WebMvcConfiguration extends WebMvcConfigurerAdapter { + + private static final String[] RESOURCE_LOCATIONS = { + "classpath:/static/"}; + + @Bean + public InternalResourceViewResolver viewResolver() { + InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); + viewResolver.setViewClass(JstlView.class); + viewResolver.setPrefix("/WEB-INF/jsp/"); + viewResolver.setSuffix(".jsp"); + return viewResolver; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**/js/**","/**/css/**").addResourceLocations(RESOURCE_LOCATIONS); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/AbstractEntity.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/AbstractEntity.java new file mode 100644 index 00000000..1c1d2200 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/AbstractEntity.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.persistence.entities.construct; + +import javax.persistence.*; +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@MappedSuperclass +public abstract class AbstractEntity + implements com.espark.adarsh.persistence.entities.construct.Entity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(insertable = true, nullable = false, unique = true, updatable = true) + private E id; + + protected AbstractEntity(Class entity) { + final Class entityObject = entity; + System.out.println(entity.getCanonicalName()); + } + + @Override + public E getId() { + return id; + } + + public void setId(E id) { + this.id = id; + } + + @PrePersist + protected void prePersist() { + } + + @PreUpdate + protected void preUpdate() { + } + + @PreRemove + protected void preRemove() { + } + + @Override + public int compareTo(Object o) { + + if (o instanceof com.espark.adarsh.persistence.entities.construct.Entity) { + com.espark.adarsh.persistence.entities.construct.Entity entity = (com.espark.adarsh.persistence.entities.construct.Entity) o; + return 0; + } + return 1; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/Entity.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/Entity.java new file mode 100644 index 00000000..2bb60f09 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/construct/Entity.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.persistence.entities.construct; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface Entity extends Serializable,Cloneable,Comparable{ + + public E getId(); + + public void setId(E id); + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/User.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/User.java new file mode 100644 index 00000000..3a06b57a --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/User.java @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.entities.impl; + + +import com.espark.adarsh.persistence.entities.construct.AbstractEntity; +import org.springframework.util.DigestUtils; + +import javax.persistence.*; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Entity +@Table(name = "User") +public final class User extends AbstractEntity { + + @Column(unique = true, length = 24, nullable = false) + private String userName; + + @Column(length = 100, nullable = false) + private String userEmail; + + + @Column(length = 100, nullable = false) + private String userPwd; + + @Column(length = 10, nullable = true) + private String userPhone; + + @Column(nullable = false) + private Boolean enabled; + + + @Column(length = 24, nullable = false) + private String firstName; + + @Column(length = 24, nullable = true) + private String lastName; + + + @Column + @Temporal(value = TemporalType.TIMESTAMP) + private Date createdDate; + + @Column + @Temporal(value = TemporalType.TIMESTAMP) + private Date modifiedDate; + + + @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @JoinTable(name = "user_role_mapping") + private Set userRoles; + + + + public User() { + super(User.class); + } + + public User(Long id) { + super(User.class); + super.setId(id); + this.setUserName(""); + } + + + public User(String userName) { + this(); + this.userName = userName; + } + + public User(User user) { + super(User.class); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.userEmail = user.getUserEmail(); + this.enabled = user.getEnabled(); + this.userName = user.getUserName(); + this.setUserPwd(user.getUserPwd()); + this.userPhone = user.getUserPhone(); + this.setUserRoles(user.getUserRoles()); + this.setModifiedDate(new Date()); + this.setCreatedDate(new Date()); + } + + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + public String getUserPwd() { + return userPwd; + } + + public void setUserPwd(String userPwd) { + this.userPwd = DigestUtils.md5DigestAsHex(userPwd.getBytes()); + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Set getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set userRoles) { + this.userRoles = userRoles; + } + + public void setRole(UserRole roles) { + if (userRoles == null) { + userRoles = new HashSet(); + } + this.userRoles.add(roles); + } + + + + @Override + public String toString() { + return "User{" + + "userName='" + userName + '\'' + + ", userEmail='" + userEmail + '\'' + + ", userPwd='" + userPwd + '\'' + + ", enabled=" + enabled + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", createdDate=" + createdDate + + ", modifiedDate=" + modifiedDate + + ", userRoles=" + userRoles.iterator().next().getName() + + '}'; + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/UserRole.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/UserRole.java new file mode 100644 index 00000000..469caf56 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/entities/impl/UserRole.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.entities.impl; + + +import com.espark.adarsh.persistence.entities.construct.AbstractEntity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Entity +@Table(name = "UserRole") +public final class UserRole extends AbstractEntity { + + @Column(nullable = false, length = 100) + private String name; + + public UserRole() { + super(UserRole.class); + } + + public UserRole(String name) { + super(UserRole.class); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "UserRole{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java new file mode 100644 index 00000000..ccd706a2 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories; + + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; + +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface RoleRepository { + + public Long size(); + public void refreshUser(UserRole userRole); + public UserRole getRoleByName(String roleName); + public Boolean saveUserRole(UserRole userRole); + public Boolean updateUserRole(UserRole userRole); + public Boolean dropUserRole(UserRole userRole); + public UserRole getUserRole(User user); + public List getAllUserRole(User user); +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java new file mode 100644 index 00000000..46d9e826 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories; + + +import com.espark.adarsh.persistence.entities.impl.User; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface UserRepository { + + + public Long size(); + + public void refreshUser(User user); + + public Boolean saveUser(User user); + + public User getUser(User user); + + public User getUserById(User user); + + public User getUserByName(User user); + + public Boolean deleteUser(User user); + + public User updateUser(User user); + + public Collection getAllUser(); + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java new file mode 100644 index 00000000..b7928a9f --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + + +import com.espark.adarsh.persistence.entities.construct.Entity; +import org.hibernate.*; +import org.hibernate.criterion.Example; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Assert; + +import javax.persistence.Table; +import java.util.Collection; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public abstract class AbstractRepository + implements EntityRepository { + + protected final Class entityClass; + protected final String entityClassName; + protected final String entityTableName; + + + public AbstractRepository(final Class entityClass) { + this.entityClass = entityClass; + this.entityClassName = this.entityClass.getSimpleName(); + this.entityTableName = this.entityClass.getAnnotation(Table.class).name(); + } + + @Override + public Entity getEntity(Entity entity) { + return (Entity) getSession().load(entityClass, entity.getId()); + } + + @Override + public Entity getEntityByName(Entity entity) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq("userName", entity)); + return (Entity) criteria.uniqueResult(); + } + + @Override + public Entity getEntityById(Entity entity) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq("id", entity.getId())); + return (Entity) criteria.uniqueResult(); + } + + @Override + public List getAll() { + return getSession().createCriteria(entityClass).list(); + } + + + public List getAll(int limit) { + return getSession().createCriteria(entityClass).list().subList(0, limit); + } + + @Override + public List getAll(final Integer firstResult, final Integer maxResults) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.setFirstResult(firstResult); + criteria.setMaxResults(maxResults); + final List list = criteria.list(); + return list; + } + + @Override + public Long size() { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.setProjection(Projections.rowCount()).uniqueResult(); + return (Long) criteria.uniqueResult(); + } + + @Override + public void remove(final R entity) { + try { + getSession().delete(entity); + } catch (final Exception e) { + System.out.println("Unable to delete entity : " + this.entityClassName + ", :" + entity + e.getMessage()); + } + } + + + @Override + public Entity getByColumnName(String columnName, Object columnValue) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq(columnName, columnValue)); + return (Entity) criteria.uniqueResult(); + } + + @Override + public Collection getByEntities(String columnName, Object columnValue) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq(columnName, columnValue)); + return (List) criteria.list(); + } + + @Override + public void clear() { + getSession().createQuery("DELETE FROM " + entityClassName).executeUpdate(); + } + + @Override + public void refresh(R entity) { + getSession().refresh(entity); + } + + + @Override + public List getByExample(final R example) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Example.create(example)); + final List list = criteria.list(); + return list; + } + + @Override + public R getUniqueByExample(final R example) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Example.create(example)); + R result = (R) criteria.uniqueResult(); + return result; + } + + + @Override + public void insert(R record) { + getSession().save(record); + } + + @Override + public void insertAll(final Collection items) { + for (final R record : items) { + getSession().save(record); + } + } + + @Override + public void put(final R record) { + getSession().saveOrUpdate(record); + } + + @Override + public void put(final Collection records) { + Session session = getSession(); + for (R record : records) { + session.saveOrUpdate(record); + } + } + + @Override + public void update(final R record) throws HibernateException { + getSession().update(record); + } + + @Override + public void updateAll(final Collection items) { + for (final R record : items) { + getSession().update(record); + } + } + + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByNamedQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return findByNamedQuery(queryOrQueryName, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByNamedQuery(final String queryOrQueryName, final int firstResult, final int maxResults, final Object... parameters) + throws IllegalArgumentException { + return executeQuery(queryOrQueryName, true, false, false, firstResult, maxResults, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return findByQuery(queryOrQueryName, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByQuery(final String queryOrQueryName, final int firstResult, final int maxResults, final Object... parameters) throws IllegalArgumentException { + return executeQuery(queryOrQueryName, false, false, false, firstResult, maxResults, parameters); + } + + /** + * @param query the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final Integer executeQuery(final String query, final Object... parameters) throws IllegalArgumentException { + return executeQuery(query, false, false, true, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final Integer executeNamedQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return executeQuery(queryOrQueryName, true, false, true, 0, 0, parameters); + } + + /** + * Master execute query method. this does not support named parameter queries at this movement. + * + * @param result type of the query we are expecting. + * @param queryOrQueryName the HQL query, or the named query ID. + * @param namedQuery true if its a named query. + * @param singleResult true if we are expecting a single result. + * @param isExecuteUpdate true if we are executing a update statement. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final REZ_TYPE executeQuery(final String queryOrQueryName, final boolean namedQuery, final boolean singleResult, final boolean isExecuteUpdate, + final int firstResult, final int maxResults, final Object... parameters) throws IllegalArgumentException { + + Assert.hasLength(queryOrQueryName, "Query for executing cannot be null"); + Assert.isTrue(firstResult > -1, "First result cannot be less than zero"); + + try { + Session session = getSession(); + Object result = null; + + Query query; + if (namedQuery) { + query = session.getNamedQuery(queryOrQueryName); + } else { + query = session.createQuery(queryOrQueryName); + } + if (parameters != null) { + for (int i = 0; i < parameters.length; i++) { + query.setParameter(i, parameters[i]); + } + } + if (firstResult >= 0) { + query.setFirstResult(firstResult); + } + if (maxResults >= 0) { + query.setMaxResults(maxResults); + } + if (singleResult) { + result = query.uniqueResult(); + } else if (!isExecuteUpdate) { + result = query.list(); + } else { + result = new Integer(query.executeUpdate()); + } + if (result != null && !isExecuteUpdate) { + if (singleResult) { + onFindForObject((R) result); + } else { + onFindForList((List) result); + } + } + return (REZ_TYPE) result; + } catch (final Exception e) { + System.out.println("Unable to execute query :" + queryOrQueryName + ", namedQuery:" + namedQuery + ", singleResult" + singleResult + ", firstResult" + firstResult + + ", maxResults" + maxResults + ",parameters" + parameters + " " + e); + } + return null; + } + + + protected R onFindForObject(final R record) { + return record; + // can be overridden. + } + + + protected List onFindForList(final List records) { + for (final R record : records) { + onFindForObject(record); + } + // can be overridden. + return records; + } + + + protected final Class getEntityClass() { + return entityClass; + } + + /** + * @return the entityClassName + */ + protected final String getEntityClassName() { + return entityClassName; + } + + /** + * @return the entityTableName + */ + protected final String getEntityTableName() { + return entityTableName; + } + + protected SessionFactory sessionFactory; + + @Autowired + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + protected Session getSession() { + return sessionFactory.getCurrentSession(); + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java new file mode 100644 index 00000000..6168ee63 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + + +import com.espark.adarsh.persistence.entities.construct.Entity; +import org.springframework.dao.DuplicateKeyException; + +import java.util.Collection; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@org.springframework.stereotype.Repository +public interface EntityRepository { + + /* public R get(R entity);*/ + + public List getAll(); + + public List getAll(int limit); + + public List getAll(Integer firstResult, Integer maxResults); + + public List getByExample(final R example); + + public R getUniqueByExample(final R example); + + public void put(final R record) throws DuplicateKeyException; + + public void put(final Collection records); + + public Entity getEntity(Entity entity); + + public Entity getEntityById(Entity entity); + + public Entity getEntityByName(Entity entity); + + public void insert(final R record); + + public void insertAll(final Collection items); + + public void update(final R record); + + public void updateAll(final Collection items); + + public void remove(final R entity); + + public Entity getByColumnName(String columnName, Object columnValue); + + public Collection getByEntities(String columnName, Object columnValue); + + public void clear(); + + public void refresh(final R entity); + + public Long size(); +} diff --git a/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java rename to APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java new file mode 100644 index 00000000..e6b26216 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.impl; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; +import com.espark.adarsh.persistence.repositories.RoleRepository; +import com.espark.adarsh.persistence.repositories.construct.AbstractRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Repository +public class RoleRepositoryImpl extends AbstractRepository + implements RoleRepository { + + public RoleRepositoryImpl() { + super(UserRole.class); + } + + @Override + @Transactional + public Long size() { + return super.size(); + } + + @Override + public void refreshUser(UserRole userRole) { + super.refresh(userRole); + } + + @Override + @Transactional + public Boolean saveUserRole(UserRole userRole) { + super.put(userRole); + return null; + } + + @Override + @Transactional + public UserRole getRoleByName(String roleName) { + UserRole userRole=new UserRole(); + userRole.setName(roleName); + return (UserRole) super.getUniqueByExample(userRole); + } + + @Override + @Transactional + public Boolean updateUserRole(UserRole userRole) { + super.update(userRole); + return null; + } + + @Override + @Transactional + public Boolean dropUserRole(UserRole userRole) { + super.remove(userRole); + return null; + } + + @Override + @Transactional + public UserRole getUserRole(User user) { + UserRole UserUserRole = new UserRole(); + UserUserRole.setId(1L); + UserUserRole.setName("User"); + return null; + } + + @Override + public List getAllUserRole(User user) { + return super.getAll(); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java new file mode 100644 index 00000000..4f827e05 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.impl; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.repositories.UserRepository; +import com.espark.adarsh.persistence.repositories.construct.AbstractRepository; +import org.hibernate.Criteria; +import org.hibernate.criterion.Restrictions; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Repository +public class UserRepositoryImpl extends AbstractRepository + implements UserRepository { + + public UserRepositoryImpl() { + super(User.class); + } + + @Override + @Transactional + public Boolean saveUser(User user) { + super.put(user); + return null; + } + + @Override + @Transactional + public User getUser(User user) { + return getUniqueByExample(user); + } + + @Override + @Transactional + public User getUserById(User user) { + return (User) super.getEntityById(user); + } + + @Override + @Transactional + public User getUserByName(User user) { + return (User) super.getByColumnName("userName",user.getUserName()); + } + + @Override + @Transactional + public Boolean deleteUser(User user) { + super.remove(user); + return null; + } + + @Override + @Transactional + public User updateUser(User user) { + super.update(user); + return null; + } + + + @Override + @Transactional + public Collection getAllUser() { + return getAll(); + } + + + @Transactional + public User getFacebookUser(String facebookUserEmailId){ + Criteria criteria=getSession().createCriteria(User.class); + criteria.add(Restrictions.eq("userEmail", facebookUserEmailId)) ; + Object object=criteria.uniqueResult(); + if(object!=null){ + return (User)object; + } + return (User)object; + } + + @Override + @Transactional + public Long size() { + return super.size(); + } + + @Override + public void refreshUser(User user) { + super.refresh(user); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/ApiServerAuthenticationEntryPoint.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/ApiServerAuthenticationEntryPoint.java new file mode 100644 index 00000000..9e5a7b15 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/ApiServerAuthenticationEntryPoint.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * @see org.springframework.security.core.AuthenticationException + * @see org.springframework.security.web.AuthenticationEntryPoint + * + * This class provide a entry point for the all the incomming request to the api server + * other then which is configured for not to intercept from spring security + */ +public class ApiServerAuthenticationEntryPoint implements AuthenticationEntryPoint { + + private static Logger LOG = LoggerFactory.getLogger(ApiServerAuthenticationEntryPoint.class); + private static final String MESSAGE="MESSAGE"; + private static final String NOT_AUTHENTICATED_ACCESS_DENIED ="NOT-AUTHENTICATED-ACCESS-DENIED"; + + /** + * {@inheritDoc} + */ + @Override + public void commence(HttpServletRequest httpServletRequest + , HttpServletResponse httpServletResponse, AuthenticationException authException) + throws IOException, ServletException { + LOG.debug("Entering into Security Area "+ httpServletRequest.getRequestURI()+" "+ httpServletRequest.getQueryString()+" "+ httpServletRequest.getRequestURL()); + httpServletResponse.addHeader(MESSAGE, NOT_AUTHENTICATED_ACCESS_DENIED); + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/AuthenticationTokenProcessingFilter.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/AuthenticationTokenProcessingFilter.java new file mode 100644 index 00000000..16e4bf78 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/AuthenticationTokenProcessingFilter.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + + +import com.espark.adarsh.persistence.entities.impl.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.web.filter.GenericFilterBean; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class AuthenticationTokenProcessingFilter extends GenericFilterBean { + + private static Logger LOG = LoggerFactory.getLogger(AuthenticationTokenProcessingFilter.class); + + @Autowired(required = true) + private TokenProvider tokenProvider; + + private TokenService tokenService; + + @Autowired(required = true) + private AuthenticationManager authenticationManager; + + private SecurityContextProvider securityContextProvider = new SecurityContextProvider(); + + private WebAuthenticationDetailsSource webAuthenticationDetailsSource = new WebAuthenticationDetailsSource(); + + public AuthenticationTokenProcessingFilter(AuthenticationManager authenticationManager, final TokenService tokenService) { + this.authenticationManager = authenticationManager; + this.tokenService = tokenService; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + LOG.debug("Checking headers and parameters for authentication token..."); + + String token = null; + + final HttpServletRequest httpServletRequest = this.asHttpServletRequest(request); + if (httpServletRequest.getHeader("Authentication-token") != null) { + token = httpServletRequest.getHeader("Authentication-token"); + LOG.debug("Found token '" + token + "' in request headers"); + } + + if (token != null && tokenProvider.isTokenValid(token)) { + if (this.tokenService.contains(token)) { + final SecurityContext securityContext = this.securityContextProvider.getSecurityContext(); + securityContext.setAuthentication(this.tokenService.retrieve(token)); + } else { + final User user = tokenProvider.getUserFromToken(token); + LOG.debug("Inside-AuthenticationTokenProcessingFilter.java"); + this.authenticateUser(httpServletRequest, user, token); + } + } + chain.doFilter(request, response); + // SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false); + } + + private HttpServletRequest asHttpServletRequest(ServletRequest servletRequest) { + return (HttpServletRequest) servletRequest; + } + + private HttpServletResponse asHttpServletResponse(ServletResponse servletResponse) { + return (HttpServletResponse) servletResponse; + } + + private void authenticateUser(HttpServletRequest request, User user, String token) { + final UsernamePasswordAuthenticationToken passwordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getUserPwd()); + passwordAuthenticationToken.setDetails(this.webAuthenticationDetailsSource.buildDetails(request)); + final SecurityContext securityContext = this.securityContextProvider.getSecurityContext(); + final Authentication authentication = this.authenticationManager.authenticate(passwordAuthenticationToken); + securityContext.setAuthentication(authentication); + this.tokenService.store(token, authentication); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/JwtTokenProvider.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/JwtTokenProvider.java new file mode 100644 index 00000000..619824ee --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/JwtTokenProvider.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.security; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.SignatureException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Component +public class JwtTokenProvider { + + private final String key; + + @Autowired + public JwtTokenProvider(@Value("${token-secret-key}") String key) { + this.key = key; + } + + public String getTokenFromValue(Map vals) { + return Jwts.builder().setSubject("sso").setClaims(vals).signWith(SignatureAlgorithm.HS512, key).compact(); + } + + public Map getTokenValue(String data) { + if (null == data) { + return null; + } + try { + final Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(data).getBody(); + final Map params = new HashMap(); + for (Entry entry : claims.entrySet()) { + params.put(entry.getKey(), entry.getValue()); + } + return params; + } catch (SignatureException e) { + return null; + } + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAccessDeniedHandler.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAccessDeniedHandler.java new file mode 100644 index 00000000..7574b41e --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAccessDeniedHandler.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.access.AccessDeniedException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * @see org.springframework.security.access.AccessDeniedException + * @see org.springframework.security.web.access.AccessDeniedHandler + * + * This class provide the implementation for Access Denied Handler handle() + * is the callback method which will executed when any protected resource is + * access without sufficent privillage. + */ +public class RestAccessDeniedHandler implements + org.springframework.security.web.access.AccessDeniedHandler { + + private static final Logger LOG = LoggerFactory.getLogger(RestAccessDeniedHandler.class); + private static final String MESSAGE="ACCESS-DENIED-LACK-OF-PERMISSIONS"; + + /** + * {@inheritDoc} + */ + @Override + public void handle(HttpServletRequest request + , HttpServletResponse response, AccessDeniedException accessDeniedException) + throws IOException, ServletException { + LOG.error("RestAccessDeniedHandler ", accessDeniedException); + response.addHeader("MESSAGE", MESSAGE); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "ACCESS-DENIED"); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestApiAuthProvider.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestApiAuthProvider.java new file mode 100644 index 00000000..9ad48d88 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestApiAuthProvider.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.security; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class RestApiAuthProvider implements AuthenticationProvider { + + private static final Logger LOG = LoggerFactory.getLogger(RestApiAuthProvider.class); + + @Qualifier("userManager") + @Autowired(required = true) + private UserManager userManager; + + + @Override + @Transactional(readOnly = true) + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + LOG.debug("RestApiAuthProvider retrieveUser() "); + final String username=authentication.getName(); + final String userPassword=authentication.getCredentials().toString(); + try { + User bean = new User(username); + bean = userManager.getUser(bean); + if(bean != null){ + if(!bean.getUserPwd().equals(userPassword)){ + throw new BadCredentialsException("Invalid Credentials"); + } + } + Collection authorities = new ArrayList(bean.getUserRoles().size()); + for (UserRole role : bean.getUserRoles()) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + } + return new UsernamePasswordAuthenticationToken(username, userPassword, + authorities); + + } catch (Exception e) { + LOG.error("Unable to find record with username:=" + username, e); + } + return null; + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAuthenticationFailureHandler.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAuthenticationFailureHandler.java new file mode 100644 index 00000000..2e390e11 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestAuthenticationFailureHandler.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * + * @see org.springframework.security.core.AuthenticationException + * @see org.springframework.security.web.authentication.AuthenticationFailureHandler + * + * This component provide the functionality for handling the authentication failure event. + * onAuthenticationFailure() is the callback method executed by framework whent authentication + * failure event is triggered. + */ +public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler { + + private static final Logger LOG = LoggerFactory.getLogger(RestAuthenticationFailureHandler.class); + private static final String MESSAGE="AUTHENTICATION-NOT-SUCCESS"; + /** + * {@inheritDoc} + */ + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest + , HttpServletResponse httpServletResponse, AuthenticationException authException) + throws IOException, ServletException { + LOG.error("On Authentication Failure Exception Occur",authException); + httpServletResponse.addHeader("MESSAGE",MESSAGE); + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Bad credentials"); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestLogoutSuccessHandler.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestLogoutSuccessHandler.java new file mode 100644 index 00000000..a0835b42 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/RestLogoutSuccessHandler.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.security; + + +import com.google.gson.Gson; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class RestLogoutSuccessHandler implements LogoutSuccessHandler { + + @Override + public void onLogoutSuccess(HttpServletRequest request + , HttpServletResponse response, Authentication authentication) + throws IOException, ServletException { + response.addHeader("MESSAGE", "LOGOUT-SUCCESS"); + response.setStatus(HttpServletResponse.SC_OK); + final Map apiServer = new HashMap(); + apiServer.put("MESSAGE", "LOGOUT-SUCCESS"); + apiServer.put("HttpStatus", "" + HttpServletResponse.SC_OK); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.getWriter().write(new Gson().toJson(apiServer)); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/SecurityContextProvider.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/SecurityContextProvider.java new file mode 100644 index 00000000..8352fc1d --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/SecurityContextProvider.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + + +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * + * @see org.springframework.security.core.context.SecurityContext; + * @see org.springframework.security.core.context.SecurityContextHolder; + * + * This component provide the functionality for getting the spring security context + * + */ +public class SecurityContextProvider { + + /** + * getSecurityContext() provide the functionality of + * retrieving the current spring security instance. + * @return the current instance of the SecurityContext + */ + public SecurityContext getSecurityContext() { + return SecurityContextHolder.getContext(); + } + + /** + * getUserDetails() provide the UserDetails instance. + * @return + */ + public String getUserDetails(){ + return this.getSecurityContext().getAuthentication().getPrincipal().toString(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenProvider.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenProvider.java new file mode 100644 index 00000000..0ca2abeb --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenProvider.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.web.manager.UserManager; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Component +public class TokenProvider { + + @Qualifier(value = "userManager") + @Autowired(required = true) + private UserManager userManager; + + @Value("${token-secret-key}") + private String secretKey; + + + private MessageDigest md5er; + + + static String FENCE_POST = "!!!"; + private static final String NEWLINE = "\r\n"; + + + public TokenProvider() { + try { + md5er = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Cannot find MD5 algorithm",e); + } + } + + public String getToken(User user) { + return getToken(user, DateTime.now().plusDays(1).getMillis()); + } + + public String getToken(User user, long expirationDateInMillis) { + + StringBuilder tokenBuilder = new StringBuilder(); + + byte[] token = tokenBuilder + .append(user.getUserName()) + .append(FENCE_POST) + .append(expirationDateInMillis) + .append(FENCE_POST) + .append(new String(buildTokenKey(expirationDateInMillis, user))) + .toString().getBytes(); + + // the below function returns a string ending in "\r\n", which tends to cause problems...remove it + return Base64.encodeBase64String(token).replace(NEWLINE, ""); + } + + public boolean isTokenValid(String encodedToken) { + String[] components = decodeAndDissectToken(encodedToken); + + if (components == null || components.length != 3) { + return false; + } + String externalUser = components[0]; + Long externalDate = Long.parseLong(components[1]); + String externalKey = components[2]; + User user = userManager.getUserByName(new User(externalUser)); + String expectedKey = new String(buildTokenKey(externalDate, user)); + byte[] expectedKeyBytes = expectedKey.getBytes(); + byte[] externalKeyBytes = externalKey.getBytes(); + if (!MessageDigest.isEqual(expectedKeyBytes, externalKeyBytes)) { + return false; + } + + if (new DateTime(externalDate).isBeforeNow()) { + return false; + } + + return true; + } + + private byte[] buildTokenKey(long expirationDateInMillis, User user) { + Assert.notNull(secretKey, "Secret Key must not be null!"); + StringBuilder keyBuilder = new StringBuilder(); + String key = keyBuilder + .append(user.getUserName()) + .append(FENCE_POST) + .append(user.getUserPwd()) + .append(FENCE_POST) + .append(expirationDateInMillis) + .append(FENCE_POST) + .append(secretKey).toString(); + + byte[] keyBytes = key.getBytes(); + return md5er.digest(keyBytes); + } + + public User getUserFromToken(String token) { + if (!isTokenValid(token)) { return null; } + String[] components = decodeAndDissectToken(token); + if (components == null || components.length != 3) { return null; } + String username = components[0]; + return userManager.getUserByName(new User(username)); + } + + private String[] decodeAndDissectToken(String encodedToken) { + if(StringUtils.isBlank(encodedToken) || !Base64.isArrayByteBase64(encodedToken.getBytes())) { + return null; + } + // Apache Commons Base64 tools expect Base64 strings to end in "\r\n", add if necessary + if(!encodedToken.endsWith(NEWLINE)) { encodedToken = encodedToken + NEWLINE; } + String token = new String(Base64.decodeBase64(encodedToken)); + if(!token.contains(FENCE_POST) || token.split(FENCE_POST).length != 3) { + return null; + } + return token.split(FENCE_POST); + } + + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + public MessageDigest getMd5er() { + return md5er; + } + + public void setMd5er(MessageDigest md5er) { + this.md5er = md5er; + } + + +} + diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenService.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenService.java new file mode 100644 index 00000000..7393b111 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/TokenService.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.security.core.Authentication; + +import java.util.UUID; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class TokenService { + + private static final Logger logger = LoggerFactory.getLogger(TokenService.class); + private static final Cache restApiAuthTokenCache = CacheManager.getInstance().getCache("restApiAuthTokenCache"); + public static final int HALF_AN_HOUR_IN_MILLISECONDS = 30 * 60 * 1000; + + @Scheduled(fixedRate = HALF_AN_HOUR_IN_MILLISECONDS) + public void evictExpiredTokens() { + logger.info("Evicting expired tokens"); + restApiAuthTokenCache.evictExpiredElements(); + } + + public String generateNewToken() { + return UUID.randomUUID().toString(); + } + + public void store(String token, Authentication authentication) { + restApiAuthTokenCache.put(new Element(token, authentication)); + } + + public boolean contains(String token) { + return restApiAuthTokenCache.get(token) != null; + } + + public Authentication retrieve(String token) { + return (Authentication) restApiAuthTokenCache.get(token).getObjectValue(); + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsImpl.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsImpl.java new file mode 100644 index 00000000..faf63f82 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.security; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class UserDetailsImpl extends User implements UserDetails { + + public UserDetailsImpl(String username, String password, Collection authorities) { + super(username, password, authorities); + } + + public UserDetailsImpl(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) { + super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); + } + + private com.espark.adarsh.persistence.entities.impl.User user; + + + public com.espark.adarsh.persistence.entities.impl.User getUser() { + return user; + } + + public void setUser(com.espark.adarsh.persistence.entities.impl.User user) { + this.user = user; + } + + @Override + public String toString() { + return "UserDetailsImpl{" + + "user=" + user + + '}'; + } +} + diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsServiceImpl.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsServiceImpl.java new file mode 100644 index 00000000..602c35b4 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/security/UserDetailsServiceImpl.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.security; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; +import com.espark.adarsh.web.manager.UserManager; +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Component("userDetailsService") +public class UserDetailsServiceImpl implements UserDetailsService { + + private static final Logger logger = Logger.getLogger(UserDetailsServiceImpl.class); + + @Autowired(required = true) + private UserManager userManager; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { + logger.debug("UserDetailsServiceImpl loadUserByUsername() "); + try { + User bean = new User(username); + bean = this.userManager.getUser(bean); + final Collection authorities = new ArrayList(bean.getUserRoles().size()); + for (UserRole role : bean.getUserRoles()) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + } + final UserDetailsImpl details = new UserDetailsImpl(bean.getUserName(), bean.getUserPwd(), bean.getEnabled(), + true, true, true, authorities); + details.setUser(bean); + return details; + } catch (Exception e) { + logger.error("Unable to find record with username:=" + username, e); + } + return null; + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ApiServerViewBean.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ApiServerViewBean.java new file mode 100644 index 00000000..61ce15c4 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ApiServerViewBean.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.bean; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@JsonPropertyOrder({"userName", "userPassword","token","message","httpStatus"}) +public class ApiServerViewBean implements Serializable { + + + @JsonProperty("User-Name") + private String userName; + + + @JsonProperty("User-Password") + private String userPassword; + + + @JsonProperty("Authentication-token") + private String token; + + + @JsonProperty("Response-Message") + private String message; + + + @JsonProperty("Response-Status") + private Integer httpStatus; + + @JsonProperty("data") + private T data; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserPassword() { + return userPassword; + } + + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Integer getHttpStatus() { + return httpStatus; + } + + public void setHttpStatus(Integer httpStatus) { + this.httpStatus = httpStatus; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ResponseBean.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ResponseBean.java new file mode 100644 index 00000000..268245fc --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/bean/ResponseBean.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.bean; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@XmlRootElement(name = "response") +@XmlAccessorType(XmlAccessType.FIELD) +public class ResponseBean implements Serializable{ + + private T data; + + private String message; + + @XmlElement(name = "statusCode") + private Integer statusCode = 200; + + @XmlElement(name = "statusMessage") + private String statusMessage = "Success"; + + @XmlElement(name = "success") + private Boolean success = true; + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Integer getStatusCode() { + return statusCode; + } + + public void setStatusCode(Integer statusCode) { + this.statusCode = statusCode; + } + + public String getStatusMessage() { + return statusMessage; + } + + public void setStatusMessage(String statusMessage) { + this.statusMessage = statusMessage; + } + + public Boolean getSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/ApplicationRestController.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/ApplicationRestController.java new file mode 100644 index 00000000..0de4c70d --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/ApplicationRestController.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller; + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.web.bean.ApiServerViewBean; +import com.espark.adarsh.web.manager.UserManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@RestController +public class ApplicationRestController { + + @Autowired(required = true) + private UserManager userManager; + + @RequestMapping(value = "/welcomeRest", method = RequestMethod.GET) + public Map welcome() { + return new HashMap() { + { + put("name", System.getProperty("user.name")); + put("message", "welcome to espark application"); + } + }; + } + + @RequestMapping(value = "/rest/users", method = RequestMethod.GET, produces = {"application/json"}) + public + @ResponseBody + ApiServerViewBean getAllUser() { + final ApiServerViewBean> apiServerViewBean = new ApiServerViewBean>(); + apiServerViewBean.setMessage("User Data "); + apiServerViewBean.setData(this.userManager.getAllUser()); + apiServerViewBean.setHttpStatus(HttpServletResponse.SC_OK); + return apiServerViewBean; + } + +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationController.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationController.java new file mode 100644 index 00000000..e348b38c --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationController.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller; + + + +import com.espark.adarsh.web.bean.ApiServerViewBean; +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.security.TokenProvider; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Scope; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Lazy(value = false) +@Scope(value = "singleton") +@RestController +public class RestAuthenticationController { + + private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationController.class); + + public static final String LOGIN_URL="/rest/authenticate/login"; + + @Autowired(required = true) + private UserManager userManager; + + @Autowired(required = true) + private TokenProvider tokenProvider; + + private final String USERNAME = "username"; + private final String PASSWORD = "password"; + + + // http://localhost:8080/ + @RequestMapping(value = LOGIN_URL, method = RequestMethod.POST) + public + @ResponseBody + ApiServerViewBean authenticateUser(@RequestBody Map map, HttpServletResponse httpServletResponse) { + final ApiServerViewBean apiServer = new ApiServerViewBean(); + logger.debug("Inside-AuthenticationController "); + + final String loginSuccessMsg="LOGIN SUCCESSFUL"; + final String loginFailureMsg="LOGIN UNSUCCESSFUL"; + + + final String username = map.get(USERNAME); + final String password = map.get(PASSWORD); + + try { + final User user = userManager.getUserByName(new User(username)); + if(user!=null){ + if(!user.getUserPwd().equals(password)){ + throw new BadCredentialsException("Invalid User Credentials "); + } + final String token = tokenProvider.getToken(user); + httpServletResponse.setHeader("Authentication-token", token); + apiServer.setToken(token); + apiServer.setUserName(username); + apiServer.setUserPassword(password); + apiServer.setMessage(loginSuccessMsg); + apiServer.setHttpStatus(HttpServletResponse.SC_OK); + } else { + throw new RuntimeException("User Not Found "); + } + return apiServer; + + } catch (Exception e) { + logger.error("Exception Generated "+e.getMessage()); + apiServer.setMessage(loginFailureMsg + " - " + e.getMessage()); + apiServer.setHttpStatus(HttpServletResponse.SC_UNAUTHORIZED); + return apiServer; + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebApplicationController.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebApplicationController.java new file mode 100644 index 00000000..25410995 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebApplicationController.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller; + +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; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Controller +public class WebApplicationController { + + private static final String welcomeMsg="WELCOME TO THE ESPARK"; + + @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET) + public ModelAndView welcomePage() { + ModelAndView model = new ModelAndView(); + model.addObject("title", welcomeMsg); + model.addObject("message", "This is welcome page!"); + model.setViewName("home"); + return model; + } + + @RequestMapping(value = "/sadmin/page", method = RequestMethod.GET) + public ModelAndView sAdminPage() { + ModelAndView model = new ModelAndView(); + model.addObject("title", welcomeMsg); + model.addObject("message", "This is protected page - Super Admin Page!"); + model.setViewName("sadmin"); + return model; + + } + + @RequestMapping(value = "/admin/page", method = RequestMethod.GET) + public ModelAndView adminPage() { + + ModelAndView model = new ModelAndView(); + model.addObject("title", welcomeMsg); + model.addObject("message", "This is protected page - Admin Page!"); + model.setViewName("admin"); + + return model; + + } + + @RequestMapping(value = "/user/page", method = RequestMethod.GET) + public ModelAndView dbaPage() { + ModelAndView model = new ModelAndView(); + model.addObject("title", welcomeMsg); + model.addObject("message", "This is protected page - User Page!"); + model.setViewName("user"); + return model; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebLoginController.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebLoginController.java new file mode 100644 index 00000000..39968ec7 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/controller/WebLoginController.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Controller +public class WebLoginController { + + private static final String welcomeMsg = "WELCOME TO THE ESPARK"; + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public ModelAndView loginPage(@RequestParam(value = "error", required = false) String error, + @RequestParam(value = "logout", required = false) String logout) { + + ModelAndView model = new ModelAndView(); + if (error != null) { + model.addObject("error", "Invalid Credentials provided."); + } + + if (logout != null) { + model.addObject("message", welcomeMsg); + } + + model.setViewName("login"); + return model; + } + + @RequestMapping(value = "/logout", method = RequestMethod.GET) + public String logoutPage(HttpServletRequest request, HttpServletResponse response) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { + new SecurityContextLogoutHandler().logout(request, response, auth); + } + return "redirect:/login?logout"; + } + + @RequestMapping(value = "/accessDenied", method = RequestMethod.GET) + public String accessDeniedPage(HttpServletRequest request, HttpServletResponse response) { + return "accessDenied"; + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java new file mode 100644 index 00000000..5439083f --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.manager; + + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface UserManager { + public void refreshUser(User user); + public Boolean saveUser(User user); + public Boolean updateUser(User user); + public Boolean deleteUser(User user); + public User getUser(User user); + public User getUserById(User user); + public User getUserByName(User user); + public Collection getAllUser(); + public UserRole getUserRole(String roleName); +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java new file mode 100644 index 00000000..222f2dc2 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.manager; + + +import com.espark.adarsh.persistence.entities.impl.User; +import com.espark.adarsh.persistence.entities.impl.UserRole; +import com.espark.adarsh.persistence.repositories.RoleRepository; +import com.espark.adarsh.persistence.repositories.UserRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Service("userManager") +final public class UserManagerImpl + implements UserManager { + + private final static Logger logger = LoggerFactory.getLogger(UserManagerImpl.class); + + public UserManagerImpl() { + } + + @Override + public void refreshUser(User user) { + userRepository.refreshUser(user); + } + + @Transactional + public Boolean saveUser(User user) { + userRepository.saveUser(user); + return null; + } + + @Transactional + public Boolean updateUser(User user) { + userRepository.updateUser(user); + return null; + } + + @Transactional + public Boolean deleteUser(User user) { + userRepository.deleteUser(user); + return null; + } + + public User getUser(final User user) { + return userRepository.getUser(user); + } + + @Override + public Collection getAllUser() { + return userRepository.getAllUser(); + } + + @Override + public User getUserById(User user) { + return userRepository.getUserById(user); + } + + @Override + public User getUserByName(User user) { + return userRepository.getUserByName(user); + } + + @Override + public UserRole getUserRole(String roleName) { + return roleRepository.getRoleByName(roleName); + } + + @Qualifier("userRepositoryImpl") + @Autowired + private UserRepository userRepository; + + public void setUserRepository(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Qualifier("roleRepositoryImpl") + @Autowired + private RoleRepository roleRepository; + + public void setRoleRepository(RoleRepository roleRepository) { + this.roleRepository = roleRepository; + } +} diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/accessDenied.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/accessDenied.jsp new file mode 100644 index 00000000..51e2d1d4 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/accessDenied.jsp @@ -0,0 +1,20 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + + + + +
+

INSUFFICIENT PRIVILEGE

+
+ + diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/admin.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/admin.jsp new file mode 100644 index 00000000..348ac3ec --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/admin.jsp @@ -0,0 +1,38 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve +--%> +<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@page session="true" %> + + + + + + + +
+
+

+ + Welcome : ${pageContext.request.userPrincipal.name} | + Logout + + Espark Home +

+
+
+
+
+

${title}

+
+ +
${message}
+
+
+
+ + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/home.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/home.jsp new file mode 100644 index 00000000..8f4dbbc0 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/home.jsp @@ -0,0 +1,55 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * +--%> +<%@page isELIgnored="false" session="true" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + + + +
+
+

+ + Welcome : ${pageContext.request.userPrincipal.name} | + Logout + +

+
+ +
+
+
+

${title}

+
+ +

${message}

+ +
+
+ + Super Admin Home + + + + Admin Home + + + + User Home + +
+ +
+ +
+ + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/login.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/login.jsp new file mode 100644 index 00000000..7e607f46 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/login.jsp @@ -0,0 +1,59 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve +--%> + +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + + + + + + + +
+
+
+ + + +
+

${message}

+
+
+
+
+ Login Window + +
+

${error}

+
+
+
+ + +
+
+ + +
+
+ +
+
+ +
+ +
+
+
+ + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/sadmin.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/sadmin.jsp new file mode 100644 index 00000000..89afea18 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/sadmin.jsp @@ -0,0 +1,42 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve +--%> +<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@page session="true" %> + + + + + + + +
+
+

+ + Welcome : ${pageContext.request.userPrincipal.name} | + Logout + + Espark Home +

+
+ +
+ +
+ +
+

${title}

+
+ +
${message}
+
+
+ + +
+ + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/user.jsp b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/user.jsp new file mode 100644 index 00000000..7f0694dc --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/META-INF/resources/WEB-INF/jsp/user.jsp @@ -0,0 +1,39 @@ +<%-- + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve +--%> +<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@page session="true" %> + + + + + + + + +
+
+

+ + Welcome : ${pageContext.request.userPrincipal.name} | + Logout + + Espark Home +

+
+
+
+
+

${title}

+
+ +
${message}
+
+
+
+ + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/application.properties new file mode 100644 index 00000000..09a32f7f --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.mvc.view.prefix=/WEB-INF/jsp/ +spring.mvc.view.suffix=.jsp + +token-secret-key=TOKEN + + +# Log levels severity mapping. +logging.file=application.log +logging.path=\\log +logging.level.org.hibernate.*= ALL +logging.level.org.springframework.security.web.*= ALL +logging.level.org.springframework.security.core.*= ALL +logging.level.com.espark.adarsh.*=ALL +logging.level.org.springframework.web.*=ALL +logging.level.org.springframework.boot.*=ALL +logging.level.org.springframework.jpa.*=ALL \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/database/database.sql b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/database/database.sql new file mode 100644 index 00000000..e257ce6c --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/database/database.sql @@ -0,0 +1,67 @@ +DROP TABLE IF EXISTS `user_role_mapping`; +DROP TABLE IF EXISTS `userrole`; +DROP TABLE IF EXISTS `user`; + + +CREATE TABLE `user` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `createdDate` datetime DEFAULT NULL, + `enabled` tinyint(1) NOT NULL, + `firstName` varchar(24) NOT NULL, + `lastName` varchar(24) DEFAULT NULL, + `modifiedDate` datetime DEFAULT NULL, + `userEmail` varchar(100) NOT NULL, + `userName` varchar(24) NOT NULL, + `userPhone` varchar(10) DEFAULT NULL, + `userPwd` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + UNIQUE KEY `userName` (`userName`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +CREATE TABLE `userrole` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +CREATE TABLE `user_role_mapping` ( + `User_id` bigint(20) NOT NULL, + `userRoles_id` bigint(20) NOT NULL, + PRIMARY KEY (`User_id`,`userRoles_id`), + KEY `FK5D9A9F9181C6E86` (`User_id`), + KEY `FK5D9A9F9995F6035` (`userRoles_id`), + CONSTRAINT `FK5D9A9F9995F6035` FOREIGN KEY (`userRoles_id`) REFERENCES `userrole` (`id`), + CONSTRAINT `FK5D9A9F9181C6E86` FOREIGN KEY (`User_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +INSERT INTO `USER` +(`id`,`createdDate`,`enabled`,`firstName`,`lastName`,`modifiedDate`,`userEmail`,`userName`,`userPhone`,`userPwd`) +VALUES(1,'2015-01-01',1,'adarsh','kumar','2015-01-01','adarsh@kumar','adarsh','8197416336','adarsh') + ,(2,'2015-01-01',1,'admin','kumar','2015-01-01','admin@kumar','admin','8197416336','admin') + ,(3,'2015-01-01',1,'user','kumar','2015-01-01','user@kumar','user','8197416336','user'); + +-- When Encryption is enabled +-- Encryption of Adarsh pwd $2a$10$mc7NY8ZlU/ASATaTaQRYfuxNAJDA5S3NSr0jMM1oSqCWSuURsMUuq +-- Encryption of Admin pwd $2a$10$i5jVLzELbFBsL35Ut9WICeMyHFDQnGOrcYs2Q80ornhubErrngwVW +-- Encryption of User pwd $2a$10$3L4krlIm76O6SaR4njs.GOfqDS5Yu.4QU9Uhbr6tjeJi0xXswMGjK +-- INSERT INTO `USER` +-- (`id`,`createdDate`,`enabled`,`firstName`,`lastName`,`modifiedDate`,`userEmail`,`userName`,`userPhone`,`userPwd`) +-- VALUES(1,'2015-01-01',1,'adarsh','kumar','2015-01-01','adarsh@kumar','adarsh','8197416336','$2a$10$mc7NY8ZlU/ASATaTaQRYfuxNAJDA5S3NSr0jMM1oSqCWSuURsMUuq') +-- ,(2,'2015-01-01',1,'admin','kumar','2015-01-01','admin@kumar','admin','8197416336','$2a$10$i5jVLzELbFBsL35Ut9WICeMyHFDQnGOrcYs2Q80ornhubErrngwVW') +-- ,(3,'2015-01-01',1,'user','kumar','2015-01-01','user@kumar','user','8197416336','$2a$10$3L4krlIm76O6SaR4njs.GOfqDS5Yu.4QU9Uhbr6tjeJi0xXswMGjK'); + + +INSERT INTO `USERROLE`(`ID`,`NAME`) +VALUES(1,'ROLE_SUPERADMIN') + ,(2,'ROLE_ADMIN') + ,(3,'ROLE_USER'); + +INSERT INTO `user_role_mapping`(`User_id`,`userRoles_id`) +VALUES((SELECT ID FROM USER WHERE USERNAME='adarsh'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_SUPERADMIN')) + ,((SELECT ID FROM USER WHERE USERNAME='admin'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_ADMIN')) + ,((SELECT ID FROM USER WHERE USERNAME='user'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_USER')); \ No newline at end of file diff --git a/SpringBootRestMvcSecurityExample/src/main/resources/ehcache.xml b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/ehcache.xml similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/resources/ehcache.xml rename to APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/ehcache.xml diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/dataSource.properties b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/dataSource.properties new file mode 100644 index 00000000..2fbe5aeb --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/dataSource.properties @@ -0,0 +1,8 @@ +dataSource.driverClass=com.mysql.jdbc.Driver +dataSource.url=jdbc:mysql:// +dataSource.hostname=127.0.0.1 +dataSource.portNumber=:3306 +dataSource.database=/espark +dataSource.extraParam=?autoReconnect=true +dataSource.username=adarsh +dataSource.password=adarsh \ No newline at end of file diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/hibernate.properties b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/hibernate.properties new file mode 100644 index 00000000..2f0543e6 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/properties/hibernate.properties @@ -0,0 +1,13 @@ +#hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect +hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect +hibernate.hbm2ddl.auto=update +hibernate.max_fetch_depth=1 +hibernate.batch_size=100 +hibernate.jdbc.use_scrollable_resultset=true +hibernate.generate_statistics=false +hibernate.format_sql=true +hibernate.show_sql=true +#Cache configuration +hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider +hibernate.cache.use_second_level_cache=true +#hibernate.cache.use_query_cache=true diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/css/bootstrap.min.css new file mode 100644 index 00000000..679272d2 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/css/bootstrap.min.css @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.1.1 (http://getbootstrap.com) + * Copyright 2011-2014 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ + +/*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}@media print{*{text-shadow:none!important;color:#000!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#999}h1,.h1,h2,.h2,h3,.h3{margin-top:20px;margin-bottom:10px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:10px;margin-bottom:10px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:200;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}cite{font-style:normal}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-muted{color:#999}.text-primary{color:#428bca}a.text-primary:hover{color:#3071a9}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#428bca}a.bg-primary:hover{background-color:#3071a9}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none;margin-left:-5px}.list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#999}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;white-space:nowrap;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.row{margin-left:-15px;margin-right:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:0}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:0}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:0}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:0}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:0}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:0}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:0}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:0}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*=col-]{position:static;float:none;display:table-column}table td[class*=col-],table th[class*=col-]{position:static;float:none;display:table-cell}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th{background-color:#d0e9c6}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#d9edf7}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th{background-color:#c4e3f3}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th{background-color:#faf2cc}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th{background-color:#ebcccc}@media (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;overflow-x:scroll;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd;-webkit-overflow-scrolling:touch}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0;min-width:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date]{line-height:34px}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;margin-top:10px;margin-bottom:10px;padding-left:20px}.radio label,.checkbox label{display:inline;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm,select[multiple].input-sm{height:auto}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:46px;line-height:46px}textarea.input-lg,select[multiple].input-lg{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.has-feedback .form-control-feedback{position:absolute;top:25px;right:0;display:block;width:34px;height:34px;line-height:34px;text-align:center}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.form-control-static{margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{float:none;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-control-static{padding-top:7px}@media (min-width:768px){.form-horizontal .control-label{text-align:right}}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:14px;line-height:1.42857143;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#3276b1;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#47a447;border-color:#398439}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#39b3d7;border-color:#269abc}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#ed9c28;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#d2322d;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{text-decoration:none;color:#262626;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;outline:0;background-color:#428bca}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);cursor:not-allowed}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{left:auto;right:0}.dropdown-menu-left{left:0;right:auto}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#999}.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.navbar-right .dropdown-menu{left:auto;right:0}.navbar-right .dropdown-menu-left{left:0;right:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:4px;border-top-right-radius:0;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.btn-group-justified>.btn-group .btn{width:100%}[data-toggle=buttons]>.btn>input[type=radio],[data-toggle=buttons]>.btn>input[type=checkbox]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{margin-bottom:0;padding-left:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;background-color:transparent;cursor:not-allowed}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,.1);-webkit-overflow-scrolling:touch}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-left:0;padding-right:0}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:15px;font-size:18px;line-height:20px;height:50px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{margin-left:-15px;margin-right:-15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);margin-top:8px;margin-bottom:8px}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;padding-left:0;vertical-align:middle}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{float:none;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media (min-width:768px){.navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-left:15px;margin-right:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{background-color:#e7e7e7;color:#555}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{background-color:#080808;color:#fff}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{content:"/\00a0";padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.42857143;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pager{padding-left:0;margin:20px 0;list-style:none;text-align:center}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;background-color:#fff;cursor:not-allowed}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:gray}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#999;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.container .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-left:60px;padding-right:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-left:auto;margin-right:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#428bca}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{margin-bottom:20px;padding-left:0}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}a.list-group-item.active,a.list-group-item.active:hover,a.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}a.list-group-item.active .list-group-item-heading,a.list-group-item.active:hover .list-group-item-heading,a.list-group-item.active:focus .list-group-item-heading{color:inherit}a.list-group-item.active .list-group-item-text,a.list-group-item.active:hover .list-group-item-text,a.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.panel>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{border:0;margin-bottom:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px;overflow:hidden}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#428bca}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#d6e9c6}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#bce8f1}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#faebcc}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#ebccd1}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ebccd1}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{display:none;overflow:auto;overflow-y:scroll;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.42857143px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:20px}.modal-footer{margin-top:15px;padding:19px 20px 20px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.tooltip.bottom{margin-top:3px;padding:5px 0}.tooltip.left{margin-left:-3px;padding:0 5px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;right:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:400;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{border-width:10px;content:""}.popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.carousel{position:relative}.carousel-inner{position:relative;overflow:hidden;width:100%}.carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-control.left{background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.5) 0),color-stop(rgba(0,0,0,.0001) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1)}.carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,.0001) 0),color-stop(rgba(0,0,0,.5) 100%));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1)}.carousel-control:hover,.carousel-control:focus{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0)}.carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{left:20%;right:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{content:" ";display:table}.clearfix:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}@media print{.hidden-print{display:none!important}} \ No newline at end of file diff --git a/SpringBootRestMvcSecurityExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/js/bootstrap.min.js diff --git a/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/js/jquery.js b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/js/jquery.js new file mode 100644 index 00000000..dd3cd4c7 --- /dev/null +++ b/APPLICATIONS/SpringBootMvcAndRestExample/src/main/resources/static/js/jquery.js @@ -0,0 +1,10308 @@ +/*! + * jQuery JavaScript Library v1.11.1 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-05-01T17:42Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper window is present, + // execute the factory and get jQuery + // For environments that do not inherently posses a window with a document + // (such as Node.js), expose a jQuery-making factory as module.exports + // This accentuates the need for the creation of a real window + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +// + +var deletedIds = []; + +var slice = deletedIds.slice; + +var concat = deletedIds.concat; + +var push = deletedIds.push; + +var indexOf = deletedIds.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "1.11.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1, IE<9 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + // See test/unit/web.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( support.ownLast ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1, IE<9 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + while ( j < len ) { + first[ i++ ] = second[ j++ ]; + } + + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: function() { + return +( new Date() ); + }, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v1.10.19 + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-04-18 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== strundefined && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, + doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", function() { + setDocument(); + }, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", function() { + setDocument(); + }); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { + div.innerHTML = "
"; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowclip^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !(--remaining) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * Clean-up method for dom ready events + */ +function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } +} + +/** + * The ready event handler and self cleanup method + */ +function completed() { + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + + +var strundefined = typeof undefined; + + + +// Support: IE<9 +// Iteration over object's inherited properties before its own +var i; +for ( i in jQuery( support ) ) { + break; +} +support.ownLast = i !== "0"; + +// Note: most support tests are defined in their respective modules. +// false until the test is run +support.inlineBlockNeedsLayout = false; + +// Execute ASAP in case we need to set body.style.zoom +jQuery(function() { + // Minified: var a,b,c,d + var val, div, body, container; + + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { + // Return for frameset docs that don't have a body + return; + } + + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); + + if ( typeof div.style.zoom !== strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; + + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); +}); + + + + +(function() { + var div = document.createElement( "div" ); + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( elem ) { + var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], + nodeType = +elem.nodeType || 1; + + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : + + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute("classid") === noData; +}; + + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + +function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[0], + attrs = elem && elem.attributes; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; +}; +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + // Minified: var a,b,c + var input = document.createElement( "input" ), + div = document.createElement( "div" ), + fragment = document.createDocumentFragment(); + + // Setup + div.innerHTML = "
a"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; + + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); + div.innerHTML = ""; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + support.noCloneEvent = true; + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } +})(); + + +(function() { + var i, eventName, + div = document.createElement( "div" ); + + // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) + for ( i in { submit: true, change: true, focusin: true }) { + eventName = "on" + i; + + if ( !(support[ i + "Bubbles" ] = eventName in window) ) { + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!support.noCloneEvent || !support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + deletedIds.push( id ); + } + } + } + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optmization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( " + + + \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/css/bootstrap-theme.min.css diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/css/bootstrap.min.css similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/css/bootstrap.min.css diff --git a/SpringBootWebMvcJspExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/js/bootstrap.min.js similarity index 100% rename from SpringBootWebMvcJspExample/src/main/webapp/js/bootstrap.min.js rename to APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/js/bootstrap.min.js diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/js/jquery.min.js similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/js/jquery.min.js rename to APPLICATIONS/SpringBootRestMvcExample/src/main/webapp/js/jquery.min.js diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java b/APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java rename to APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java b/APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java rename to APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java diff --git a/APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java b/APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java new file mode 100644 index 00000000..c6738bad --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java @@ -0,0 +1,56 @@ +package com.espark.adarsh.test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.util.Assert; + + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +@RunWith(SpringJUnit4ClassRunner.class) +public class TestWebRestServices extends AbstractWebServicesTest { + + @Before + public void init() throws JsonProcessingException { + LOG.info("init TestWebRestServices"); + } + + @Test + public void testLoadApplication() throws Exception { + final String token = this.generateTokenWithAuthenticatedUser(); + LOG.info(token); + Assert.notNull(token, "Token is Null"); + } + + @Test + public void testLoginForUser() throws Exception { + final String jsonString=super.generateTokenWithAuthenticatedUser(); + LOG.debug("controller returns : {}", jsonString); + Assert.notNull(jsonString, "Resulted Json is Null"); + } + + + @Test + public void testGetWelcomeMsgForUser() throws Exception { + final String token = super.generateTokenWithAuthenticatedUser(); + final String url = "/rest/welcome"; + final ResultActions apiResultActions = this.mockMvc.perform(get(url) + .header("Authentication-token", token) + .contentType(MediaType.APPLICATION_JSON)); + final String jsonString = apiResultActions.andReturn().getResponse().getContentAsString(); + LOG.debug("controller returns : {}", jsonString); + Assert.notNull(jsonString, "Resulted Json is Null"); + } + + @After + public void destroy() { + LOG.info("destroy TestWebRestServices"); + } +} diff --git a/SpringBootRestMvcSecurityExample/pom.xml b/APPLICATIONS/SpringBootRestMvcSecurityExample/pom.xml similarity index 100% rename from SpringBootRestMvcSecurityExample/pom.xml rename to APPLICATIONS/SpringBootRestMvcSecurityExample/pom.xml diff --git a/SpringBootRestMvcSecurityExample/src/main/docs/help.txt b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/docs/help.txt similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/docs/help.txt rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/docs/help.txt diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..de9812f2 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@EnableWebMvc +@ComponentScan("com.espark.adarsh") +@EnableAutoConfiguration +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/annotations/WebMvcController.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/annotations/WebMvcController.java new file mode 100644 index 00000000..c02c59ed --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/annotations/WebMvcController.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.annotations; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RestController; + +import java.lang.annotation.*; + +/** + * @Author: Adarsh_K + * @Author: $LastChangeBy Adarsh_K + * @Version $Revised Date: 9/1/13 Time: 9:26 AM + * @Espark @copyright all right reserve + * @see org.springframework.stereotype.Component + */ + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Controller +public @interface WebMvcController { +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java new file mode 100644 index 00000000..41f3aeb0 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.bean; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class ResponseBean implements Serializable{ + + private T data; + private String message; + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/UserCreateForm.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/UserCreateForm.java new file mode 100644 index 00000000..4581f420 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/bean/UserCreateForm.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.bean; + +import com.espark.adarsh.persistence.entites.impl.UserRole; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.constraints.NotNull; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class UserCreateForm { + + @NotEmpty + private String userName= ""; + + private String userPhone= ""; + + private Boolean enabled =true; + + @NotEmpty + private String firstName= ""; + + @NotEmpty + private String lastName= ""; + + @NotEmpty + private String email = ""; + + @NotEmpty + private String password = ""; + + @NotEmpty + private String passwordRepeated = ""; + + @NotNull + private String roleName="" ; + + private UserRole userRole; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public void setRole(UserRole userRole) { + this.userRole = userRole; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPasswordRepeated() { + return passwordRepeated; + } + + public void setPasswordRepeated(String passwordRepeated) { + this.passwordRepeated = passwordRepeated; + } + + public String getRoleName() { + return roleName; + } + + public UserRole getRole() { + return userRole; + } + + @Override + public String toString() { + return "UserCreateForm{" + + "email='" + email.replaceFirst("@.+", "@***") + '\'' + + ", password=***" + '\'' + + ", passwordRepeated=***" + '\'' + + ", role=" + roleName + + '}'; + } + +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/security/RestMvcSecurityConfiguration.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/security/RestMvcSecurityConfiguration.java new file mode 100644 index 00000000..0be07e63 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/security/RestMvcSecurityConfiguration.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.configuration.security; + +import com.espark.adarsh.web.controller.rest.ApplicationController; +import com.espark.adarsh.web.controller.rest.RestAuthenticationServiceImpl; +import com.espark.adarsh.web.security.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.security.SecurityProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.encoding.Md5PasswordEncoder; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@Configuration +@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) +@EnableGlobalMethodSecurity(securedEnabled = true) +public class RestMvcSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter { + + + @EnableGlobalMethodSecurity(prePostEnabled = true) + @Configuration + @Order(1) + public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { + + @Override + public void configure(WebSecurity webSecurity) throws Exception { + webSecurity.ignoring().antMatchers("*.js") + .antMatchers("*.css") + .antMatchers("/imaages/**") + .antMatchers("*.ico") + .antMatchers("/rest/authenticate/login"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + + http.regexMatcher("/rest/*") + .csrf().disable() + // never use server side sessions (stateless mode) + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers(RestAuthenticationServiceImpl.LOGIN_URL).permitAll() + .antMatchers(ApplicationController.WELCOME_URL).hasAnyAuthority(getAllRoles()) + .antMatchers("/rest/**").authenticated() + .and() + .httpBasic().disable() + .formLogin().disable() + .rememberMe().disable() + .requestCache().disable() + .x509().disable() + .logout().disable() + //.anonymous().disable() + // add custom authentication filter + .addFilterBefore(this.getAuthenticationTokenProcessingFilter(), BasicAuthenticationFilter.class) + // register custom authentication exception handler + .exceptionHandling().authenticationEntryPoint(this.getEntryPointBean()) + .accessDeniedHandler(this.getAccessDeniedHandler()); + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(getRestApiAuthProvider()); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean(name = "authenticationProvider") + public AuthenticationProvider getRestApiAuthProvider() { + return new RestApiAuthProvider(); + } + + @Bean + public AuthenticationTokenProcessingFilter getAuthenticationTokenProcessingFilter() throws Exception { + return new AuthenticationTokenProcessingFilter(this.authenticationManager(), this.tokenService()); + } + + @Bean(name = "entryPoint") + public ApiServerAuthenticationEntryPoint getEntryPointBean() { + return new ApiServerAuthenticationEntryPoint(); + } + + @Bean(name = "accessDeniedHandler") + public RestAccessDeniedHandler getAccessDeniedHandler() { + return new RestAccessDeniedHandler(); + } + + @Bean(name = "md5PasswordEncoder") + public Md5PasswordEncoder getEncoder() { + return new Md5PasswordEncoder(); + } + + @Bean + public TokenService tokenService() { + return new TokenService(); + } + } + + @EnableGlobalMethodSecurity(prePostEnabled = true) + @Configuration + @Order(2) + public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Override + public void configure(WebSecurity webSecurity) throws Exception { + webSecurity.ignoring().antMatchers("*.js") + .antMatchers("*.css") + .antMatchers("/imaages/*") + .antMatchers("*.ico"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/home").hasAnyRole(getAllRoles()) + .antMatchers("/**").authenticated() + .anyRequest().fullyAuthenticated() + .and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/") + .failureUrl("/login?error=true") + .usernameParameter("username") + .passwordParameter("password") + .permitAll() + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("remember-me") + .logoutSuccessUrl("/login?logout=true") + .permitAll() + .and() + .rememberMe(); + } + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + // with encryption + //auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); + // without encryption + auth.userDetailsService(userDetailsService); + } + } + + private static String[] getAllRoles() { + return new String[]{"ROLE_SUPERADMIN", "ROLE_ADMIN", "ROLE_USER"}; + } +} diff --git a/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java new file mode 100644 index 00000000..c37dcec4 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.entites.impl; + +import com.espark.adarsh.bean.UserCreateForm; +import com.espark.adarsh.persistence.entites.construct.AbstractEntity; +import org.springframework.util.DigestUtils; + +import javax.persistence.*; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Entity +@Table(name = "User") +public final class User extends AbstractEntity { + + @Column(unique = true, length = 24, nullable = false) + private String userName; + + @Column(length = 100, nullable = false) + private String userEmail; + + + @Column(length = 100, nullable = false) + private String userPwd; + + @Column(length = 10, nullable = true) + private String userPhone; + + @Column(nullable = false) + private Boolean enabled; + + + @Column(length = 24, nullable = false) + private String firstName; + + @Column(length = 24, nullable = true) + private String lastName; + + + @Column + @Temporal(value = TemporalType.TIMESTAMP) + private Date createdDate; + + @Column + @Temporal(value = TemporalType.TIMESTAMP) + private Date modifiedDate; + + + @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @JoinTable(name = "user_role_mapping") + private Set userRoles; + + + + public User() { + super(User.class); + } + + public User(Long id) { + super(User.class); + super.setId(id); + this.setUserName(""); + } + + + public User(String userName) { + this(); + this.userName = userName; + } + + public User(User user) { + super(User.class); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.userEmail = user.getUserEmail(); + this.enabled = user.getEnabled(); + this.userName = user.getUserName(); + this.setUserPwd(user.getUserPwd()); + this.userPhone = user.getUserPhone(); + this.setUserRoles(user.getUserRoles()); + this.setModifiedDate(new Date()); + this.setCreatedDate(new Date()); + } + + public User(final UserCreateForm userCreateForm){ + super(User.class); + this.firstName = userCreateForm.getFirstName(); + this.lastName = userCreateForm.getLastName(); + this.userEmail = userCreateForm.getEmail(); + this.enabled = userCreateForm.getEnabled(); + this.userName = userCreateForm.getUserName(); + this.setUserPwd(userCreateForm.getPassword()); + this.userPhone = userCreateForm.getUserPhone(); + this.setUserRoles(new HashSet(){ + { + add(userCreateForm.getRole()); + } + }); + this.setModifiedDate(new Date()); + this.setCreatedDate(new Date()); + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserEmail() { + return userEmail; + } + + public void setUserEmail(String userEmail) { + this.userEmail = userEmail; + } + + public String getUserPwd() { + return userPwd; + } + + public void setUserPwd(String userPwd) { + //this.userPwd = DigestUtils.md5DigestAsHex(userPwd.getBytes()); + this.userPwd = userPwd; + } + + public String getUserPhone() { + return userPhone; + } + + public void setUserPhone(String userPhone) { + this.userPhone = userPhone; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Set getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set userRoles) { + this.userRoles = userRoles; + } + + public void setRole(UserRole roles) { + if (userRoles == null) { + userRoles = new HashSet(); + } + this.userRoles.add(roles); + } + + + + @Override + public String toString() { + return "User{" + + "userName='" + userName + '\'' + + ", userEmail='" + userEmail + '\'' + + ", userPwd='" + userPwd + '\'' + + ", enabled=" + enabled + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", createdDate=" + createdDate + + ", modifiedDate=" + modifiedDate + + ", userRoles=" + userRoles.iterator().next().getName() + + '}'; + } +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java new file mode 100644 index 00000000..f6881cc1 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface Repository { +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/CurrentUserControllerAdvice.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/CurrentUserControllerAdvice.java new file mode 100644 index 00000000..61e84a30 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/CurrentUserControllerAdvice.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web; + + +import com.espark.adarsh.annotations.WebMvcController; +import com.espark.adarsh.web.controller.web.LoginController; +import com.espark.adarsh.web.controller.web.UserController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ModelAttribute; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@ControllerAdvice(assignableTypes = {LoginController.class, UserController.class}) +public class CurrentUserControllerAdvice { + + private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserControllerAdvice.class); + + @ModelAttribute("currentUser") + public UserDetails getCurrentUser(Authentication authentication) { + try{ + return (authentication == null ? null : (UserDetails) authentication.getPrincipal()); + }catch (Exception e){ + LOGGER.error("Exception "+e.getLocalizedMessage()); + } + return null; + } + +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/ApplicationController.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/ApplicationController.java new file mode 100644 index 00000000..649bf625 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/ApplicationController.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller.rest; + +import com.espark.adarsh.bean.ResponseBean; +import com.espark.adarsh.web.security.SecurityContextProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@RestController +public class ApplicationController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationController.class); + + public static final String WELCOME_URL="/rest/welcome"; + + @Value("${application.message}") + private String message; + + private SecurityContextProvider securityContextProvider = new SecurityContextProvider(); + + + @RequestMapping(value = WELCOME_URL, method = RequestMethod.GET) + public + @ResponseBody + ResponseBean> welcome() { + final Map data = new HashMap<>(); + data.put("time", new Date()); + data.put("message", this.message + " " + securityContextProvider.getUserDetails()); + final ResponseBean> responseBean = new ResponseBean>(); + responseBean.setData(data); + responseBean.setMessage("Request Process Successful"); + return responseBean; + } + + +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationService.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationService.java new file mode 100644 index 00000000..09ba44e4 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationService.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller.rest; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface RestAuthenticationService { +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationServiceImpl.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationServiceImpl.java new file mode 100644 index 00000000..9f27350a --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/rest/RestAuthenticationServiceImpl.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller.rest; + + +import com.espark.adarsh.bean.ApiServerViewBean; +import com.espark.adarsh.web.security.TokenProvider; +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Scope; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */@Lazy(value = false) +@Scope(value = "singleton") +@RestController +public class RestAuthenticationServiceImpl + implements RestAuthenticationService{ + + private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationServiceImpl.class); + + public static final String LOGIN_URL="/rest/authenticate/login"; + + @Autowired(required = true) + private UserManager userManager; + + @Autowired(required = true) + private TokenProvider tokenProvider; + + private final String USERNAME = "username"; + private final String PASSWORD = "password"; + + + // http://localhost:8080/ + @RequestMapping(value = LOGIN_URL, method = RequestMethod.POST) + public + @ResponseBody + ApiServerViewBean authenticateUser(@RequestBody Map map, HttpServletResponse httpServletResponse) { + final ApiServerViewBean apiServer = new ApiServerViewBean(); + logger.debug("Inside-AuthenticationController "); + + final String loginSuccessMsg="LOGIN SUCCESSFUL"; + final String loginFailureMsg="LOGIN UNSUCCESSFUL"; + + + final String username = map.get(USERNAME); + final String password = map.get(PASSWORD); + + try { + final User user = userManager.getUserByName(new User(username)); + if(user!=null){ + if(!user.getUserPwd().equals(password)){ + throw new BadCredentialsException("Invalid User Credentials "); + } + final String token = tokenProvider.getToken(user); + httpServletResponse.setHeader("Authentication-token", token); + apiServer.setToken(token); + apiServer.setUserName(username); + apiServer.setUserPassword(password); + apiServer.setMessage(loginSuccessMsg); + apiServer.setHttpStatus(HttpServletResponse.SC_OK); + } else { + throw new RuntimeException("User Not Found "); + } + return apiServer; + + } catch (Exception e) { + logger.error("Exception Generated "+e.getMessage()); + apiServer.setMessage(loginFailureMsg + " - " + e.getMessage()); + apiServer.setHttpStatus(HttpServletResponse.SC_UNAUTHORIZED); + return apiServer; + } + } +} \ No newline at end of file diff --git a/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/LoginController.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/LoginController.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/LoginController.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/LoginController.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/UserController.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/UserController.java new file mode 100644 index 00000000..618e6daa --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/controller/web/UserController.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.controller.web; + +import com.espark.adarsh.annotations.WebMvcController; +import com.espark.adarsh.bean.UserCreateForm; +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import javax.validation.Valid; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@WebMvcController +public class UserController { + + private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); + + @Autowired(required = true) + private UserManager userManager; + + @RequestMapping("/users") + public ModelAndView getUsersPage() { + LOGGER.debug("Getting users page"); + return new ModelAndView("users", "users", userManager.getAllUser()); + } + + //@PreAuthorize("hasAuthority('ROLE_ADMIN')") + @RequestMapping(value = "/user/create", method = RequestMethod.GET) + public ModelAndView getUserCreatePage() { + LOGGER.debug("Getting user create form"); + return new ModelAndView("createUser", "form", new UserCreateForm()); + } + + //@PreAuthorize("hasAuthority('ROLE_ADMIN')") + @RequestMapping(value = "/user/create", method = RequestMethod.POST) + public String handleUserCreateForm(@Valid @ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) { + LOGGER.debug("Processing user create form={}, bindingResult={}", form, bindingResult); + if (bindingResult.hasErrors()) { + // failed validation + return "createUser"; + } + try { + final UserRole userRole=this.userManager.getUserRole(form.getRoleName()); + form.setRole(userRole); + this.userManager.saveUser(new User(form)); + } catch (DataIntegrityViolationException e) { + // probably email already exists - very rare case when multiple admins are adding same user + // at the same time and form validation has passed for more than one of them. + LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate email", e); + bindingResult.reject("email.exists", "Email already exists"); + return "createUser"; + } + // ok, redirect + return "redirect:/users"; + } + + +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/ApiServerAuthenticationEntryPoint.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/ApiServerAuthenticationEntryPoint.java new file mode 100644 index 00000000..2d22fa91 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/ApiServerAuthenticationEntryPoint.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * @see org.springframework.security.core.AuthenticationException + * @see org.springframework.security.web.AuthenticationEntryPoint + * + * This class provide a entry point for the all the incomming request to the api server + * other then which is configured for not to intercept from spring security + */ +public class ApiServerAuthenticationEntryPoint implements AuthenticationEntryPoint { + + private static Logger LOG = LoggerFactory.getLogger(ApiServerAuthenticationEntryPoint.class); + private static final String MESSAGE="MESSAGE"; + private static final String NOT_AUTHENTICATED_ACCESS_DENIED ="NOT-AUTHENTICATED-ACCESS-DENIED"; + + /** + * {@inheritDoc} + */ + @Override + public void commence(HttpServletRequest httpServletRequest + , HttpServletResponse httpServletResponse, AuthenticationException authException) + throws IOException, ServletException { + LOG.debug("Entering into Security Area "+ httpServletRequest.getRequestURI()+" "+ httpServletRequest.getQueryString()+" "+ httpServletRequest.getRequestURL()); + httpServletResponse.addHeader(MESSAGE, NOT_AUTHENTICATED_ACCESS_DENIED); + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/AuthenticationTokenProcessingFilter.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/AuthenticationTokenProcessingFilter.java new file mode 100644 index 00000000..0241f11b --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/AuthenticationTokenProcessingFilter.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + + +import com.espark.adarsh.persistence.entites.impl.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.web.filter.GenericFilterBean; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class AuthenticationTokenProcessingFilter extends GenericFilterBean { + + private static Logger LOG = LoggerFactory.getLogger(AuthenticationTokenProcessingFilter.class); + + @Autowired(required = true) + private TokenProvider tokenProvider; + + private TokenService tokenService; + + @Autowired(required = true) + private AuthenticationManager authenticationManager; + + private SecurityContextProvider securityContextProvider = new SecurityContextProvider(); + + private WebAuthenticationDetailsSource webAuthenticationDetailsSource = new WebAuthenticationDetailsSource(); + + public AuthenticationTokenProcessingFilter(AuthenticationManager authenticationManager,final TokenService tokenService) { + this.authenticationManager = authenticationManager; + this.tokenService=tokenService; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + LOG.debug("Checking headers and parameters for authentication token..."); + + String token = null; + + final HttpServletRequest httpServletRequest = this.asHttpServletRequest(request); + if (httpServletRequest.getHeader("Authentication-token") != null) { + token = httpServletRequest.getHeader("Authentication-token"); + LOG.debug("Found token '" + token + "' in request headers"); + } + + if (token != null) { + if(this.tokenService.contains(token)){ + final SecurityContext securityContext = this.securityContextProvider.getSecurityContext(); + securityContext.setAuthentication(this.tokenService.retrieve(token)); + }else if (tokenProvider.isTokenValid(token)) { + final User user = tokenProvider.getUserFromToken(token); + LOG.debug("Inside-AuthenticationTokenProcessingFilter.java"); + this.authenticateUser(httpServletRequest, user,token); + } + } + chain.doFilter(request, response); + } + + private HttpServletRequest asHttpServletRequest(ServletRequest servletRequest){ + return (HttpServletRequest)servletRequest; + } + + private HttpServletResponse asHttpServletResponse(ServletResponse servletResponse){ + return (HttpServletResponse)servletResponse; + } + + private void authenticateUser(HttpServletRequest request, User user,String token) { + final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getUserPwd()); + authenticationToken.setDetails(this.webAuthenticationDetailsSource.buildDetails(request)); + final SecurityContext securityContext = this.securityContextProvider.getSecurityContext(); + final Authentication authentication=this.authenticationManager.authenticate(authenticationToken); + securityContext.setAuthentication(authentication); + this.tokenService.store(token,authentication); + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/CustomUserDetailsService.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/CustomUserDetailsService.java new file mode 100644 index 00000000..8195b870 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/CustomUserDetailsService.java @@ -0,0 +1,63 @@ +package com.espark.adarsh.web.security; + + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.dao.DataAccessException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collection; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Service(value = "userDetailsService") +@Transactional(readOnly = true) +public class CustomUserDetailsService implements UserDetailsService { + + private static final Logger logger = LoggerFactory.getLogger("CustomUserDetailsService"); + + @Override + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { + logger.debug("DbUserDetailsService loadUserByUsername() "); + try { + User bean = new User(username); + bean = userManager.getUser(bean); + userManager.updateUser(bean); + Collection authorities = new ArrayList(bean.getUserRoles().size()); + for (UserRole role : bean.getUserRoles()) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + } + UserDetailsImpl details = new UserDetailsImpl(bean.getUserName(), bean.getUserPwd(), bean.getEnabled(), + true, true, true, authorities); + details.setUser(bean); + return details; + } catch (Exception e) { + logger.error("Unable to find record with username:=" + username, e); + } + return null; + } + + @Qualifier("userManagerImpl") + @Autowired + private UserManager userManager; + + public void setUserManager(UserManager userManager) { + this.userManager = userManager; + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAccessDeniedHandler.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAccessDeniedHandler.java new file mode 100644 index 00000000..f2a48a3f --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAccessDeniedHandler.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.access.AccessDeniedException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * @see org.springframework.security.access.AccessDeniedException + * @see org.springframework.security.web.access.AccessDeniedHandler + * + * This class provide the implementation for Access Denied Handler handle() + * is the callback method which will executed when any protected resource is + * access without sufficent privillage. + */ +public class RestAccessDeniedHandler implements + org.springframework.security.web.access.AccessDeniedHandler { + + private static final Logger LOG = LoggerFactory.getLogger(RestAccessDeniedHandler.class); + private static final String MESSAGE="ACCESS-DENIED-LACK-OF-PERMISSIONS"; + + /** + * {@inheritDoc} + */ + @Override + public void handle(HttpServletRequest request + , HttpServletResponse response, AccessDeniedException accessDeniedException) + throws IOException, ServletException { + LOG.error("RestAccessDeniedHandler ", accessDeniedException); + response.addHeader("MESSAGE", MESSAGE); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "ACCESS-DENIED"); + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestApiAuthProvider.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestApiAuthProvider.java new file mode 100644 index 00000000..6c60264d --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestApiAuthProvider.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.security; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class RestApiAuthProvider implements AuthenticationProvider{ + + private static final Logger LOG = LoggerFactory.getLogger(RestApiAuthProvider.class); + + @Qualifier("userManagerImpl") + @Autowired(required = true) + private UserManager userManager; + + + @Override + @Transactional(readOnly = true) + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + LOG.debug("RestApiAuthProvider retrieveUser() "); + final String username=authentication.getName(); + final String userPassword=authentication.getCredentials().toString(); + try { + User bean = new User(username); + bean = userManager.getUser(bean); + userManager.updateUser(bean); + Collection authorities = new ArrayList(bean.getUserRoles().size()); + for (UserRole role : bean.getUserRoles()) { + authorities.add(new SimpleGrantedAuthority(role.getName())); + } + return new UsernamePasswordAuthenticationToken(username, userPassword, + authorities); + + } catch (Exception e) { + LOG.error("Unable to find record with username:=" + username, e); + } + return null; + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } + +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAuthenticationFailureHandler.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAuthenticationFailureHandler.java new file mode 100644 index 00000000..c1170c24 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/RestAuthenticationFailureHandler.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * + * @see org.springframework.security.core.AuthenticationException + * @see org.springframework.security.web.authentication.AuthenticationFailureHandler + * + * This component provide the functionality for handling the authentication failure event. + * onAuthenticationFailure() is the callback method executed by framework whent authentication + * failure event is triggered. + */ +public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler { + + private static final Logger LOG = LoggerFactory.getLogger(RestAuthenticationFailureHandler.class); + private static final String MESSAGE="AUTHENTICATION-NOT-SUCCESS"; + /** + * {@inheritDoc} + */ + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest + , HttpServletResponse httpServletResponse, AuthenticationException authException) + throws IOException, ServletException { + LOG.error("On Authentication Failure Exception Occur",authException); + httpServletResponse.addHeader("MESSAGE",MESSAGE); + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Bad credentials"); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/SecurityContextProvider.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/SecurityContextProvider.java new file mode 100644 index 00000000..afac36da --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/SecurityContextProvider.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + + +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + * + * @see org.springframework.security.core.context.SecurityContext; + * @see org.springframework.security.core.context.SecurityContextHolder; + * + * This component provide the functionality for getting the spring security context + * + */ +public class SecurityContextProvider { + + /** + * getSecurityContext() provide the functionality of + * retrieving the current spring security instance. + * @return the current instance of the SecurityContext + */ + public SecurityContext getSecurityContext() { + return SecurityContextHolder.getContext(); + } + + /** + * getUserDetails() provide the UserDetails instance. + * @return + */ + public String getUserDetails(){ + return this.getSecurityContext().getAuthentication().getPrincipal().toString(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenProvider.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenProvider.java new file mode 100644 index 00000000..fee3dfeb --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenProvider.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.web.manager.UserManager; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Component +public class TokenProvider { + + @Qualifier(value = "userManagerImpl") + @Autowired(required = true) + private UserManager userManager; + + @Value("${token-secret-key}") + private String secretKey; + + + private MessageDigest md5er; + + + static String FENCE_POST = "!!!"; + private static final String NEWLINE = "\r\n"; + + + public TokenProvider() { + try { + md5er = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Cannot find MD5 algorithm",e); + } + } + + public String getToken(User user) { + return getToken(user, DateTime.now().plusDays(1).getMillis()); + } + + public String getToken(User user, long expirationDateInMillis) { + + StringBuilder tokenBuilder = new StringBuilder(); + + byte[] token = tokenBuilder + .append(user.getUserName()) + .append(FENCE_POST) + .append(expirationDateInMillis) + .append(FENCE_POST) + .append(new String(buildTokenKey(expirationDateInMillis, user))) + .toString().getBytes(); + + // the below function returns a string ending in "\r\n", which tends to cause problems...remove it + return Base64.encodeBase64String(token).replace(NEWLINE, ""); + } + + public boolean isTokenValid(String encodedToken) { + String[] components = decodeAndDissectToken(encodedToken); + + if (components == null || components.length != 3) { + return false; + } + String externalUser = components[0]; + Long externalDate = Long.parseLong(components[1]); + String externalKey = components[2]; + User user = userManager.getUserByName(new User(externalUser)); + String expectedKey = new String(buildTokenKey(externalDate, user)); + byte[] expectedKeyBytes = expectedKey.getBytes(); + byte[] externalKeyBytes = externalKey.getBytes(); + if (!MessageDigest.isEqual(expectedKeyBytes, externalKeyBytes)) { + return false; + } + + if (new DateTime(externalDate).isBeforeNow()) { + return false; + } + + return true; + } + + private byte[] buildTokenKey(long expirationDateInMillis, User user) { + Assert.notNull(secretKey, "Secret Key must not be null!"); + StringBuilder keyBuilder = new StringBuilder(); + String key = keyBuilder + .append(user.getUserName()) + .append(FENCE_POST) + .append(user.getUserPwd()) + .append(FENCE_POST) + .append(expirationDateInMillis) + .append(FENCE_POST) + .append(secretKey).toString(); + + byte[] keyBytes = key.getBytes(); + return md5er.digest(keyBytes); + } + + public User getUserFromToken(String token) { + if (!isTokenValid(token)) { return null; } + String[] components = decodeAndDissectToken(token); + if (components == null || components.length != 3) { return null; } + String username = components[0]; + return userManager.getUserByName(new User(username)); + } + + private String[] decodeAndDissectToken(String encodedToken) { + if(StringUtils.isBlank(encodedToken) || !Base64.isArrayByteBase64(encodedToken.getBytes())) { + return null; + } + // Apache Commons Base64 tools expect Base64 strings to end in "\r\n", add if necessary + if(!encodedToken.endsWith(NEWLINE)) { encodedToken = encodedToken + NEWLINE; } + String token = new String(Base64.decodeBase64(encodedToken)); + if(!token.contains(FENCE_POST) || token.split(FENCE_POST).length != 3) { + return null; + } + return token.split(FENCE_POST); + } + + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + public MessageDigest getMd5er() { + return md5er; + } + + public void setMd5er(MessageDigest md5er) { + this.md5er = md5er; + } + + +} + diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenService.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenService.java new file mode 100644 index 00000000..1d012be0 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/TokenService.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.security.core.Authentication; + +import java.util.UUID; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class TokenService { + + private static final Logger logger = LoggerFactory.getLogger(TokenService.class); + private static final Cache restApiAuthTokenCache = CacheManager.getInstance().getCache("restApiAuthTokenCache"); + public static final int HALF_AN_HOUR_IN_MILLISECONDS = 30 * 60 * 1000; + + @Scheduled(fixedRate = HALF_AN_HOUR_IN_MILLISECONDS) + public void evictExpiredTokens() { + logger.info("Evicting expired tokens"); + restApiAuthTokenCache.evictExpiredElements(); + } + + public String generateNewToken() { + return UUID.randomUUID().toString(); + } + + public void store(String token, Authentication authentication) { + restApiAuthTokenCache.put(new Element(token, authentication)); + } + + public boolean contains(String token) { + return restApiAuthTokenCache.get(token) != null; + } + + public Authentication retrieve(String token) { + return (Authentication) restApiAuthTokenCache.get(token).getObjectValue(); + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/UserDetailsImpl.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/UserDetailsImpl.java new file mode 100644 index 00000000..27cef834 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/security/UserDetailsImpl.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.web.security; + +import com.espark.adarsh.persistence.entites.impl.UserRole; +import org.springframework.context.annotation.Role; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class UserDetailsImpl extends User implements UserDetails { + + public UserDetailsImpl(String username, String password, Collection authorities) { + super(username, password, authorities); + } + + public UserDetailsImpl(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) { + super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); + } + + private com.espark.adarsh.persistence.entites.impl.User user; + + + public com.espark.adarsh.persistence.entites.impl.User getUser() { + return user; + } + + public void setUser(com.espark.adarsh.persistence.entites.impl.User user) { + this.user = user; + } + + public String getRole() { + return user.getUserRoles().iterator().next().getName(); + } + + + @Override + public String toString() { + return "UserDetailsImpl{" + + "user=" + user + + '}'; + } +} + diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/validator/UserCreateFormValidator.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/validator/UserCreateFormValidator.java new file mode 100644 index 00000000..a97b177b --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/com/espark/adarsh/web/validator/UserCreateFormValidator.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.validator; + +import com.espark.adarsh.bean.UserCreateForm; +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.web.manager.UserManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Component +public class UserCreateFormValidator implements Validator { + + private static final Logger LOGGER = LoggerFactory.getLogger(UserCreateFormValidator.class); + + @Autowired + private UserManager userManager; + + + @Override + public boolean supports(Class clazz) { + return clazz.equals(UserCreateForm.class); + } + + @Override + public void validate(Object target, Errors errors) { + LOGGER.debug("Validating {}", target); + UserCreateForm form = (UserCreateForm) target; + validatePasswords(errors, form); + validateEmail(errors, form); + } + + private void validatePasswords(Errors errors, UserCreateForm form) { + if (!form.getPassword().equals(form.getPasswordRepeated())) { + errors.reject("password.no_match", "Passwords do not match"); + } + } + + private void validateEmail(Errors errors, UserCreateForm form) { + if (userManager.getUserByName(new User(form.getUserName())) != null ) { + errors.reject("email.exists", "User with this email already exists"); + } + } +} diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/sql/database.sql b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/sql/database.sql new file mode 100644 index 00000000..39e4c5c1 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/java/sql/database.sql @@ -0,0 +1,77 @@ +drop schema if exists `espark`; +CREATE SCHEMA `espark` ; +drop user 'adarsh'@'localhost'; +FLUSH PRIVILEGES; +CREATE USER 'adarsh'@'localhost' IDENTIFIED BY 'adarsh'; +GRANT ALL PRIVILEGES ON *.* TO 'adarsh'@'localhost' WITH GRANT OPTION; + + +use espark; + +DROP TABLE IF EXISTS `user_role_mapping`; +DROP TABLE IF EXISTS `userrole`; +DROP TABLE IF EXISTS `user`; + + +CREATE TABLE `user` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `createdDate` datetime DEFAULT NULL, + `enabled` tinyint(1) NOT NULL, + `firstName` varchar(24) NOT NULL, + `lastName` varchar(24) DEFAULT NULL, + `modifiedDate` datetime DEFAULT NULL, + `userEmail` varchar(100) NOT NULL, + `userName` varchar(24) NOT NULL, + `userPhone` varchar(10) DEFAULT NULL, + `userPwd` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`), + UNIQUE KEY `userName` (`userName`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +CREATE TABLE `userrole` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +CREATE TABLE `user_role_mapping` ( + `User_id` bigint(20) NOT NULL, + `userRoles_id` bigint(20) NOT NULL, + PRIMARY KEY (`User_id`,`userRoles_id`), + KEY `FK5D9A9F9181C6E86` (`User_id`), + KEY `FK5D9A9F9995F6035` (`userRoles_id`), + CONSTRAINT `FK5D9A9F9995F6035` FOREIGN KEY (`userRoles_id`) REFERENCES `userrole` (`id`), + CONSTRAINT `FK5D9A9F9181C6E86` FOREIGN KEY (`User_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + + +INSERT INTO `USER` +(`id`,`createdDate`,`enabled`,`firstName`,`lastName`,`modifiedDate`,`userEmail`,`userName`,`userPhone`,`userPwd`) +VALUES(1,'2015-01-01',1,'adarsh','kumar','2015-01-01','adarsh@kumar','adarsh','8197416336','adarsh') + ,(2,'2015-01-01',1,'admin','kumar','2015-01-01','admin@kumar','admin','8197416336','admin') + ,(3,'2015-01-01',1,'user','kumar','2015-01-01','user@kumar','user','8197416336','user'); + +-- When Encryption is enabled +-- Encryption of Adarsh pwd $2a$10$mc7NY8ZlU/ASATaTaQRYfuxNAJDA5S3NSr0jMM1oSqCWSuURsMUuq +-- Encryption of Admin pwd $2a$10$i5jVLzELbFBsL35Ut9WICeMyHFDQnGOrcYs2Q80ornhubErrngwVW +-- Encryption of User pwd $2a$10$3L4krlIm76O6SaR4njs.GOfqDS5Yu.4QU9Uhbr6tjeJi0xXswMGjK +-- INSERT INTO `USER` +-- (`id`,`createdDate`,`enabled`,`firstName`,`lastName`,`modifiedDate`,`userEmail`,`userName`,`userPhone`,`userPwd`) +-- VALUES(1,'2015-01-01',1,'adarsh','kumar','2015-01-01','adarsh@kumar','adarsh','8197416336','$2a$10$mc7NY8ZlU/ASATaTaQRYfuxNAJDA5S3NSr0jMM1oSqCWSuURsMUuq') +-- ,(2,'2015-01-01',1,'admin','kumar','2015-01-01','admin@kumar','admin','8197416336','$2a$10$i5jVLzELbFBsL35Ut9WICeMyHFDQnGOrcYs2Q80ornhubErrngwVW') +-- ,(3,'2015-01-01',1,'user','kumar','2015-01-01','user@kumar','user','8197416336','$2a$10$3L4krlIm76O6SaR4njs.GOfqDS5Yu.4QU9Uhbr6tjeJi0xXswMGjK'); + + +INSERT INTO `USERROLE`(`ID`,`NAME`) +VALUES(1,'ROLE_SUPERADMIN') + ,(2,'ROLE_ADMIN') + ,(3,'ROLE_USER'); + +INSERT INTO `user_role_mapping`(`User_id`,`userRoles_id`) +VALUES((SELECT ID FROM USER WHERE USERNAME='adarsh'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_SUPERADMIN')) + ,((SELECT ID FROM USER WHERE USERNAME='admin'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_ADMIN')) + ,((SELECT ID FROM USER WHERE USERNAME='user'),(SELECT ID FROM USERROLE WHERE NAME ='ROLE_USER')); \ No newline at end of file diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/application.properties new file mode 100644 index 00000000..33f057f2 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/application.properties @@ -0,0 +1,50 @@ +# +# * @author Adarsh Kumar +# * @author $LastChangedBy: Adarsh Kumar$ +# * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ +# * @Espark @copyright all right reserve +# + + +# To set the context path for the web application +#server.contextPath=/espark +server.port = 9090 +spring.freemarker.checkTemplateLocation=true + +spring.freemarker.template-loader-path=/WEB-INF/ftl +spring.freemarker.expose-request-attributes=true +spring.freemarker.expose-spring-macro-helpers=true + + +#spring.mvc.view.prefix=/WEB-INF/jsp/ +#spring.mvc.view.suffix=.jsp + +application.message=welcome to the application + +#spring.application.index=index.html +# Database +db.driver=com.mysql.jdbc.Driver +db.url=jdbc:mysql://localhost:3306/espark +db.username=adarsh +db.password=adarsh + +# Hibernate +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate + +# Log levels severity mapping. +logging.file=application.log +logging.path=\\log +logging.level.org.hibernate= ALL +logging.level.org.springframework.security.web= ALL +logging.level.org.springframework.security.core= ALL +logging.level.com.espark.adarsh=ALL +logging.level.org.springframework.web=ALL +logging.level.org.springframework.boot=ALL +logging.level.org.springframework.jpa=ALL + +token-secret-key=secret + +#CREATE USER 'adarsh'@'localhost' IDENTIFIED BY 'adarsh'; +#GRANT ALL ON *.* TO 'adarsh'@'localhost'; diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/ehcache.xml b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/ehcache.xml new file mode 100644 index 00000000..2770294b --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/ehcache.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/css/bootstrap-theme.min.css diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootWebMvcProfileExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootWebMvcProfileExample/src/main/webapp/js/bootstrap.min.js rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/js/jquery.min.js similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/js/jquery.min.js rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/resources/static/js/jquery.min.js diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/createUser.ftl b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/createUser.ftl new file mode 100644 index 00000000..62154155 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/createUser.ftl @@ -0,0 +1,96 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="form" type="com.espark.adarsh.domain.UserCreateForm" --> +<#import "/spring.ftl" as spring> + + + + + + + + + + + + Create a new user + + + + +
+
+

USER REGISTRATION FORM

+
+
+ + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+ + +
+ + +
+ + + +
+<@spring.bind "form" /> +<#if spring.status.error> +
    + <#list spring.status.errorMessages as error> +
  • ${error}
  • + +
+ + + + \ No newline at end of file diff --git a/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/login.ftl b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/login.ftl similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/login.ftl rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/login.ftl diff --git a/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/users.ftl b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/users.ftl new file mode 100644 index 00000000..62e56fc2 --- /dev/null +++ b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/users.ftl @@ -0,0 +1,57 @@ +<#-- @ftlvariable name="users" type="java.util.List" --> + + + + + + + List of Users + + + + + + + + + +
+

User Information

+

user data for analysis

+
+ + + + + + + + + + <#list users as user> + + + + + + + + +
User First NameUser Last NameUser EmailRole
${user.firstName}${user.lastName}${user.userEmail} + <#list user.userRoles as role> + ${role.name}   + +
+ + + \ No newline at end of file diff --git a/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/welcome.ftl b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/welcome.ftl similarity index 100% rename from SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/welcome.ftl rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/main/webapp/WEB-INF/ftl/welcome.ftl diff --git a/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java diff --git a/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java diff --git a/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java b/APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java similarity index 100% rename from SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java rename to APPLICATIONS/SpringBootRestMvcSecurityExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java diff --git a/SpringBootSecurityDaoAuthenticationExample/doc/help.txt b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/doc/help.txt similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/doc/help.txt rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/doc/help.txt diff --git a/SpringBootSecurityDaoAuthenticationExample/pom.xml b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/pom.xml similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/pom.xml rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/pom.xml diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/bean/UserBean.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/bean/UserBean.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/bean/UserBean.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/bean/UserBean.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/mvc/WebMvcConfiguration.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/mvc/WebMvcConfiguration.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/mvc/WebMvcConfiguration.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/mvc/WebMvcConfiguration.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationService.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationService.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationService.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationService.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityInitializer.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityInitializer.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityInitializer.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/configuration/security/SecurityInitializer.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/controller/UserDetailController.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/controller/UserDetailController.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/controller/UserDetailController.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/controller/UserDetailController.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/driver/ApplicationMain.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepository.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepository.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepository.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/repository/UserRepositoryImpl.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailService.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailService.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailService.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailService.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailServiceImpl.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailServiceImpl.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailServiceImpl.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/java/com/espark/adarsh/service/UserDetailServiceImpl.java diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/jdbc.properties b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/jdbc.properties similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/jdbc.properties rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/jdbc.properties diff --git a/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/log4j.xml new file mode 100644 index 00000000..defb8601 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/log4j.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.css b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.css similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.css rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.css diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.css b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.css similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.css rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.css diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.min.css b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.min.css similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.min.css rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/css/font-awesome.min.css diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/FontAwesome.otf b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/FontAwesome.otf similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/FontAwesome.otf rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/FontAwesome.otf diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.eot diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.svg diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.ttf diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/fonts/fontawesome-webfont.woff diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/bordered-pulled.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/bordered-pulled.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/bordered-pulled.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/bordered-pulled.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/core.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/core.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/core.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/core.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/fixed-width.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/fixed-width.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/fixed-width.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/fixed-width.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/font-awesome.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/font-awesome.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/font-awesome.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/font-awesome.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/icons.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/icons.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/icons.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/icons.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/larger.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/larger.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/larger.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/larger.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/list.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/list.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/list.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/list.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/mixins.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/mixins.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/mixins.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/mixins.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/path.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/path.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/path.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/path.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/rotated-flipped.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/rotated-flipped.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/rotated-flipped.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/rotated-flipped.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/spinning.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/spinning.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/spinning.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/spinning.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/stacked.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/stacked.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/stacked.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/stacked.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/variables.less b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/variables.less similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/variables.less rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/less/variables.less diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_bordered-pulled.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_bordered-pulled.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_bordered-pulled.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_bordered-pulled.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_core.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_core.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_core.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_core.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_fixed-width.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_fixed-width.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_fixed-width.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_fixed-width.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_icons.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_icons.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_icons.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_icons.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_larger.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_larger.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_larger.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_larger.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_list.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_list.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_list.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_list.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_mixins.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_mixins.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_mixins.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_mixins.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_path.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_path.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_path.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_path.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_rotated-flipped.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_rotated-flipped.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_rotated-flipped.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_rotated-flipped.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_spinning.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_spinning.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_spinning.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_spinning.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_stacked.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_stacked.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_stacked.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_stacked.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_variables.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_variables.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_variables.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/_variables.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/font-awesome.scss b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/font-awesome.scss similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/font-awesome.scss rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/font/scss/font-awesome.scss diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.js b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.js similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.js rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.js diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.min.js similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.min.js rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/bootstrap.min.js diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/jquery-1.10.2.min.js b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/jquery-1.10.2.min.js similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/jquery-1.10.2.min.js rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/static/js/jquery-1.10.2.min.js diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkHome.html b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkHome.html similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkHome.html rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkHome.html diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkLoginPage.html b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkLoginPage.html similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkLoginPage.html rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkLoginPage.html diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserDetailPage.html b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserDetailPage.html similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserDetailPage.html rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserDetailPage.html diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserPage.html b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserPage.html similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserPage.html rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/resources/templates/esparkUserPage.html diff --git a/SpringBootSecurityDaoAuthenticationExample/src/main/sql/script.sql b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/sql/script.sql similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/main/sql/script.sql rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/main/sql/script.sql diff --git a/SpringBootSecurityDaoAuthenticationExample/src/test/java/com/espark/adarsh/test/TestCredential.java b/APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/test/java/com/espark/adarsh/test/TestCredential.java similarity index 100% rename from SpringBootSecurityDaoAuthenticationExample/src/test/java/com/espark/adarsh/test/TestCredential.java rename to APPLICATIONS/SpringBootSecurityDaoAuthenticationExample/src/test/java/com/espark/adarsh/test/TestCredential.java diff --git a/SpringBootSecurityHibernateExample/docs/help.txt b/APPLICATIONS/SpringBootSecurityHibernateExample/docs/help.txt similarity index 100% rename from SpringBootSecurityHibernateExample/docs/help.txt rename to APPLICATIONS/SpringBootSecurityHibernateExample/docs/help.txt diff --git a/SpringBootSecurityHibernateExample/pom.xml b/APPLICATIONS/SpringBootSecurityHibernateExample/pom.xml similarity index 100% rename from SpringBootSecurityHibernateExample/pom.xml rename to APPLICATIONS/SpringBootSecurityHibernateExample/pom.xml diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/Application.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/CustomUserDetailsService.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/CustomUserDetailsService.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/CustomUserDetailsService.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/CustomUserDetailsService.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java diff --git a/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java new file mode 100644 index 00000000..f6881cc1 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface Repository { +} diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/controller/LoginController.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/controller/LoginController.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/controller/LoginController.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/controller/LoginController.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java diff --git a/SpringBootSecurityHibernateExample/src/main/java/sql/database.sql b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/sql/database.sql similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/java/sql/database.sql rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/java/sql/database.sql diff --git a/SpringBootSecurityHibernateExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/resources/application.properties similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/resources/application.properties diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkLoginPage.jsp b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkLoginPage.jsp similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkLoginPage.jsp rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkLoginPage.jsp diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkUserPage.jsp b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkUserPage.jsp similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkUserPage.jsp rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/esparkUserPage.jsp diff --git a/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/login.jsp b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/login.jsp new file mode 100644 index 00000000..1f8a48fa --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/login.jsp @@ -0,0 +1,32 @@ + + + + + Log in + + + + +

Log in

+ +
+ + + +
+ + +
+
+ + +
+
+ + +
+ +
+ + + \ No newline at end of file diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/welcome.jsp b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/welcome.jsp similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/welcome.jsp rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/WEB-INF/jsp/welcome.jsp diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.css b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.css similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.css rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.css diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.min.css similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/bootstrap.min.css diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/css/espark.css b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/espark.css similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/css/espark.css rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/css/espark.css diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.css b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.css similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.css rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.css diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.min.css b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.min.css similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.min.css rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/css/font-awesome.min.css diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/FontAwesome.otf b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/FontAwesome.otf similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/FontAwesome.otf rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/FontAwesome.otf diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.eot b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.eot similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.eot rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.eot diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.svg b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.svg similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.svg rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.svg diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.ttf b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.ttf similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.ttf rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.ttf diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.woff b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.woff similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.woff rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/fonts/fontawesome-webfont.woff diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/bordered-pulled.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/bordered-pulled.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/bordered-pulled.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/bordered-pulled.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/core.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/core.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/core.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/core.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/fixed-width.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/fixed-width.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/fixed-width.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/fixed-width.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/font-awesome.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/font-awesome.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/font-awesome.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/font-awesome.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/icons.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/icons.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/icons.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/icons.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/larger.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/larger.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/larger.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/larger.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/list.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/list.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/list.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/list.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/mixins.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/mixins.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/mixins.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/mixins.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/path.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/path.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/path.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/path.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/rotated-flipped.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/rotated-flipped.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/rotated-flipped.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/rotated-flipped.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/spinning.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/spinning.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/spinning.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/spinning.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/stacked.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/stacked.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/stacked.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/stacked.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/less/variables.less b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/variables.less similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/less/variables.less rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/less/variables.less diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_bordered-pulled.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_bordered-pulled.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_bordered-pulled.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_bordered-pulled.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_core.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_core.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_core.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_core.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_fixed-width.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_fixed-width.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_fixed-width.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_fixed-width.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_icons.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_icons.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_icons.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_icons.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_larger.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_larger.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_larger.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_larger.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_list.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_list.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_list.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_list.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_mixins.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_mixins.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_mixins.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_mixins.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_path.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_path.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_path.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_path.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_rotated-flipped.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_rotated-flipped.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_rotated-flipped.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_rotated-flipped.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_spinning.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_spinning.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_spinning.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_spinning.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_stacked.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_stacked.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_stacked.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_stacked.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_variables.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_variables.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_variables.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/_variables.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/font-awesome.scss b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/font-awesome.scss similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/font/scss/font-awesome.scss rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/font/scss/font-awesome.scss diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.js b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.js similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.js rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.js diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.min.js similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.min.js rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/bootstrap.min.js diff --git a/SpringBootSecurityHibernateExample/src/main/webapp/js/jquery-1.10.2.min.js b/APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/jquery-1.10.2.min.js similarity index 100% rename from SpringBootSecurityHibernateExample/src/main/webapp/js/jquery-1.10.2.min.js rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/main/webapp/js/jquery-1.10.2.min.js diff --git a/SpringBootSecurityHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java b/APPLICATIONS/SpringBootSecurityHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java similarity index 100% rename from SpringBootSecurityHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java rename to APPLICATIONS/SpringBootSecurityHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java diff --git a/SpringBootSecurityHsSqlDbExample/.gitignore b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/.gitignore similarity index 100% rename from SpringBootSecurityHsSqlDbExample/.gitignore rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/.gitignore diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/README.md b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/README.md new file mode 100644 index 00000000..56b4be3d --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/README.md @@ -0,0 +1,24 @@ +Example Spring Boot Security +============================ + +The application showing how to use Spring Boot with Spring Security for common needs, such as: + +* Customized login form +* DAO-based authentication +* Basic "remember me" authentication +* URL-based security +* Method-level security + +Requirements +------------ +* [Java Platform (JDK) 8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) +* [Apache Maven 3.x](http://maven.apache.org/) + +Quick start +----------- +1. `mvn spring-boot:run` +3. Point your browser to [http://localhost:8080/](http://localhost:8080/) + + + +https://www.future-processing.pl/blog/exploring-spring-boot-and-spring-security-custom-token-based-authentication-of-rest-services-with-spring-security-and-pinch-of-spring-java-configuration-and-spring-integration-testing/ \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/pom.xml b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/pom.xml similarity index 100% rename from SpringBootSecurityHsSqlDbExample/pom.xml rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/pom.xml diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/TestClass.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/TestClass.java new file mode 100644 index 00000000..c38dcfa9 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/TestClass.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +/** + * Created by adarkuma on 3/18/2016. + */ +public class TestClass { + + /* public static void main(String[] args) { + + System.out.println(new BCryptPasswordEncoder().encode("adarsh.radha@espark.com")); + System.out.println(new BCryptPasswordEncoder().encode("adarsh@radha")); + }*/ +} diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UserController.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UserController.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UserController.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UserController.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/Role.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/Role.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/Role.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/Role.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/User.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/User.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/User.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/User.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java diff --git a/SpringBootSecurityHsSqlDbExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/resources/application.properties similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/resources/application.properties diff --git a/SpringBootSecurityHsSqlDbExample/src/main/resources/data.sql b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/resources/data.sql similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/resources/data.sql rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/resources/data.sql diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/home.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/home.ftl new file mode 100644 index 00000000..fc9b5db8 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/home.ftl @@ -0,0 +1,31 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="currentUser" type="com.espark.adarsh.domain.CurrentUser" --> + + + + + Home page + + + + + \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/login.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/login.ftl new file mode 100644 index 00000000..f6d49eef --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/login.ftl @@ -0,0 +1,61 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="error" type="java.util.Optional" --> + + + + + + + Login Page + + + + + + Log in + + + + +

Log in

+ +

You can use: adarsh.radha@espark.com / adarsh@radha

+ +
+
+
+
+ + +
+ + +
+
+ + +
+ +
+ + +
+
+ + +<#if error.isPresent()> +

The email or password you have entered is invalid, try again.

+ + + \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user.ftl new file mode 100644 index 00000000..edb285b9 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user.ftl @@ -0,0 +1,21 @@ +<#-- @ftlvariable name="user" type="com.espark.adarsh.domain.User" --> + + + + + User details + + + + +

User details

+ +

E-mail: ${user.email}

+ +

Role: ${user.role}

+ + \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl new file mode 100644 index 00000000..f5e10a61 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl @@ -0,0 +1,61 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="form" type="com.espark.adarsh.domain.UserCreateForm" --> +<#import "/spring.ftl" as spring> + + + + + + + + + Create a new user + + + + +

Create a new user

+
+
+
+ + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+
+<@spring.bind "form" /> +<#if spring.status.error> +
    + <#list spring.status.errorMessages as error> +
  • ${error}
  • + +
+ + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/users.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/users.ftl new file mode 100644 index 00000000..3cf2567f --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/users.ftl @@ -0,0 +1,35 @@ +<#-- @ftlvariable name="users" type="java.util.List" --> + + + + + List of Users + + + + +

List of Users

+ + + + + + + + + + <#list users as user> + + + + + + +
E-mailRole
${user.email}${user.role}
+ + \ No newline at end of file diff --git a/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap-theme.min.css diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap.min.css b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap.min.css similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap.min.css rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/css/bootstrap.min.css diff --git a/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/bootstrap.min.js new file mode 100644 index 00000000..e79c0651 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/jquery.min.js b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/jquery.min.js similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/jquery.min.js rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/main/webapp/js/jquery.min.js diff --git a/SpringBootSecurityHsSqlDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java b/APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java similarity index 100% rename from SpringBootSecurityHsSqlDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java rename to APPLICATIONS/SpringBootSecurityHsSqlDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java diff --git a/SpringBootSecurityMongoDbExample/pom.xml b/APPLICATIONS/SpringBootSecurityMongoDbExample/pom.xml similarity index 100% rename from SpringBootSecurityMongoDbExample/pom.xml rename to APPLICATIONS/SpringBootSecurityMongoDbExample/pom.xml diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/BootApplicationMain.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/configuration/SpringSecurityConfiguration.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/CurrentUserControllerAdvice.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/HomeController.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/LoginController.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UserController.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UserController.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UserController.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UserController.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/controller/UsersController.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/CurrentUser.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/Role.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/Role.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/Role.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/Role.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/User.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/User.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/User.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/User.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/UserCreateForm.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/domain/validator/UserCreateFormValidator.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/handlers/ExceptionHandlerControllerAdvice.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/repository/UserRepository.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserDetailsService.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserService.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/currentuser/CurrentUserServiceImpl.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserService.java diff --git a/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/java/com/espark/adarsh/service/user/UserServiceImpl.java diff --git a/SpringBootSecurityMongoDbExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/resources/application.properties similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/resources/application.properties diff --git a/SpringBootSecurityMongoDbExample/src/main/resources/data.sql b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/resources/data.sql similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/resources/data.sql rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/resources/data.sql diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/home.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/home.ftl new file mode 100644 index 00000000..fc9b5db8 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/home.ftl @@ -0,0 +1,31 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="currentUser" type="com.espark.adarsh.domain.CurrentUser" --> + + + + + Home page + + + + + \ No newline at end of file diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/homePage.ftl diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/login.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/login.ftl new file mode 100644 index 00000000..f6d49eef --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/login.ftl @@ -0,0 +1,61 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="error" type="java.util.Optional" --> + + + + + + + Login Page + + + + + + Log in + + + + +

Log in

+ +

You can use: adarsh.radha@espark.com / adarsh@radha

+ +
+
+
+
+ + +
+ + +
+
+ + +
+ +
+ + +
+
+ + +<#if error.isPresent()> +

The email or password you have entered is invalid, try again.

+ + + \ No newline at end of file diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/loginPage.ftl diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user.ftl new file mode 100644 index 00000000..edb285b9 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user.ftl @@ -0,0 +1,21 @@ +<#-- @ftlvariable name="user" type="com.espark.adarsh.domain.User" --> + + + + + User details + + + + +

User details

+ +

E-mail: ${user.email}

+ +

Role: ${user.role}

+ + \ No newline at end of file diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userCreationPage.ftl diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/userDetailPage.ftl diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl new file mode 100644 index 00000000..f5e10a61 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/user_create.ftl @@ -0,0 +1,61 @@ +<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" --> +<#-- @ftlvariable name="form" type="com.espark.adarsh.domain.UserCreateForm" --> +<#import "/spring.ftl" as spring> + + + + + + + + + Create a new user + + + + +

Create a new user

+
+
+
+ + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+
+<@spring.bind "form" /> +<#if spring.status.error> +
    + <#list spring.status.errorMessages as error> +
  • ${error}
  • + +
+ + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/users.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/users.ftl new file mode 100644 index 00000000..3cf2567f --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/users.ftl @@ -0,0 +1,35 @@ +<#-- @ftlvariable name="users" type="java.util.List" --> + + + + + List of Users + + + + +

List of Users

+ + + + + + + + + + <#list users as user> + + + + + + +
E-mailRole
${user.email}${user.role}
+ + \ No newline at end of file diff --git a/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl similarity index 100% rename from SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/WEB-INF/ftl/usersPage.ftl diff --git a/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap-theme.min.css diff --git a/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap.min.css similarity index 100% rename from SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/css/bootstrap.min.css diff --git a/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/js/bootstrap.min.js new file mode 100644 index 00000000..e79c0651 --- /dev/null +++ b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/SpringBootWebMvcJspExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/js/jquery.min.js similarity index 100% rename from SpringBootWebMvcJspExample/src/main/webapp/js/jquery.min.js rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/main/webapp/js/jquery.min.js diff --git a/SpringBootSecurityMongoDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java b/APPLICATIONS/SpringBootSecurityMongoDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java similarity index 100% rename from SpringBootSecurityMongoDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java rename to APPLICATIONS/SpringBootSecurityMongoDbExample/src/test/java/com/espark/adarsh/test/PasswordGenerator.java diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/pom.xml b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/pom.xml new file mode 100644 index 00000000..65ed77a7 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + + SpringBootSocialFbAndGitLoginExample + SpringBootSocialFbAndGitLoginExample + 1.0-SNAPSHOT + jar + + SpringBootSocialFbAndGitLoginExample + Demo project for Spring Boot Social Logging + https://github.com/adarshkumarsingh83 + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + + org.springframework.boot + spring-boot-starter-parent + 1.4.0.RELEASE + + + + + SpringBootSocialFbAndGitLoginExample + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.security.oauth + spring-security-oauth2 + + + org.webjars + angularjs + 1.4.3 + + + org.webjars + jquery + 2.1.1 + + + org.webjars + bootstrap + 3.2.0 + + + org.webjars + webjars-locator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4971d6c5 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; + + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@SpringBootApplication +@ComponentScan("com.espark.adarsh") +@PropertySource({"classpath:properties/application.properties"}) +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java new file mode 100644 index 00000000..70db0066 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; +import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.web.filter.CompositeFilter; + +import javax.servlet.Filter; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Configuration +@EnableOAuth2Client +@EnableAuthorizationServer +@Order(6) +public class ApplicationConfiguration extends WebSecurityConfigurerAdapter { + + @Autowired + OAuth2ClientContext oauth2ClientContext; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**").authorizeRequests() + .antMatchers("/", "/login**", "/webjars/**", "/js/application.js") + .permitAll().anyRequest() + .authenticated().and().exceptionHandling() + .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout() + .logoutSuccessUrl("/").permitAll().and().csrf() + .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and() + .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class); + } + + @Configuration + @EnableResourceServer + protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/me").authorizeRequests().anyRequest().authenticated(); + } + } + + @Bean + public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(filter); + registration.setOrder(-100); + return registration; + } + + @Bean + @ConfigurationProperties("github") + public ClientResources github() { + return new ClientResources(); + } + + @Bean + @ConfigurationProperties("facebook") + public ClientResources facebook() { + return new ClientResources(); + } + + private Filter ssoFilter() { + CompositeFilter filter = new CompositeFilter(); + List filters = new ArrayList(); + filters.add(this.ssoFilter(facebook(), "/login/facebook")); + filters.add(this.ssoFilter(github(), "/login/github")); + filter.setFilters(filters); + return filter; + } + + private Filter ssoFilter(ClientResources client, String path) { + OAuth2ClientAuthenticationProcessingFilter filter + = new OAuth2ClientAuthenticationProcessingFilter(path); + OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext); + filter.setRestTemplate(template); + filter.setTokenServices(new UserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId())); + return filter; + } + +} + diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ClientResources.java b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ClientResources.java new file mode 100644 index 00000000..fa18b6ca --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/configuration/ClientResources.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.configuration; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Configuration +public class ClientResources { + + @NestedConfigurationProperty + private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails(); + + @NestedConfigurationProperty + private ResourceServerProperties resource = new ResourceServerProperties(); + + public AuthorizationCodeResourceDetails getClient() { + return client; + } + + public ResourceServerProperties getResource() { + return resource; + } +} diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/controller/EsparkController.java b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/controller/EsparkController.java new file mode 100644 index 00000000..399a522d --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/java/com/espark/adarsh/controller/EsparkController.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.controller; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.security.Principal; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@RestController +public class EsparkController { + + @Value("${application.welcome.msg}") + private String message; + + @RequestMapping({"/user", "/me"}) + public Map user(final Principal principal) { + return new LinkedHashMap() { + { + put("name", principal.getName()); + put("message", message); + } + }; + } + +} diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/properties/application.properties b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/properties/application.properties new file mode 100644 index 00000000..4b96ae47 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/properties/application.properties @@ -0,0 +1,24 @@ +security.oauth2.client.client-id = acme +security.oauth2.client.client-secret = acmesecret +security.oauth2.client.scope = read,write +security.oauth2.client.auto-approve-scopes = .* +facebook.client.clientId = 233668646673605 +facebook.client.clientSecret = 33b17e044ee6a4fa383f46ec6e28ea1d +facebook.client.accessTokenUri = https://graph.facebook.com/oauth/access_token +facebook.client.userAuthorizationUri = https://www.facebook.com/dialog/oauth +facebook.client.tokenName = oauth_token +facebook.client.authenticationScheme = query +facebook.client.clientAuthenticationScheme = form +facebook.resource.userInfoUri = https://graph.facebook.com/me + +github.client.clientId = bd1c0a783ccdd1c9b9e4 +github.client.clientSecret = 1a9030fbca47a5b2c28e92f19050bb77824b5ad1 +github.client.accessTokenUri = https://github.com/login/oauth/access_token +github.client.userAuthorizationUri = https://github.com/login/oauth/authorize +github.client.clientAuthenticationScheme = form +github.resource.userInfoUri = https://api.github.com/user + +application.welcome.msg=WELCOME TO THE ESPARK + +logging.level.org.springframework.security = ALL +logging.level.org.springframework.context = ALL diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/index.html b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/index.html new file mode 100644 index 00000000..b799e7c3 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/index.html @@ -0,0 +1,78 @@ + + + + + + + Demo + + + + + + + + + + +
+

LOGIN

+ +
+ +
+

WELCOME TO ESPARK FB & GIT LOGIN

+
+ +
+ +
+ +
+
+
+ + +
+ +
+
+
+ + +
+ +
+
+
+ +
+
+
+ + +
+
+

Message :

+ +

Logged in as:

+
+
+ +
+
+
+ +
+ + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/js/application.js b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/js/application.js new file mode 100644 index 00000000..9372bcb1 --- /dev/null +++ b/APPLICATIONS/SpringBootSocialFbAndGitLoginExample/src/main/resources/static/js/application.js @@ -0,0 +1,37 @@ +/* + +* @author Adarsh Kumar +* @author $LastChangedBy: Adarsh Kumar$ +* @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ +* @Espark @copyright all right reserve +*/ +angular + .module("app", []) + .config( + function($httpProvider) { + $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; + }).controller("home", function($http, $location) { + var indexPage = this; + $http.get("/user").success(function(data) { + if (data.name) { + indexPage.user = data.name; + indexPage.message = data.message; + indexPage.authenticated = true; + } else { + indexPage.user = "N/A"; + indexPage.authenticated = false; + } + }).error(function() { + indexPage.user = "N/A"; + indexPage.authenticated = false; + }); + indexPage.logout = function() { + $http.post('logout', {}).success(function() { + indexPage.authenticated = false; + $location.path("/"); + }).error(function(data) { + console.log("Logout failed") + indexPage.authenticated = false; + }); + }; + }); \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSolr/doc/help.txt b/APPLICATIONS/SpringBootSolr/doc/help.txt new file mode 100644 index 00000000..dfeb8975 --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/doc/help.txt @@ -0,0 +1,9 @@ +$ brew install solr +$ brew services start solr +$ brew services stop solr +url => http://localhost:8983/solr +$ sudo chown -R `whoami` /usr/local/Cellar/solr/ +$ solr create -c customer +$ curl http://localhost:8983/solr/customer/config -d '{"set-user-property": {"update.autoCreateFields":"false"}}' + +$ brew uninstall solr \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSolr/pom.xml b/APPLICATIONS/SpringBootSolr/pom.xml new file mode 100644 index 00000000..8be84dc6 --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.javasampleapproach.solr + SpringBootSolr + 0.0.1 + jar + + SpringBootSolr + SpringBootSolr + + + org.springframework.boot + spring-boot-starter-parent + 1.5.6.RELEASE + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-solr + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-autoconfigure + 1.5.6.RELEASE + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/SpringBootSolrApplication.java b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/SpringBootSolrApplication.java new file mode 100644 index 00000000..73ed1bd4 --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/SpringBootSolrApplication.java @@ -0,0 +1,53 @@ +package com.javasampleapproach.solr; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.javasampleapproach.solr.model.Customer; +import com.javasampleapproach.solr.repo.CustomerRepository; + +@SpringBootApplication +public class SpringBootSolrApplication implements CommandLineRunner { + + @Autowired + private CustomerRepository customerRepository; + + @Override + public void run(String... args) throws Exception { + + customerRepository.deleteAll(); + + // Store customers + customerRepository.save(Arrays.asList(new Customer("1", "Jack", 20), + new Customer("2", "Adam", 24), + new Customer("3", "Kim", 27), + new Customer("4", "David", 30), + new Customer("5", "Peter", 21))); + + // Fetch all customers + System.out.println("--------------------------------"); + System.out.println("Select all Customers:"); + System.out.println("--------------------------------"); + + for (Customer product : this.customerRepository.findAll()) { + System.out.println(product); + } + + // Find customer by Name ends with 'm' + System.out.println("--------------------------------"); + System.out.println("Find Customers that have names EndsWith m:"); + System.out.println("--------------------------------"); + + for (Customer customer : this.customerRepository.findByNameEndsWith("m")) { + System.out.println(customer); + } + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(SpringBootSolrApplication.class, args); + } +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/model/Customer.java b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/model/Customer.java new file mode 100644 index 00000000..51b091ba --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/model/Customer.java @@ -0,0 +1,61 @@ +package com.javasampleapproach.solr.model; + +import org.apache.solr.client.solrj.beans.Field; +import org.springframework.data.annotation.Id; +import org.springframework.data.solr.core.mapping.Indexed; +import org.springframework.data.solr.core.mapping.SolrDocument; + +@SolrDocument(solrCoreName = "customer") +public class Customer { + + @Id + @Field + @Indexed(name = "id", type = "string") + private String id; + + @Field + @Indexed(name = "name", type = "string") + private String name; + + @Field + @Indexed(name = "age", type = "int") + private Integer age; + + public Customer() { + } + + public Customer(String id, String name, Integer age){ + this.id = id; + this.name = name; + this.age = age; + } + + public void setId(String id){ + this.id = id; + } + + public String getId(){ + return this.id; + } + + public void setName(String name){ + this.name = name; + } + + public String getName(){ + return this.name; + } + + public void setAge(Integer age){ + this.age = age; + } + + public Integer getAge(){ + return this.age; + } + + @Override + public String toString() { + return "Customer [id=" + this.id + ", name=" + this.name + ", age=" + this.age + "]"; + } +} diff --git a/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/repo/CustomerRepository.java b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/repo/CustomerRepository.java new file mode 100644 index 00000000..2f809958 --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/src/main/java/com/javasampleapproach/solr/repo/CustomerRepository.java @@ -0,0 +1,11 @@ +package com.javasampleapproach.solr.repo; + +import java.util.List; + +import org.springframework.data.solr.repository.SolrCrudRepository; + +import com.javasampleapproach.solr.model.Customer; + +public interface CustomerRepository extends SolrCrudRepository { + List findByNameEndsWith(String name); +} diff --git a/APPLICATIONS/SpringBootSolr/src/main/resources/application.properties b/APPLICATIONS/SpringBootSolr/src/main/resources/application.properties new file mode 100644 index 00000000..12fba20f --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.data.solr.host=http://localhost:8983/solr \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSolr/src/test/java/com/javasampleapproach/solr/SpringBootSolrApplicationTests.java b/APPLICATIONS/SpringBootSolr/src/test/java/com/javasampleapproach/solr/SpringBootSolrApplicationTests.java new file mode 100644 index 00000000..16bb7223 --- /dev/null +++ b/APPLICATIONS/SpringBootSolr/src/test/java/com/javasampleapproach/solr/SpringBootSolrApplicationTests.java @@ -0,0 +1,16 @@ +package com.javasampleapproach.solr; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootSolrApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/doc/help.txt b/APPLICATIONS/SpringBootSwaggerExample/doc/help.txt new file mode 100644 index 00000000..07cedd35 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/doc/help.txt @@ -0,0 +1,46 @@ +To compile +--------------------------- +>mvn clean package + +To Execute the Application +--------------------------- +>mvn spring-boot:run + +http://localhost:8080/swagger-ui.html + + +To get the output +------------------------- +url http://localhost:8080/application/welcome +url http://localhost:8080/user/list +url http://localhost:8080/employee/list + + +To exit from Execution +-------------------------- +ctrl-c + + +=========================================================================== +To Create Executable Jar +------------------------------------ +In Pom.xml file + + + + org.springframework.boot + spring-boot-maven-plugin + + + + +> mvn package + +To Check the content of jar file +>jar tvf target/SpringBootSwaggerExample.jar + +To execute the jar file +>java -jar target/SpringBootSwaggerExample.jar + +or create a jar and execute a file +>mvn package && java -jar target/SpringBootSwaggerExample.jar diff --git a/APPLICATIONS/SpringBootSwaggerExample/pom.xml b/APPLICATIONS/SpringBootSwaggerExample/pom.xml new file mode 100644 index 00000000..62d7792b --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + SpringBootSwaggerExample + SpringBootSwaggerExample + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.3.1.RELEASE + + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + maven2-repository.java.net + Java.net Repository for Maven + http://download.java.net/maven/2/ + + + + JBoss repository + http://repository.jboss.org/nexus/content/groups/public/ + + + + java.net + https://maven.java.net/content/repositories/public/ + + + + + + SpringBootSwaggerExample + UTF-8 + 1.7 + 1.3.1.RELEASE + 2.4.0 + 4.11 + 1.6.1 + 1.2.17 + + + + + + org.springframework.boot + spring-boot-starter-web + ${sping.boot.version} + + + + org.springframework.boot + spring-boot-starter-test + 1.2.6.RELEASE + + + + junit + junit + ${junit.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + + io.springfox + springfox-swagger-ui + ${springfox.version} + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..f612b2ec --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh; + + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@EnableSwagger2 +@EnableAutoConfiguration +@PropertySource("classpath:application.properties") +@ComponentScan("com.espark.adarsh") +public class ApplicationMain { + + @Value("${base.url}") + private String baseUrl; + + public static void main(String[] args) throws Exception { + SpringApplication.run(ApplicationMain.class, args); + } + + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).pathMapping(baseUrl) + .select() + .apis(RequestHandlerSelectors.basePackage("com.espark.adarsh")) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + ApiInfo apiInfo = new ApiInfo( + "Espark Innovation Labs Rest Api", + "Espark Rest Swagger Apis UI.", + "Espark 1.0", + "http://esparkinnovationlabs.com", + "adarsh.espark@innovationlabs.com", + "Espark Innovation Lab License", + "http://esparkinnovationlab/icense"); + return apiInfo; + } +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..489e7610 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.bean; + +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public class Employee implements Serializable{ + + private String empId; + private String empName; + private String empEmail; + + public Employee() { + } + + public Employee(String empId, String empName, String empEmail) { + this.empId = empId; + this.empName = empName; + this.empEmail = empEmail; + } + + @ApiModelProperty(position = 1, required = true, value = "Emp Id containing only Number") + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + @ApiModelProperty(position = 2, required = true, value = "Emp Name containing only Character") + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + @ApiModelProperty(position = 3, required = true, value = "Emp Email containing only Character") + public String getEmpEmail() { + return empEmail; + } + + public void setEmpEmail(String empEmail) { + this.empEmail = empEmail; + } +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java new file mode 100644 index 00000000..4925f540 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.bean; + +import io.swagger.annotations.ApiModel; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@ApiModel(description = "Rest Api Response Bean ") +public class EsparkResponseBean { + + T data; + + public EsparkResponseBean() { + } + + public EsparkResponseBean(T data) { + this.data = data; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java new file mode 100644 index 00000000..1074855e --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/EmployeeController.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.bean.EsparkResponseBean; +import com.espark.adarsh.service.EmployeeService; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.websocket.server.PathParam; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@RestController +@RequestMapping("/employee") +@Api(value = "EmployeeController", description = "Employee Operations") +public class EmployeeController { + + + @Autowired(required = true) + private EmployeeService employeeService; + + @ApiOperation(value = "Employee", nickname = "employee", notes = "Return the List of the Employee") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Successful Response Send"), + @ApiResponse(code = 404, message = "Employees not found") + , @ApiResponse(code = 500, message = "Server Error")}) + @RequestMapping(value = "/list" + , produces = {"application/json"} + , method = RequestMethod.GET) + public + @ResponseBody + EsparkResponseBean> getEmployeeList() { + return new EsparkResponseBean(employeeService.getEmployeeList()); + } + + + @ApiOperation(value = "Employee", nickname = "employee", notes = "Return the the Employee based on EmpId") + @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Employee not found") + , @ApiResponse(code = 500, message = "Server Error")}) + @RequestMapping(value = "/id/{empId}" + , produces = {"application/json"} + , method = RequestMethod.GET) + public + @ResponseBody + EsparkResponseBean getEmployee(@ApiParam(value = "ID of employee", required = true) @PathVariable("empId") String empId) { + + if (empId != null && !empId.isEmpty()) { + final Employee employee = this.employeeService.getEmployee(empId); + return new EsparkResponseBean(employee); + } + return new EsparkResponseBean(); + } + + @ApiOperation(value = "Employee", nickname = "employee", notes = "Delete the Employee") + @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Employee not found") + , @ApiResponse(code = 500, message = "Server Error")}) + @RequestMapping(value = "/delete/{empId}" + , produces = {"application/json"} + , method = RequestMethod.DELETE) + public + @ResponseBody + EsparkResponseBean deleteEmployee(@ApiParam(value = "ID of employee", required = true) @PathVariable("empId") String empId) { + + if (empId != null && !empId.isEmpty()) { + final Employee employee = this.employeeService.deleteEmployee(empId); + return new EsparkResponseBean(employee); + } + return new EsparkResponseBean(); + } + + @ApiOperation(value = "Employee", nickname = "employee", notes = "Create the Employee") + @ApiResponses(value = {@ApiResponse(code = 400, message = "Employee Exist") + , @ApiResponse(code = 404, message = "Employee Exist") + , @ApiResponse(code = 500, message = "Server Error") + , @ApiResponse(code = 200, message = "Employee Created", responseContainer = "EsparkResponseBean")}) + @RequestMapping(value = "/create" + , produces = {"application/json"} + , method = RequestMethod.POST) + public + @ResponseBody + EsparkResponseBean createEmployee(@RequestBody Employee employee) { + if (employee != null) { + if (this.employeeService.createEmployee(employee)) { + return new EsparkResponseBean(employee); + } + } + return new EsparkResponseBean(); + } + + @ApiOperation(value = "Employee", nickname = "employee", notes = "Update the Employee") + @ApiResponses(value = {@ApiResponse(code = 400, message = "Employee Not Exist") + , @ApiResponse(code = 404, message = "Employee not Exist") + , @ApiResponse(code = 500, message = "Server Error") + , @ApiResponse(code = 200, message = "Employee Updated", responseContainer = "EsparkResponseBean")}) + @RequestMapping(value = "/update" + , produces = {"application/json"} + , method = RequestMethod.PUT) + public + @ResponseBody + EsparkResponseBean updateEmployee(@ApiParam(name = "empId", value = "String to the application", required = true) @RequestParam("empId") String empId + , @ApiParam(name = "empName", value = "String to the application", required = true) @RequestParam("empName") String empName + , @ApiParam(name = "empEmail", value = "String to the application", required = true) @RequestParam("empEmail") String empEmail) { + if (empId != null && empName != null && empEmail != null) { + final Employee employee = new Employee(empId, empName, empEmail); + if (this.employeeService.updateEmployee(employee)) { + return new EsparkResponseBean(employee); + } + } + return new EsparkResponseBean(); + } + +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/SpringBootController.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/SpringBootController.java new file mode 100644 index 00000000..b9a678e3 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/SpringBootController.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.controller; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; +import org.springframework.context.annotation.PropertySource; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@RestController +@RequestMapping("/application") +public class SpringBootController { + + @Value("${message}") + private String message; + + @RequestMapping(value = "/welcome" + , produces = {"application/json"} + , method = RequestMethod.GET) + public + @ResponseBody + Map welcomeMessage() { + return new HashMap() { + { + put("name", System.getProperty("user.name")); + put("message", message); + } + }; + } + +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/UserController.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/UserController.java new file mode 100644 index 00000000..4fbdf2b3 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/controller/UserController.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.EsparkResponseBean; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@RestController +@RequestMapping("/user") +@Api(value = "UserController", description = "User Operations") +public class UserController { + + @ApiOperation(value = "User", nickname = "user") + @RequestMapping(value = "/list" + , produces = {"application/json"} + , method = RequestMethod.GET) + public + @ResponseBody + EsparkResponseBean> getUserList() { + return new EsparkResponseBean(new ArrayList() { + { + add("{'name':'adarsh','email':'adarsh@kumar'}"); + add("{'name':'amit','email':'amit@kumar'}"); + add("{'name':'radha','email':'radha@singh'}"); + add("{'name':'sonu','email':'sonu@singh'}"); + } + }); + } +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..57817070 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface EmployeeService { + + public List employeeList = new ArrayList() { + { + add(new Employee("1", "adarsh kumar", "adarsh@kumar")); + add(new Employee("2", "amit kumar", "amit@kumar")); + add(new Employee("3", "radha singh", "radha@singh")); + } + }; + + public List getEmployeeList(); + + public Employee getEmployee(String empId); + + public Boolean createEmployee(Employee employee); + + public Boolean updateEmployee(Employee employee); + + public Employee deleteEmployee(String empId); +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java new file mode 100644 index 00000000..3b004bb5 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import org.springframework.stereotype.Service; + +import java.util.Iterator; +import java.util.List; +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Override + public List getEmployeeList() { + return employeeList; + } + + @Override + public Employee getEmployee(String empId) { + for (Employee employee : employeeList) { + if (employee.getEmpId().equals(empId)) { + return employee; + } + } + return null; + } + + @Override + public Boolean createEmployee(Employee newEmployee) { + boolean flag = false; + for (Employee employee : employeeList) { + flag = employee.getEmpId().equals(newEmployee.getEmpId()); + } + if (!flag) { + employeeList.add(newEmployee); + return true; + } + return false; + } + + @Override + public Boolean updateEmployee(Employee newEmployee) { + + for (Employee employee : employeeList) { + if (employee.getEmpId().equals(newEmployee.getEmpId())) { + employee.setEmpEmail(newEmployee.getEmpEmail()); + employee.setEmpName(newEmployee.getEmpName()); + return true; + } + + } + return false; + } + + @Override + public Employee deleteEmployee(String empId) { + final Iterator employeeIterator=employeeList.listIterator(); + while(employeeIterator.hasNext()){ + Employee employee=employeeIterator.next(); + if(employee.getEmpId().equals(empId)){ + employeeIterator.remove(); + return employee; + } + } + return null; + } +} diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/application.properties new file mode 100644 index 00000000..79c92d15 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=8080 +message=Welcome To Spring Boot + +base.url= \ No newline at end of file diff --git a/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/log4j.xml new file mode 100644 index 00000000..defb8601 --- /dev/null +++ b/APPLICATIONS/SpringBootSwaggerExample/src/main/resources/log4j.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootTokenAuthenticatoinHibernateExample/pom.xml b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/pom.xml similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/pom.xml rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/pom.xml diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/docs/help.txt b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/docs/help.txt similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/docs/help.txt rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/docs/help.txt diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/Application.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/Application.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/Application.java diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java new file mode 100644 index 00000000..f48045a8 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ApiServerViewBean.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.bean; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonView; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@JsonPropertyOrder({"userName", "userPassword","token","message","httpStatus"}) +public class ApiServerViewBean implements Serializable { + + + @JsonProperty("User-Name") + private String userName; + + + @JsonProperty("User-Password") + private String userPassword; + + + @JsonProperty("Authentication-token") + private String token; + + + @JsonProperty("Response-Message") + private String message; + + + @JsonProperty("Response-Status") + private Integer httpStatus; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserPassword() { + return userPassword; + } + + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Integer getHttpStatus() { + return httpStatus; + } + + public void setHttpStatus(Integer httpStatus) { + this.httpStatus = httpStatus; + } +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/bean/ResponseBean.java diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java new file mode 100644 index 00000000..afeae55c --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/persistence/PersistenceConfigurations.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.configuration.persistence; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Configuration +@EnableTransactionManagement +@PropertySource("classpath:/application.properties") +public class PersistenceConfigurations { + + @Value("${db.driver}") + private String DB_DRIVER; + + @Value("${db.password}") + private String DB_PASSWORD; + + @Value("${db.url}") + private String DB_URL; + + @Value("${db.username}") + private String DB_USERNAME; + + @Value("${hibernate.dialect}") + private String HIBERNATE_DIALECT; + + @Value("${hibernate.show_sql}") + private String HIBERNATE_SHOW_SQL; + + @Value("${hibernate.hbm2ddl.auto}") + private String HIBERNATE_HBM2DDL_AUTO; + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(DB_DRIVER); + dataSource.setUrl(DB_URL); + dataSource.setUsername(DB_USERNAME); + dataSource.setPassword(DB_PASSWORD); + return dataSource; + } + + @Bean + public LocalSessionFactoryBean sessionFactory() { + LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); + sessionFactoryBean.setDataSource(dataSource()); + sessionFactoryBean.setPackagesToScan("com.espark.adarsh"); + Properties hibernateProperties = new Properties(); + hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT); + hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL); + hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO); + sessionFactoryBean.setHibernateProperties(hibernateProperties); + + return sessionFactoryBean; + } + + @Bean + public HibernateTransactionManager transactionManager() { + HibernateTransactionManager transactionManager = + new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/ApiServerAuthenticationEntryPoint.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/ApiServerAuthenticationEntryPoint.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/ApiServerAuthenticationEntryPoint.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/ApiServerAuthenticationEntryPoint.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationTokenProcessingFilter.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationTokenProcessingFilter.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationTokenProcessingFilter.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/AuthenticationTokenProcessingFilter.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAccessDeniedHandler.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAccessDeniedHandler.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAccessDeniedHandler.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAccessDeniedHandler.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestApiAuthProvider.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestApiAuthProvider.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestApiAuthProvider.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestApiAuthProvider.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAuthenticationFailureHandler.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAuthenticationFailureHandler.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAuthenticationFailureHandler.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/RestAuthenticationFailureHandler.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityConfiguration.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityContextProvider.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityContextProvider.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityContextProvider.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/SecurityContextProvider.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenProvider.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenProvider.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenProvider.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenProvider.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenService.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenService.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenService.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/TokenService.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/configuration/security/UserDetailsImpl.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/handler/ApiExceptionHandler.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/handler/ApiExceptionHandler.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/handler/ApiExceptionHandler.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/handler/ApiExceptionHandler.java diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java new file mode 100644 index 00000000..70bbdf8d --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/AbstractEntity.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.persistence.entites.construct; + +import javax.persistence.*; +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@MappedSuperclass +public abstract class AbstractEntity + implements Entity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(insertable = true, nullable = false, unique = true, updatable = true) + private E id; + + protected AbstractEntity(Class entity) { + final Class entityObject = entity; + System.out.println(entity.getCanonicalName()); + } + + @Override + public E getId() { + return id; + } + + public void setId(E id) { + this.id = id; + } + + @PrePersist + protected void prePersist() { + } + + @PreUpdate + protected void preUpdate() { + } + + @PreRemove + protected void preRemove() { + } + + @Override + public int compareTo(Object o) { + + if (o instanceof javax.persistence.Entity) { + Entity entity = (Entity) o; + return 0; + } + return 1; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java new file mode 100644 index 00000000..7966edb5 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/construct/Entity.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.espark.adarsh.persistence.entites.construct; + +import java.io.Serializable; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface Entity extends Serializable,Cloneable,Comparable{ + + public E getId(); + + public void setId(E id); + +} \ No newline at end of file diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/User.java diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java new file mode 100644 index 00000000..bc7c950d --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/entites/impl/UserRole.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.entites.impl; + +import com.espark.adarsh.persistence.entites.construct.AbstractEntity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Entity +@Table(name = "UserRole") +public final class UserRole extends AbstractEntity { + + @Column(nullable = false, length = 100) + private String name; + + public UserRole() { + super(UserRole.class); + } + + public UserRole(String name) { + super(UserRole.class); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "UserRole{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java new file mode 100644 index 00000000..71c373b8 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/RoleRepository.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; + +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface RoleRepository { + + public Long size(); + public void refreshUser(UserRole userRole); + public UserRole getRoleByName(String roleName); + public Boolean saveUserRole(UserRole userRole); + public Boolean updateUserRole(UserRole userRole); + public Boolean dropUserRole(UserRole userRole); + public UserRole getUserRole(User user); + public List getAllUserRole(User user); +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java new file mode 100644 index 00000000..deeb95e4 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/UserRepository.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories; + +import com.espark.adarsh.persistence.entites.impl.User; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface UserRepository { + + + public Long size(); + + public void refreshUser(User user); + + public Boolean saveUser(User user); + + public User getUser(User user); + + public User getUserById(User user); + + public User getUserByName(User user); + + public Boolean deleteUser(User user); + + public User updateUser(User user); + + public Collection getAllUser(); + +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java new file mode 100644 index 00000000..96418806 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/AbstractRepository.java @@ -0,0 +1,373 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + +import com.espark.adarsh.persistence.entites.construct.Entity; +import org.hibernate.*; +import org.hibernate.criterion.Example; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Assert; + +import javax.persistence.Table; +import java.util.Collection; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public abstract class AbstractRepository + implements EntityRepository { + + protected final Class entityClass; + protected final String entityClassName; + protected final String entityTableName; + + + public AbstractRepository(final Class entityClass) { + this.entityClass = entityClass; + this.entityClassName = this.entityClass.getSimpleName(); + this.entityTableName = this.entityClass.getAnnotation(Table.class).name(); + } + + @Override + public Entity getEntity(Entity entity) { + return (Entity) getSession().load(entityClass, entity.getId()); + } + + @Override + public Entity getEntityByName(Entity entity) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq("userName", entity)); + return (Entity) criteria.uniqueResult(); + } + + @Override + public Entity getEntityById(Entity entity) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq("id", entity.getId())); + return (Entity) criteria.uniqueResult(); + } + + @Override + public List getAll() { + return getSession().createCriteria(entityClass).list(); + } + + + public List getAll(int limit) { + return getSession().createCriteria(entityClass).list().subList(0, limit); + } + + @Override + public List getAll(final Integer firstResult, final Integer maxResults) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.setFirstResult(firstResult); + criteria.setMaxResults(maxResults); + final List list = criteria.list(); + return list; + } + + @Override + public Long size() { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.setProjection(Projections.rowCount()).uniqueResult(); + return (Long) criteria.uniqueResult(); + } + + @Override + public void remove(final R entity) { + try { + getSession().delete(entity); + } catch (final Exception e) { + System.out.println("Unable to delete entity : " + this.entityClassName + ", :" + entity + e.getMessage()); + } + } + + + @Override + public Entity getByColumnName(String columnName, Object columnValue) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq(columnName, columnValue)); + return (Entity) criteria.uniqueResult(); + } + + @Override + public Collection getByEntities(String columnName, Object columnValue) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Restrictions.eq(columnName, columnValue)); + return (List) criteria.list(); + } + + @Override + public void clear() { + getSession().createQuery("DELETE FROM " + entityClassName).executeUpdate(); + } + + @Override + public void refresh(R entity) { + getSession().refresh(entity); + } + + + @Override + public List getByExample(final R example) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Example.create(example)); + final List list = criteria.list(); + return list; + } + + @Override + public R getUniqueByExample(final R example) { + final Criteria criteria = getSession().createCriteria(entityClass); + criteria.add(Example.create(example)); + R result = (R) criteria.uniqueResult(); + return result; + } + + + @Override + public void insert(R record) { + getSession().save(record); + } + + @Override + public void insertAll(final Collection items) { + for (final R record : items) { + getSession().save(record); + } + } + + @Override + public void put(final R record) { + getSession().saveOrUpdate(record); + } + + @Override + public void put(final Collection records) { + Session session = getSession(); + for (R record : records) { + session.saveOrUpdate(record); + } + } + + @Override + public void update(final R record) throws HibernateException { + getSession().update(record); + } + + @Override + public void updateAll(final Collection items) { + for (final R record : items) { + getSession().update(record); + } + } + + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByNamedQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return findByNamedQuery(queryOrQueryName, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByNamedQuery(final String queryOrQueryName, final int firstResult, final int maxResults, final Object... parameters) + throws IllegalArgumentException { + return executeQuery(queryOrQueryName, true, false, false, firstResult, maxResults, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return findByQuery(queryOrQueryName, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final List findByQuery(final String queryOrQueryName, final int firstResult, final int maxResults, final Object... parameters) throws IllegalArgumentException { + return executeQuery(queryOrQueryName, false, false, false, firstResult, maxResults, parameters); + } + + /** + * @param query the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final Integer executeQuery(final String query, final Object... parameters) throws IllegalArgumentException { + return executeQuery(query, false, false, true, 0, 0, parameters); + } + + /** + * @param queryOrQueryName the HQL query, or the named query ID. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final Integer executeNamedQuery(final String queryOrQueryName, final Object... parameters) throws IllegalArgumentException { + return executeQuery(queryOrQueryName, true, false, true, 0, 0, parameters); + } + + /** + * Master execute query method. this does not support named parameter queries at this movement. + * + * @param result type of the query we are expecting. + * @param queryOrQueryName the HQL query, or the named query ID. + * @param namedQuery true if its a named query. + * @param singleResult true if we are expecting a single result. + * @param isExecuteUpdate true if we are executing a update statement. + * @param firstResult a non "0" number for the first result for any kinda of pagination. + * @param maxResults the maximum results we want to see per page. if this is "0" all results are returned. + * @param parameters is a Object[] array identified by parameterPosition. + * @return a list or an object based on the sql. + * @throws IllegalArgumentException is thrown if the queryOrQueryName or firstResult is invalid. + */ + protected final REZ_TYPE executeQuery(final String queryOrQueryName, final boolean namedQuery, final boolean singleResult, final boolean isExecuteUpdate, + final int firstResult, final int maxResults, final Object... parameters) throws IllegalArgumentException { + + Assert.hasLength(queryOrQueryName, "Query for executing cannot be null"); + Assert.isTrue(firstResult > -1, "First result cannot be less than zero"); + + try { + Session session = getSession(); + Object result = null; + + Query query; + if (namedQuery) { + query = session.getNamedQuery(queryOrQueryName); + } else { + query = session.createQuery(queryOrQueryName); + } + if (parameters != null) { + for (int i = 0; i < parameters.length; i++) { + query.setParameter(i, parameters[i]); + } + } + if (firstResult >= 0) { + query.setFirstResult(firstResult); + } + if (maxResults >= 0) { + query.setMaxResults(maxResults); + } + if (singleResult) { + result = query.uniqueResult(); + } else if (!isExecuteUpdate) { + result = query.list(); + } else { + result = new Integer(query.executeUpdate()); + } + if (result != null && !isExecuteUpdate) { + if (singleResult) { + onFindForObject((R) result); + } else { + onFindForList((List) result); + } + } + return (REZ_TYPE) result; + } catch (final Exception e) { + System.out.println("Unable to execute query :" + queryOrQueryName + ", namedQuery:" + namedQuery + ", singleResult" + singleResult + ", firstResult" + firstResult + + ", maxResults" + maxResults + ",parameters" + parameters + " " + e); + } + return null; + } + + + protected R onFindForObject(final R record) { + return record; + // can be overridden. + } + + + protected List onFindForList(final List records) { + for (final R record : records) { + onFindForObject(record); + } + // can be overridden. + return records; + } + + + protected final Class getEntityClass() { + return entityClass; + } + + /** + * @return the entityClassName + */ + protected final String getEntityClassName() { + return entityClassName; + } + + /** + * @return the entityTableName + */ + protected final String getEntityTableName() { + return entityTableName; + } + + protected SessionFactory sessionFactory; + + @Autowired + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + protected Session getSession() { + return sessionFactory.getCurrentSession(); + } + +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java new file mode 100644 index 00000000..d92d17cc --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/EntityRepository.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + +import com.espark.adarsh.persistence.entites.construct.Entity; +import org.springframework.dao.DuplicateKeyException; + +import java.util.Collection; +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@org.springframework.stereotype.Repository +public interface EntityRepository { + + /* public R get(R entity);*/ + + public List getAll(); + + public List getAll(int limit); + + public List getAll(Integer firstResult, Integer maxResults); + + public List getByExample(final R example); + + public R getUniqueByExample(final R example); + + public void put(final R record) throws DuplicateKeyException; + + public void put(final Collection records); + + public Entity getEntity(Entity entity); + + public Entity getEntityById(Entity entity); + + public Entity getEntityByName(Entity entity); + + public void insert(final R record); + + public void insertAll(final Collection items); + + public void update(final R record); + + public void updateAll(final Collection items); + + public void remove(final R entity); + + public Entity getByColumnName(String columnName, Object columnValue); + + public Collection getByEntities(String columnName, Object columnValue); + + public void clear(); + + public void refresh(final R entity); + + public Long size(); +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java new file mode 100644 index 00000000..f6881cc1 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/construct/Repository.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.construct; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface Repository { +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java new file mode 100644 index 00000000..24bffc4f --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/RoleRepositoryImpl.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.impl; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; +import com.espark.adarsh.persistence.repositories.RoleRepository; +import com.espark.adarsh.persistence.repositories.construct.AbstractRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Repository +public class RoleRepositoryImpl extends AbstractRepository + implements RoleRepository { + + public RoleRepositoryImpl() { + super(UserRole.class); + } + + @Override + @Transactional + public Long size() { + return super.size(); + } + + @Override + public void refreshUser(UserRole userRole) { + super.refresh(userRole); + } + + @Override + @Transactional + public Boolean saveUserRole(UserRole userRole) { + super.put(userRole); + return null; + } + + @Override + @Transactional + public UserRole getRoleByName(String roleName) { + UserRole userRole=new UserRole(); + userRole.setName(roleName); + return (UserRole) super.getUniqueByExample(userRole); + } + + @Override + @Transactional + public Boolean updateUserRole(UserRole userRole) { + super.update(userRole); + return null; + } + + @Override + @Transactional + public Boolean dropUserRole(UserRole userRole) { + super.remove(userRole); + return null; + } + + @Override + @Transactional + public UserRole getUserRole(User user) { + UserRole UserUserRole = new UserRole(); + UserUserRole.setId(1L); + UserUserRole.setName("User"); + return null; + } + + @Override + public List getAllUserRole(User user) { + return super.getAll(); + } +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java new file mode 100644 index 00000000..a0f933c9 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/persistence/repositories/impl/UserRepositoryImpl.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.persistence.repositories.impl; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.repositories.UserRepository; +import com.espark.adarsh.persistence.repositories.construct.AbstractRepository; +import org.hibernate.Criteria; +import org.hibernate.criterion.Restrictions; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Repository +public class UserRepositoryImpl extends AbstractRepository + implements UserRepository { + + public UserRepositoryImpl() { + super(User.class); + } + + @Override + @Transactional + public Boolean saveUser(User user) { + super.put(user); + return null; + } + + @Override + @Transactional + public User getUser(User user) { + return getUniqueByExample(user); + } + + @Override + @Transactional + public User getUserById(User user) { + return (User) super.getEntityById(user); + } + + @Override + @Transactional + public User getUserByName(User user) { + return (User) super.getByColumnName("userName",user.getUserName()); + } + + @Override + @Transactional + public Boolean deleteUser(User user) { + super.remove(user); + return null; + } + + @Override + @Transactional + public User updateUser(User user) { + super.update(user); + return null; + } + + + @Override + @Transactional + public Collection getAllUser() { + return getAll(); + } + + + @Transactional + public User getFacebookUser(String facebookUserEmailId){ + Criteria criteria=getSession().createCriteria(User.class); + criteria.add(Restrictions.eq("userEmail",facebookUserEmailId)) ; + Object object=criteria.uniqueResult(); + if(object!=null){ + return (User)object; + } + return (User)object; + } + + @Override + @Transactional + public Long size() { + return super.size(); + } + + @Override + public void refreshUser(User user) { + super.refresh(user); + } +} \ No newline at end of file diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/ApplicationController.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/ApplicationController.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/ApplicationController.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/ApplicationController.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationService.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationService.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationService.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationService.java diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationServiceImpl.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationServiceImpl.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationServiceImpl.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/controller/RestAuthenticationServiceImpl.java diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java new file mode 100644 index 00000000..25b69c3f --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManager.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.manager; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +public interface UserManager { + public void refreshUser(User user); + public Boolean saveUser(User user); + public Boolean updateUser(User user); + public Boolean deleteUser(User user); + public User getUser(User user); + public User getUserById(User user); + public User getUserByName(User user); + public Collection getAllUser(); + public UserRole getUserRole(String roleName); +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java new file mode 100644 index 00000000..0559e79c --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/com/espark/adarsh/web/manager/UserManagerImpl.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Espark nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.espark.adarsh.web.manager; + +import com.espark.adarsh.persistence.entites.impl.User; +import com.espark.adarsh.persistence.entites.impl.UserRole; +import com.espark.adarsh.persistence.repositories.RoleRepository; +import com.espark.adarsh.persistence.repositories.UserRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ +@Service +final public class UserManagerImpl + implements UserManager { + + private final static Logger logger = LoggerFactory.getLogger(UserManagerImpl.class); + + public UserManagerImpl() { + } + + @Override + public void refreshUser(User user) { + userRepository.refreshUser(user); + } + + @Transactional + public Boolean saveUser(User user) { + userRepository.saveUser(user); + return null; + } + + @Transactional + public Boolean updateUser(User user) { + userRepository.updateUser(user); + return null; + } + + @Transactional + public Boolean deleteUser(User user) { + userRepository.deleteUser(user); + return null; + } + + public User getUser(final User user) { + return userRepository.getUser(user); + } + + @Override + public Collection getAllUser() { + return userRepository.getAllUser(); + } + + @Override + public User getUserById(User user) { + return userRepository.getUserById(user); + } + + @Override + public User getUserByName(User user) { + return userRepository.getUserByName(user); + } + + @Override + public UserRole getUserRole(String roleName) { + return roleRepository.getRoleByName(roleName); + } + + @Qualifier("userRepositoryImpl") + @Autowired + private UserRepository userRepository; + + public void setUserRepository(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Qualifier("roleRepositoryImpl") + @Autowired + private RoleRepository roleRepository; + + public void setRoleRepository(RoleRepository roleRepository) { + this.roleRepository = roleRepository; + } +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/sql/database.sql b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/sql/database.sql similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/java/sql/database.sql rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/java/sql/database.sql diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/application.properties similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/application.properties diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/ehcache.xml b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/ehcache.xml new file mode 100644 index 00000000..2770294b --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/ehcache.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/SpringBootWebMvcProfileExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap-theme.min.css similarity index 100% rename from SpringBootWebMvcProfileExample/src/main/webapp/css/bootstrap-theme.min.css rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap-theme.min.css diff --git a/SpringBootWebMvcProfileExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap.min.css similarity index 100% rename from SpringBootWebMvcProfileExample/src/main/webapp/css/bootstrap.min.css rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/css/bootstrap.min.css diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/index.html b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/index.html similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/index.html rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/index.html diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/bootstrap.min.js b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/bootstrap.min.js new file mode 100644 index 00000000..e79c0651 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/SpringBootWebMvcProfileExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/jquery.min.js similarity index 100% rename from SpringBootWebMvcProfileExample/src/main/webapp/js/jquery.min.js rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/main/resources/static/js/jquery.min.js diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java new file mode 100644 index 00000000..8099bb71 --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/AbstractWebServicesTest.java @@ -0,0 +1,106 @@ +package com.espark.adarsh.test; + +import com.espark.adarsh.Application; +import com.espark.adarsh.bean.ApiServerViewBean; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.IntegrationTest; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.MediaType; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.web.context.WebApplicationContext; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = {Application.class}) +@WebAppConfiguration +@IntegrationTest("server.port:0") +public class AbstractWebServicesTest { + + protected static final Logger LOG = LoggerFactory.getLogger(AbstractWebServicesTest.class); + + private static final String X_AUTH_USERNAME = "username"; + private static final String X_AUTH_PASSWORD = "password"; + private static final String X_AUTH_TOKEN = "Authentication-token"; + + @Value("${local.server.port}") + int port; + protected MockMvc mockMvc; + protected static final String USERNAME = "adarsh"; + protected static final String PASSWORD = "adarsh"; + + @Autowired(required = true) + protected WebApplicationContext wac; + + @Autowired(required = true) + protected FilterChainProxy springSecurityFilterChain; + + @Before + public void setup() throws JsonProcessingException { + this.mockMvc = webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build(); + } + + + protected static String getJsonString(Object object) throws IOException { + final ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(object); + } + + protected static ApiServerViewBean jsonToObject(String jsonString) throws IOException { + final ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.readValue(jsonString, new TypeReference() { }); + } + + protected boolean compareJson(String actualJsonString, String filePath) throws JsonProcessingException, IOException{ + + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualTree = mapper.readTree(actualJsonString); + + Resource expectedJsonFileResource = new ClassPathResource(filePath); + JsonNode expectedTree = mapper.readTree(expectedJsonFileResource.getFile()); + return actualTree.equals(expectedTree); + } + + protected String generateTokenWithAuthenticatedUser() throws Exception { + final String url="/rest/authenticate/login"; + return this.generateTokenWithAuthenticatedUser(url,USERNAME,PASSWORD); + } + + protected String generateTokenWithAuthenticatedUser(final String url,final String USERNAME,final String PASSWORD) throws Exception { + final Map map = new HashMap(); + map.put("username", USERNAME); + map.put("password", PASSWORD); + final ResultActions authResultActions = this.mockMvc.perform(post( + url).content(getJsonString(map)) + .contentType(MediaType.APPLICATION_JSON)); + final String jsonString=authResultActions.andReturn().getResponse().getContentAsString(); + LOG.debug("controller returns : {}", jsonString); + final ApiServerViewBean apiServerViewBean = jsonToObject(jsonString); + return apiServerViewBean.getToken().trim(); + } + + +} diff --git a/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java new file mode 100644 index 00000000..bedeffce --- /dev/null +++ b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/PasswordEncoderTest.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.test; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +/** + * Created by Adarsh on 2/2/16. + */ +public class PasswordEncoderTest { + public static void main(String[] args) { + System.out.println("Encryption of Adarsh pwd "+new BCryptPasswordEncoder().encode("adarsh")); + System.out.println("Encryption of Admin pwd "+new BCryptPasswordEncoder().encode("admin")); + System.out.println("Encryption of User pwd "+new BCryptPasswordEncoder().encode("user")); + } +} diff --git a/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java b/APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java similarity index 100% rename from SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java rename to APPLICATIONS/SpringBootTokenAuthenticatoinHibernateExample/src/test/java/com/espark/adarsh/test/TestWebRestServices.java diff --git a/SpringBootTomcatSSLServerExample/pom.xml b/APPLICATIONS/SpringBootTomcatSSLServerExample/pom.xml similarity index 100% rename from SpringBootTomcatSSLServerExample/pom.xml rename to APPLICATIONS/SpringBootTomcatSSLServerExample/pom.xml diff --git a/SpringBootTomcatSSLServerExample/src/main/help/help.txt b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/help/help.txt similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/help/help.txt rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/help/help.txt diff --git a/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java diff --git a/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java diff --git a/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishService.java diff --git a/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java diff --git a/SpringBootTomcatSSLServerExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/application.properties similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/application.properties diff --git a/SpringBootTomcatSSLServerExample/src/main/resources/espark.key b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/espark.key similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/resources/espark.key rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/espark.key diff --git a/SpringBootTomcatSSLServerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/log4j.xml similarity index 100% rename from SpringBootTomcatSSLServerExample/src/main/resources/log4j.xml rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/main/resources/log4j.xml diff --git a/SpringBootTomcatSSLServerExample/src/test/java/com/espark/adarsh/test/TomcatSSLApplicationTests.java b/APPLICATIONS/SpringBootTomcatSSLServerExample/src/test/java/com/espark/adarsh/test/TomcatSSLApplicationTests.java similarity index 100% rename from SpringBootTomcatSSLServerExample/src/test/java/com/espark/adarsh/test/TomcatSSLApplicationTests.java rename to APPLICATIONS/SpringBootTomcatSSLServerExample/src/test/java/com/espark/adarsh/test/TomcatSSLApplicationTests.java diff --git a/SpringBootTomcatServerExample/pom.xml b/APPLICATIONS/SpringBootTomcatServerExample/pom.xml similarity index 100% rename from SpringBootTomcatServerExample/pom.xml rename to APPLICATIONS/SpringBootTomcatServerExample/pom.xml diff --git a/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java b/APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java similarity index 100% rename from SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/TomcatApplicationDriver.java diff --git a/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java similarity index 100% rename from SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/controller/ApplicationController.java diff --git a/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java b/APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java similarity index 100% rename from SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/listner/ServletContextListenerImpl.java diff --git a/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishService.java similarity index 100% rename from SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishService.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishService.java diff --git a/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java b/APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java similarity index 100% rename from SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/java/com/espark/adarsh/service/WishServiceImpl.java diff --git a/SpringBootTomcatServerExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootTomcatServerExample/src/main/resources/application.properties similarity index 100% rename from SpringBootTomcatServerExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootTomcatServerExample/src/main/resources/application.properties diff --git a/APPLICATIONS/SpringBootTomcatServerExample/src/main/resources/log4j.xml b/APPLICATIONS/SpringBootTomcatServerExample/src/main/resources/log4j.xml new file mode 100644 index 00000000..defb8601 --- /dev/null +++ b/APPLICATIONS/SpringBootTomcatServerExample/src/main/resources/log4j.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/NonAutoConfigurationTomcatApplicationDriverTests.java b/APPLICATIONS/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/NonAutoConfigurationTomcatApplicationDriverTests.java similarity index 100% rename from SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/NonAutoConfigurationTomcatApplicationDriverTests.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/NonAutoConfigurationTomcatApplicationDriverTests.java diff --git a/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/TomcatApplicationTests.java b/APPLICATIONS/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/TomcatApplicationTests.java similarity index 100% rename from SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/TomcatApplicationTests.java rename to APPLICATIONS/SpringBootTomcatServerExample/src/test/java/com/espark/adarsh/test/TomcatApplicationTests.java diff --git a/SpringBootWebMvcJspExample/pom.xml b/APPLICATIONS/SpringBootWebMvcJspExample/pom.xml similarity index 100% rename from SpringBootWebMvcJspExample/pom.xml rename to APPLICATIONS/SpringBootWebMvcJspExample/pom.xml diff --git a/SpringBootWebMvcJspExample/src/main/doc/help.txt b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/doc/help.txt similarity index 100% rename from SpringBootWebMvcJspExample/src/main/doc/help.txt rename to APPLICATIONS/SpringBootWebMvcJspExample/src/main/doc/help.txt diff --git a/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/configuration/WebMvcJspApplication.java b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/configuration/WebMvcJspApplication.java similarity index 100% rename from SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/configuration/WebMvcJspApplication.java rename to APPLICATIONS/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/configuration/WebMvcJspApplication.java diff --git a/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/web/WelcomeController.java b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/web/WelcomeController.java similarity index 100% rename from SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/web/WelcomeController.java rename to APPLICATIONS/SpringBootWebMvcJspExample/src/main/java/com/espark/adarsh/web/WelcomeController.java diff --git a/SpringBootWebMvcJspExample/src/main/resources/application.properties b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/resources/application.properties similarity index 100% rename from SpringBootWebMvcJspExample/src/main/resources/application.properties rename to APPLICATIONS/SpringBootWebMvcJspExample/src/main/resources/application.properties diff --git a/SpringBootWebMvcJspExample/src/main/webapp/WEB-INF/jsp/welcome.jsp b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/WEB-INF/jsp/welcome.jsp similarity index 100% rename from SpringBootWebMvcJspExample/src/main/webapp/WEB-INF/jsp/welcome.jsp rename to APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/WEB-INF/jsp/welcome.jsp diff --git a/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap-theme.min.css b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap-theme.min.css new file mode 100644 index 00000000..dc95d8e4 --- /dev/null +++ b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap-theme.min.css @@ -0,0 +1,6 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */.btn-danger,.btn-default,.btn-info,.btn-primary,.btn-success,.btn-warning{text-shadow:0 -1px 0 rgba(0,0,0,.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075)}.btn-danger.active,.btn-danger:active,.btn-default.active,.btn-default:active,.btn-info.active,.btn-info:active,.btn-primary.active,.btn-primary:active,.btn-success.active,.btn-success:active,.btn-warning.active,.btn-warning:active{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-danger.disabled,.btn-danger[disabled],.btn-default.disabled,.btn-default[disabled],.btn-info.disabled,.btn-info[disabled],.btn-primary.disabled,.btn-primary[disabled],.btn-success.disabled,.btn-success[disabled],.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-danger,fieldset[disabled] .btn-default,fieldset[disabled] .btn-info,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-success,fieldset[disabled] .btn-warning{-webkit-box-shadow:none;box-shadow:none}.btn-danger .badge,.btn-default .badge,.btn-info .badge,.btn-primary .badge,.btn-success .badge,.btn-warning .badge{text-shadow:none}.btn.active,.btn:active{background-image:none}.btn-default{text-shadow:0 1px 0 #fff;background-image:-webkit-linear-gradient(top,#fff 0,#e0e0e0 100%);background-image:-o-linear-gradient(top,#fff 0,#e0e0e0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fff),to(#e0e0e0));background-image:linear-gradient(to bottom,#fff 0,#e0e0e0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#dbdbdb;border-color:#ccc}.btn-default:focus,.btn-default:hover{background-color:#e0e0e0;background-position:0 -15px}.btn-default.active,.btn-default:active{background-color:#e0e0e0;border-color:#dbdbdb}.btn-default.disabled,.btn-default.disabled.active,.btn-default.disabled.focus,.btn-default.disabled:active,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled],.btn-default[disabled].active,.btn-default[disabled].focus,.btn-default[disabled]:active,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default.active,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#e0e0e0;background-image:none}.btn-primary{background-image:-webkit-linear-gradient(top,#337ab7 0,#265a88 100%);background-image:-o-linear-gradient(top,#337ab7 0,#265a88 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#265a88));background-image:linear-gradient(to bottom,#337ab7 0,#265a88 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#245580}.btn-primary:focus,.btn-primary:hover{background-color:#265a88;background-position:0 -15px}.btn-primary.active,.btn-primary:active{background-color:#265a88;border-color:#245580}.btn-primary.disabled,.btn-primary.disabled.active,.btn-primary.disabled.focus,.btn-primary.disabled:active,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled],.btn-primary[disabled].active,.btn-primary[disabled].focus,.btn-primary[disabled]:active,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary.active,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#265a88;background-image:none}.btn-success{background-image:-webkit-linear-gradient(top,#5cb85c 0,#419641 100%);background-image:-o-linear-gradient(top,#5cb85c 0,#419641 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#419641));background-image:linear-gradient(to bottom,#5cb85c 0,#419641 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#3e8f3e}.btn-success:focus,.btn-success:hover{background-color:#419641;background-position:0 -15px}.btn-success.active,.btn-success:active{background-color:#419641;border-color:#3e8f3e}.btn-success.disabled,.btn-success.disabled.active,.btn-success.disabled.focus,.btn-success.disabled:active,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled],.btn-success[disabled].active,.btn-success[disabled].focus,.btn-success[disabled]:active,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success.active,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#419641;background-image:none}.btn-info{background-image:-webkit-linear-gradient(top,#5bc0de 0,#2aabd2 100%);background-image:-o-linear-gradient(top,#5bc0de 0,#2aabd2 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5bc0de),to(#2aabd2));background-image:linear-gradient(to bottom,#5bc0de 0,#2aabd2 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#28a4c9}.btn-info:focus,.btn-info:hover{background-color:#2aabd2;background-position:0 -15px}.btn-info.active,.btn-info:active{background-color:#2aabd2;border-color:#28a4c9}.btn-info.disabled,.btn-info.disabled.active,.btn-info.disabled.focus,.btn-info.disabled:active,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled],.btn-info[disabled].active,.btn-info[disabled].focus,.btn-info[disabled]:active,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info.active,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#2aabd2;background-image:none}.btn-warning{background-image:-webkit-linear-gradient(top,#f0ad4e 0,#eb9316 100%);background-image:-o-linear-gradient(top,#f0ad4e 0,#eb9316 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f0ad4e),to(#eb9316));background-image:linear-gradient(to bottom,#f0ad4e 0,#eb9316 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#e38d13}.btn-warning:focus,.btn-warning:hover{background-color:#eb9316;background-position:0 -15px}.btn-warning.active,.btn-warning:active{background-color:#eb9316;border-color:#e38d13}.btn-warning.disabled,.btn-warning.disabled.active,.btn-warning.disabled.focus,.btn-warning.disabled:active,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled],.btn-warning[disabled].active,.btn-warning[disabled].focus,.btn-warning[disabled]:active,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning.active,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#eb9316;background-image:none}.btn-danger{background-image:-webkit-linear-gradient(top,#d9534f 0,#c12e2a 100%);background-image:-o-linear-gradient(top,#d9534f 0,#c12e2a 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9534f),to(#c12e2a));background-image:linear-gradient(to bottom,#d9534f 0,#c12e2a 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#b92c28}.btn-danger:focus,.btn-danger:hover{background-color:#c12e2a;background-position:0 -15px}.btn-danger.active,.btn-danger:active{background-color:#c12e2a;border-color:#b92c28}.btn-danger.disabled,.btn-danger.disabled.active,.btn-danger.disabled.focus,.btn-danger.disabled:active,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled],.btn-danger[disabled].active,.btn-danger[disabled].focus,.btn-danger[disabled]:active,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger.active,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#c12e2a;background-image:none}.img-thumbnail,.thumbnail{-webkit-box-shadow:0 1px 2px rgba(0,0,0,.075);box-shadow:0 1px 2px rgba(0,0,0,.075)}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{background-color:#e8e8e8;background-image:-webkit-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-o-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f5f5f5),to(#e8e8e8));background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);background-repeat:repeat-x}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{background-color:#2e6da4;background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}.navbar-default{background-image:-webkit-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:-o-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fff),to(#f8f8f8));background-image:linear-gradient(to bottom,#fff 0,#f8f8f8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 5px rgba(0,0,0,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 5px rgba(0,0,0,.075)}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.open>a{background-image:-webkit-linear-gradient(top,#dbdbdb 0,#e2e2e2 100%);background-image:-o-linear-gradient(top,#dbdbdb 0,#e2e2e2 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dbdbdb),to(#e2e2e2));background-image:linear-gradient(to bottom,#dbdbdb 0,#e2e2e2 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0);background-repeat:repeat-x;-webkit-box-shadow:inset 0 3px 9px rgba(0,0,0,.075);box-shadow:inset 0 3px 9px rgba(0,0,0,.075)}.navbar-brand,.navbar-nav>li>a{text-shadow:0 1px 0 rgba(255,255,255,.25)}.navbar-inverse{background-image:-webkit-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:-o-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#3c3c3c),to(#222));background-image:linear-gradient(to bottom,#3c3c3c 0,#222 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-radius:4px}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.open>a{background-image:-webkit-linear-gradient(top,#080808 0,#0f0f0f 100%);background-image:-o-linear-gradient(top,#080808 0,#0f0f0f 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#080808),to(#0f0f0f));background-image:linear-gradient(to bottom,#080808 0,#0f0f0f 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0);background-repeat:repeat-x;-webkit-box-shadow:inset 0 3px 9px rgba(0,0,0,.25);box-shadow:inset 0 3px 9px rgba(0,0,0,.25)}.navbar-inverse .navbar-brand,.navbar-inverse .navbar-nav>li>a{text-shadow:0 -1px 0 rgba(0,0,0,.25)}.navbar-fixed-bottom,.navbar-fixed-top,.navbar-static-top{border-radius:0}@media (max-width:767px){.navbar .navbar-nav .open .dropdown-menu>.active>a,.navbar .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}}.alert{text-shadow:0 1px 0 rgba(255,255,255,.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 1px 2px rgba(0,0,0,.05)}.alert-success{background-image:-webkit-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:-o-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dff0d8),to(#c8e5bc));background-image:linear-gradient(to bottom,#dff0d8 0,#c8e5bc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);background-repeat:repeat-x;border-color:#b2dba1}.alert-info{background-image:-webkit-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:-o-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9edf7),to(#b9def0));background-image:linear-gradient(to bottom,#d9edf7 0,#b9def0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);background-repeat:repeat-x;border-color:#9acfea}.alert-warning{background-image:-webkit-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:-o-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fcf8e3),to(#f8efc0));background-image:linear-gradient(to bottom,#fcf8e3 0,#f8efc0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);background-repeat:repeat-x;border-color:#f5e79e}.alert-danger{background-image:-webkit-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:-o-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f2dede),to(#e7c3c3));background-image:linear-gradient(to bottom,#f2dede 0,#e7c3c3 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);background-repeat:repeat-x;border-color:#dca7a7}.progress{background-image:-webkit-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:-o-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#ebebeb),to(#f5f5f5));background-image:linear-gradient(to bottom,#ebebeb 0,#f5f5f5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);background-repeat:repeat-x}.progress-bar{background-image:-webkit-linear-gradient(top,#337ab7 0,#286090 100%);background-image:-o-linear-gradient(top,#337ab7 0,#286090 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#286090));background-image:linear-gradient(to bottom,#337ab7 0,#286090 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0);background-repeat:repeat-x}.progress-bar-success{background-image:-webkit-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:-o-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44));background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);background-repeat:repeat-x}.progress-bar-info{background-image:-webkit-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:-o-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5bc0de),to(#31b0d5));background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);background-repeat:repeat-x}.progress-bar-warning{background-image:-webkit-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:-o-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f0ad4e),to(#ec971f));background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);background-repeat:repeat-x}.progress-bar-danger{background-image:-webkit-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:-o-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9534f),to(#c9302c));background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);background-repeat:repeat-x}.progress-bar-striped{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.list-group{border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.075);box-shadow:0 1px 2px rgba(0,0,0,.075)}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{text-shadow:0 -1px 0 #286090;background-image:-webkit-linear-gradient(top,#337ab7 0,#2b669a 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2b669a 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2b669a));background-image:linear-gradient(to bottom,#337ab7 0,#2b669a 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0);background-repeat:repeat-x;border-color:#2b669a}.list-group-item.active .badge,.list-group-item.active:focus .badge,.list-group-item.active:hover .badge{text-shadow:none}.panel{-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.panel-default>.panel-heading{background-image:-webkit-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-o-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f5f5f5),to(#e8e8e8));background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);background-repeat:repeat-x}.panel-primary>.panel-heading{background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}.panel-success>.panel-heading{background-image:-webkit-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:-o-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dff0d8),to(#d0e9c6));background-image:linear-gradient(to bottom,#dff0d8 0,#d0e9c6 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);background-repeat:repeat-x}.panel-info>.panel-heading{background-image:-webkit-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:-o-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9edf7),to(#c4e3f3));background-image:linear-gradient(to bottom,#d9edf7 0,#c4e3f3 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);background-repeat:repeat-x}.panel-warning>.panel-heading{background-image:-webkit-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:-o-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fcf8e3),to(#faf2cc));background-image:linear-gradient(to bottom,#fcf8e3 0,#faf2cc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);background-repeat:repeat-x}.panel-danger>.panel-heading{background-image:-webkit-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:-o-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f2dede),to(#ebcccc));background-image:linear-gradient(to bottom,#f2dede 0,#ebcccc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);background-repeat:repeat-x}.well{background-image:-webkit-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:-o-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#e8e8e8),to(#f5f5f5));background-image:linear-gradient(to bottom,#e8e8e8 0,#f5f5f5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);background-repeat:repeat-x;border-color:#dcdcdc;-webkit-box-shadow:inset 0 1px 3px rgba(0,0,0,.05),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 3px rgba(0,0,0,.05),0 1px 0 rgba(255,255,255,.1)} +/*# sourceMappingURL=bootstrap-theme.min.css.map */ \ No newline at end of file diff --git a/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap.min.css b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap.min.css new file mode 100644 index 00000000..4cf729e4 --- /dev/null +++ b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/css/bootstrap.min.css @@ -0,0 +1,6 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\002a"}.glyphicon-plus:before{content:"\002b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:focus,a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:focus,a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control::-ms-expand{background-color:transparent;border:0}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=time].form-control,input[type=datetime-local].form-control,input[type=month].form-control{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px\9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:6px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:11px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#333;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.dropdown-toggle.btn-default.focus,.open>.dropdown-toggle.btn-default:focus,.open>.dropdown-toggle.btn-default:hover{color:#333;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#286090;border-color:#122b40}.btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.dropdown-toggle.btn-primary.focus,.open>.dropdown-toggle.btn-primary:focus,.open>.dropdown-toggle.btn-primary:hover{color:#fff;background-color:#204d74;border-color:#122b40}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#449d44;border-color:#255625}.btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.dropdown-toggle.btn-success.focus,.open>.dropdown-toggle.btn-success:focus,.open>.dropdown-toggle.btn-success:hover{color:#fff;background-color:#398439;border-color:#255625}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#31b0d5;border-color:#1b6d85}.btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.dropdown-toggle.btn-info.focus,.open>.dropdown-toggle.btn-info:focus,.open>.dropdown-toggle.btn-info:hover{color:#fff;background-color:#269abc;border-color:#1b6d85}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#ec971f;border-color:#985f0d}.btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.dropdown-toggle.btn-warning.focus,.open>.dropdown-toggle.btn-warning:focus,.open>.dropdown-toggle.btn-warning:hover{color:#fff;background-color:#d58512;border-color:#985f0d}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c9302c;border-color:#761c19}.btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.dropdown-toggle.btn-danger.focus,.open>.dropdown-toggle.btn-danger:focus,.open>.dropdown-toggle.btn-danger:hover{color:#fff;background-color:#ac2925;border-color:#761c19}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group .form-control:focus{z-index:3}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.3333333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{padding-right:15px;padding-left:15px;border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-left-radius:0;border-top-right-radius:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;filter:alpha(opacity=0);opacity:0;line-break:auto}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);line-break:auto}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);background-color:rgba(0,0,0,0);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block;margin-top:-10px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000\9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-10px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-10px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.modal-header:after,.modal-header:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.modal-header:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/bootstrap.min.js b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/bootstrap.min.js new file mode 100644 index 00000000..e79c0651 --- /dev/null +++ b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/jquery.min.js b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/jquery.min.js new file mode 100644 index 00000000..f3644431 --- /dev/null +++ b/APPLICATIONS/SpringBootWebMvcJspExample/src/main/webapp/js/jquery.min.js @@ -0,0 +1,6 @@ +/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; + +return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/\s*$/g,ra={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?""!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("')}catch(d){c=J.createElement("iframe"),c.name=a}c.height="0";c.width="0";c.style.display="none";c.style.visibility="hidden";var e=Ne()+"/u/post_iframe.html";Ga(W,"beforeunload",function(){c.src="";c.parentNode&&c.parentNode.removeChild(c)}); +setTimeout(b,1E3);J.body.appendChild(c);c.src=e;return!0};var qf=function(){this.G=this.w=!1;0==Ea()%1E4&&(H(142),this.G=!0);this.C={};this.D=[];this.U=0;this.S=[["www.google-analytics.com","","/plugins/"]];this._gasoCPath=this._gasoDomain=this.bb=void 0;Re();Se()};E=qf.prototype;E.oa=function(a,b){return this.hb(a,void 0,b)};E.hb=function(a,b,c){b&&H(23);c&&H(67);void 0==b&&(b="~"+M.U++);a=new U(b,a,c);M.C[b]=a;M.D.push(a);return a};E.u=function(a){a=a||"";return M.C[a]||M.hb(void 0,a)};E.pa=function(){return M.D.slice(0)};E.ab=function(){return M.D.length}; +E.aa=function(){this.w=!0};E.la=function(){this.G=!0};var Fe=function(a){if("prerender"==J.visibilityState)return!1;a();return!0};var M=new qf;var Ha=W._gat;Ha&&Ba(Ha._getTracker)?M=Ha:W._gat=M;var Z=new Y;(function(a){if(!Fe(a)){H(123);var b=!1,c=function(){if(!b&&Fe(a)){b=!0;var d=J,e=c;d.removeEventListener?d.removeEventListener("visibilitychange",e,!1):d.detachEvent&&d.detachEvent("onvisibilitychange",e)}};Ga(J,"visibilitychange",c)}})(function(){var a=W._gaq,b=!1;if(a&&Ba(a.push)&&(b="[object Array]"==Object.prototype.toString.call(Object(a)),!b)){Z=a;return}W._gaq=Z;b&&Z.push.apply(Z,a)});function Yc(a){var b=1,c=0,d;if(a)for(b=0,d=a.length-1;0<=d;d--)c=a.charCodeAt(d),b=(b<<6&268435455)+c+(c<<14),c=b&266338304,b=0!=c?b^c>>21:b;return b};})(); diff --git "a/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/inpage_linkid.js" "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/inpage_linkid.js" new file mode 100644 index 00000000..4a0ee614 --- /dev/null +++ "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/inpage_linkid.js" @@ -0,0 +1,4 @@ +var e=document;window._gaq||eval("var _gaq = [];");_gaq.push(["_provide","inpage_linkid",f]); +function f(c,g){var l=/(?:^__utmli=|; ?__utmli=)([^;]*)/,d=this,m=function(a,b,d,c){var h="addEventListener",k="attachEvent";if(a[h])a[h](b,d,!!c);else if(a[k])a[k]("on"+b,d)};this.e=function(){return"; path=/"};var n=c._trackPageview;c._trackPageview=function(a){d.a();d.f&&c._setXKey(12,1,d.f);n.call(c,a)};this.g=function(){this.i||(this.i=!0,m(e,"click",function(a){d.h(a)}))};this.h=function(a){try{a=a||window.event;var b=a.target||a.srcElement;for(a=0;3>a&&!b.id&&b!=e.body;a++)b=b.parentNode;var c= +b.id||"";d.d(c)}catch(g){}return!0};this.b=function(a,b){f.prototype[a]=b};this.d=function(a){if(a&&100>a.length){a=a.replace(/[^-0-9a-z_:.]/gi,"");var b=new Date((new Date).getTime()+3E4);e.cookie="__utmli="+a+"; expires="+b.toUTCString()+this.e()}else this.a()};this.b("trackClickId",this.d);this.a=function(){e.cookie="__utmli=; expires=Thu, 01-Jan-1970 00:00:01 GMT"+this.e()};this.b("deleteClickId",this.a);this.c=function(a){var b=(l.exec(e.cookie)||["",""])[1];a&&a(b);return b};this.b("getClickId", +this.c);this.f=this.c();g.disableAutoTrackLinkId||this.g()}; diff --git "a/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/manual-multipage.css" "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/manual-multipage.css" new file mode 100644 index 00000000..10be4be0 --- /dev/null +++ "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/manual-multipage.css" @@ -0,0 +1 @@ +@IMPORT url("manual.css");body.firstpage{background:url("../images/background.png") no-repeat center top;}div.part h1{border-top:none;} \ No newline at end of file diff --git "a/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/note.png" "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/note.png" new file mode 100644 index 00000000..5daec8a1 Binary files /dev/null and "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/note.png" differ diff --git "a/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/searchtool.js" "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/searchtool.js" new file mode 100644 index 00000000..25cacdb3 --- /dev/null +++ "b/APPLICATIONS/properties/Appendix\302\240A.\302\240Common application properties_files/searchtool.js" @@ -0,0 +1 @@ +eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('5 3={I:7(){5 a=\'\';8(1v.18.19.2m(\'1w\'))a=\'1w\';J\'1i\'+a+\'.\'+3.1j()},1j:7(){5 a=1v.18.19.1k(\'.\');a.2n();J a[1]+\'.\'+a[0]},U:7(){1x=3.1j();5 a=1x.1k(\'.\');J a[0]},V:y,1y:7(c){8(W.X&&W.X.1z.1l==\'1.4.2\'){J}1A(0,c);7 1A(a,b){1m(5 i=a;i\');$(\'1a\').R(\'\');8($.1H.1I){$(\'1a\').R(\'\')}$(\'2w\').R(\'&2y;\'+\'\'+\' <11 1J="0" S="\'+d+\'1r" C="r://\'+f+\'/t/L/1K\'+d+\'.T" />\'+\' <11 S="\'+d+\'1r" 1J="0" C="r://\'+f+\'/t/L/2C\'+d+\'2D.T" />\'+\' \'+\' <2F 1L="p" P="Q" A="p" 1M="E F" />\'+\' <1N 1L="v" A="v">\'+\' <11 2G="E F" C="r://\'+f+\'/t/L/1O\'+d+\'.T" A="1c"/>\'+\' \'+\' \'+\' \'+\' \'+\' \'+\' (7() {\'+\' 5 s = O.1B("Y");\'+\' s.P = "Q/1n";\'+\' s.1P = 1E;\'+\' s.C = "r://2J.2K.1Q/2L/2M\'+d+\'";\'+\' 5 x = O.1D("Y")[0];\'+\' x.2N.2O(s, x);\'+\' })();\'+\' \'+\' \'+\'\');5 h=3.H(\'1R\');8(h!=y){$(\'#v\').R(h);1b(d)}z{$.2P({2Q:\'r://\'+18.19+\'/1i/t/?2R=1\',2S:\'2T\',1P:2U,2V:7(j){5 a=\'\';5 b=\'\';1m(5 i=0;i\'+j[i].1U+\'\';b+=j[i].1T+\',\'+j[i].1U;8(i!=j.K-1)b+=\'|\'}3.B(\'1R\',a,2W);$(\'#v\').R(a);1b(d)}})}7 1b(a){5 b={};8(a==\'1V\'){$(\'#v\').9(\'2X\');b={\'G\':\'1V.1Q\'}}z 8(a==\'1W\'){$(\'#v\').9(\'2Y\');b={\'G\':\'1W.2Z\'}}z 8(a==\'1X\'){$(\'#v\').9(\'30\');b={\'G\':\'1X.1Y\'}}z 8(a==\'1Z\'){$(\'#v\').9(\'31\');b={\'G\':\'1Z.1Y\'}}5 c=3.H(\'20\');8(c!=y)$(\'#v\').9(c);J b}5 k=3.H(\'21\');8(k==y)k=\'E F\';5 l=3.H(\'22\');5 m=3.H(\'23\');5 n=3.H(\'12\');$(\'#p\').9(k);$(\'#p\').24(7(){1d()});$(\'#p\').25(7(){1d()});$(\'#D\').M(\'32\',\'1e:-26;33:26;\');$(\'#D\').27(7(){3.1f($,3.H(\'12\'))});$(\'#p\').24(7(){8($(N).9()==\'E F\'){$(N).9(\'\');$(N).u(\'1g\',\'#28\')}});$(\'#p\').25(7(){8($(N).9()==\'\'||$(N).9()==\'E F\'){$(N).u(\'1g\',\'#29\');$(N).9(\'E F\')}});$(\'#p\').34(7(e){8(e.35==13){3.14($,0)}});$(\'#v\').36(7(){3.14($,0)});$(\'#1c\').27(7(){3.14($,0)});8(m!=y&&m!=\'15\'&&k!=y&&k!=\'\'&&n!=y&&n!=\'15\'){3.14($,l)}7 1d(){8($(\'#p\').9()==\'E F\'){$(\'#p\').9(\'E F\');$(\'#p\').u(\'1g\',\'#29\')}z{$(\'#p\').u(\'1g\',\'#28\')}}1d();8(n==y)3.1f(3.V,\'15\');z 8(n==\'15\')1F(\'3.1f(3.V,\\\'16\\\')\',17)},1f:7($,a){8(a==y||a==\'16\'){8($.1H.1I){5 b=2a($(\'#10\').u(\'2b\'))-37}z{5 b=2a($(\'#10\').u(\'2b\'))-38}$(\'#10\').1h({1e:b},17);$(\'#D\').M(\'S\',\'39\');$(\'#D\').1h({3a:0},17);$(\'#D 11\').M(\'C\',\'r://\'+3.I()+\'/t/L/3b\'+3.U()+\'.T\');$(\'#1s\').2c();$(\'#2d\').2c();3.B(\'12\',\'15\',6)}z{$(\'#10\').1h({1e:0},17);$(\'#D\').1h({1e:-1},17);$(\'#D\').M(\'S\',\'3c\');$(\'#D 11\').M(\'C\',\'r://\'+3.I()+\'/t/L/1K\'+3.U()+\'.T\');$(\'#1s\').2e();$(\'#2d\').2e();3.B(\'12\',\'16\',6)}},14:7($,a){8($(\'#p\').9()!=\'\'&&$(\'#p\').9()!=\'E F\'){$(\'#1c\').M(\'C\',\'r://\'+3.I()+\'/t/L/3d.3e\');$(\'#1t\').3f(\'r://\'+18.19+\'/1i/t/?\'+\'q=\'+3g($(\'#p\').9())+\'&\'+\'w=\'+$(\'#v\').9()+\'&\'+\'s=\'+a,7(){$(\'#1c\').2f(2g).M(\'C\',\'r://\'+3.I()+\'/t/L/1O\'+3.U()+\'.T\')});$(\'#1t\').2f(2h).3h(2h);3.B(\'21\',$(\'#p\').9(),6);3.B(\'20\',$(\'#v\').9(),6);3.B(\'22\',a,6);3.B(\'23\',\'16\',6);3.B(\'12\',\'16\',6)}},B:7(a,b,c){8(c){5 d=2i 3i();d.3j(d.3k()+(c*2j*2j*2g));5 e="; 3l="+d.3m()}z 5 e="";O.2k=a+"="+b+e+"; 3n=/"},H:7(a){5 b=a+"=";5 d=O.2k.1k(\';\');1m(5 i=0;i + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.1 + + + com.espark.adarsh + rabbitmq-direct-exchange + 0.0.1-SNAPSHOT + rabbitmq-direct-exchange + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.amqp + spring-rabbit-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java new file mode 100644 index 00000000..4860bfad --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java @@ -0,0 +1,50 @@ +package com.espark.adarsh; + +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import com.espark.adarsh.config.MessageReceiver; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class ApplicationMessagePublisher implements CommandLineRunner { + + private final RabbitTemplate rabbitTemplate; + private final MessageReceiver receiver; + + @Value("${app.directExchangeName}") + String directExchangeName; + + @Value("${app.routingKey}") + String routingKey; + + public ApplicationMessagePublisher(MessageReceiver receiver, RabbitTemplate rabbitTemplate) { + this.receiver = receiver; + this.rabbitTemplate = rabbitTemplate; + } + + @Override + public void run(String... args) throws Exception { + log.info("Publishing Message "); + String msg = "Welcome to Espark Adarsh "; + IntStream.range(0, 50) + .boxed().filter(integer -> { + log.info(">>> Publishing Message " + msg + integer); + try { + Thread.currentThread().sleep(1000); + } catch (Exception e) { + log.info(e.getMessage()); + } + return true; + }).forEach(integer -> { + rabbitTemplate.convertAndSend(directExchangeName, routingKey, msg + integer); + }); + receiver.getLatch().await(10000, TimeUnit.MILLISECONDS); + } + +} diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java new file mode 100644 index 00000000..9095a7de --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RabbitmqDirectExchangeApplication { + + public static void main(String[] args) { + SpringApplication.run(RabbitmqDirectExchangeApplication.class, args); + } + +} diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..7c7c2ba0 --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.config; + +import org.springframework.amqp.core.*; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; +import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class ApplicationConfig { + + @Value("${app.directExchangeName}") + String directExchangeName; + + @Value("${app.queueName}") + String queueName; + + @Value("${app.routingKey}") + String routingKey; + + @Bean + Queue queue() { + return new Queue(queueName, false); + } + + @Bean + DirectExchange exchange() { + return new DirectExchange(directExchangeName); + } + + @Bean + Binding binding(Queue queue, DirectExchange exchange) { + return BindingBuilder.bind(queue).to(exchange).with(routingKey); + } + + @Bean + SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, + MessageListenerAdapter listenerAdapter) { + SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); + container.setConnectionFactory(connectionFactory); + container.setQueueNames(queueName); + container.setMessageListener(listenerAdapter); + return container; + } + + @Bean + MessageListenerAdapter listenerAdapter(MessageReceiver messageReceiver) { + return new MessageListenerAdapter(messageReceiver, "receiveMessage"); + } +} diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java new file mode 100644 index 00000000..f0c0b1b3 --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.config; + +import java.util.concurrent.CountDownLatch; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class MessageReceiver { + + private CountDownLatch latch = new CountDownLatch(1); + + public void receiveMessage(String message) { + log.info("<<< Received Message {}", message); + latch.countDown(); + } + + public CountDownLatch getLatch() { + return latch; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/main/resources/application.properties b/APPLICATIONS/rabbitmq-direct-exchange/src/main/resources/application.properties new file mode 100644 index 00000000..1cc2f7b5 --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.rabbitmq.host=localhost +spring.rabbitmq.port=5672 +spring.rabbitmq.username=guest +spring.rabbitmq.password=guest + + +app.directExchangeName = espark-exchange +app.queueName = espark-queue +app.routingKey = espark.routing.key diff --git a/APPLICATIONS/rabbitmq-direct-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java b/APPLICATIONS/rabbitmq-direct-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java new file mode 100644 index 00000000..a7545b63 --- /dev/null +++ b/APPLICATIONS/rabbitmq-direct-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RabbitmqDirectExchangeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/rabbitmq-topic-exchange/.gitignore b/APPLICATIONS/rabbitmq-topic-exchange/.gitignore new file mode 100644 index 00000000..7ed0d6b6 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/.gitignore @@ -0,0 +1,32 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/rabbitmq-topic-exchange/README.md b/APPLICATIONS/rabbitmq-topic-exchange/README.md new file mode 100644 index 00000000..64f851b5 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/README.md @@ -0,0 +1,12 @@ +# Rabbitmq Topic Exchange + +---- + +### To Build the Code +* $ mvn clean package + +### To run the code +* $ spring-boot:run + +### To start the docker rabbitmq container +* docker run --name espark-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management diff --git a/APPLICATIONS/rabbitmq-topic-exchange/pom.xml b/APPLICATIONS/rabbitmq-topic-exchange/pom.xml new file mode 100644 index 00000000..8befb07a --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.1 + + + com.espark.adarsh + rabbitmq-topic-exchange + 0.0.1-SNAPSHOT + rabbitmq-topic-exchange + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.amqp + spring-rabbit-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java new file mode 100644 index 00000000..bb21cd96 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/ApplicationMessagePublisher.java @@ -0,0 +1,50 @@ +package com.espark.adarsh; + +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import com.espark.adarsh.config.MessageReceiver; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class ApplicationMessagePublisher implements CommandLineRunner { + + private final RabbitTemplate rabbitTemplate; + private final MessageReceiver receiver; + + @Value("${app.topicExchangeName}") + String topicExchangeName; + + @Value("${app.routingKey}") + String routingKey; + + public ApplicationMessagePublisher(MessageReceiver receiver, RabbitTemplate rabbitTemplate) { + this.receiver = receiver; + this.rabbitTemplate = rabbitTemplate; + } + + @Override + public void run(String... args) throws Exception { + log.info("Publishing Message "); + String msg = "Welcome to Espark Adarsh "; + IntStream.range(0, 50) + .boxed().filter(integer -> { + log.info(">>> Publishing Message " + msg + integer); + try { + Thread.currentThread().sleep(1000); + } catch (Exception e) { + log.info(e.getMessage()); + } + return true; + }).forEach(integer -> { + rabbitTemplate.convertAndSend(topicExchangeName, routingKey, msg + integer); + }); + receiver.getLatch().await(10000, TimeUnit.MILLISECONDS); + } + +} diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java new file mode 100644 index 00000000..9095a7de --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/RabbitmqDirectExchangeApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RabbitmqDirectExchangeApplication { + + public static void main(String[] args) { + SpringApplication.run(RabbitmqDirectExchangeApplication.class, args); + } + +} diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..01209ac4 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,54 @@ +package com.espark.adarsh.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.TopicExchange; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; +import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class ApplicationConfig { + + @Value("${app.topicExchangeName}") + String topicExchangeName; + @Value("${app.queueName}") + String queueName; + @Value("${app.routingKey}") + String routingKey; + + @Bean + Queue queue() { + return new Queue(queueName, false); + } + + @Bean + TopicExchange exchange() { + return new TopicExchange(topicExchangeName); + } + + @Bean + Binding binding(Queue queue, TopicExchange exchange) { + return BindingBuilder.bind(queue).to(exchange).with(routingKey); + } + + @Bean + SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, + MessageListenerAdapter listenerAdapter) { + SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); + container.setConnectionFactory(connectionFactory); + container.setQueueNames(queueName); + container.setMessageListener(listenerAdapter); + return container; + } + + @Bean + MessageListenerAdapter listenerAdapter(MessageReceiver messageReceiver) { + return new MessageListenerAdapter(messageReceiver, "receiveMessage"); + } +} diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java new file mode 100644 index 00000000..f0c0b1b3 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/main/java/com/espark/adarsh/config/MessageReceiver.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.config; + +import java.util.concurrent.CountDownLatch; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class MessageReceiver { + + private CountDownLatch latch = new CountDownLatch(1); + + public void receiveMessage(String message) { + log.info("<<< Received Message {}", message); + latch.countDown(); + } + + public CountDownLatch getLatch() { + return latch; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/main/resources/application.properties b/APPLICATIONS/rabbitmq-topic-exchange/src/main/resources/application.properties new file mode 100644 index 00000000..f7294455 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.rabbitmq.host=localhost +spring.rabbitmq.port=5672 +spring.rabbitmq.username=guest +spring.rabbitmq.password=guest + + +app.topicExchangeName = espark-exchange +app.queueName = espark-queue +app.routingKey = espark.routing.key.# diff --git a/APPLICATIONS/rabbitmq-topic-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java b/APPLICATIONS/rabbitmq-topic-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java new file mode 100644 index 00000000..a7545b63 --- /dev/null +++ b/APPLICATIONS/rabbitmq-topic-exchange/src/test/java/com/espark/adarsh/RabbitmqDirectExchangeApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RabbitmqDirectExchangeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/solr-client-query-example/doc/help.txt b/APPLICATIONS/solr-client-query-example/doc/help.txt new file mode 100644 index 00000000..c59b1432 --- /dev/null +++ b/APPLICATIONS/solr-client-query-example/doc/help.txt @@ -0,0 +1,23 @@ +$ cd /Users/akumar38/solr-6.6.0/bin +$ ./solr start +$ ./solr stgit add op + +#creating the core +$ ./solr create -c adarsh + +http://localhost:8983/solr/#/ +$ cd /Users/akumar38/solr-6.6.0/server/solr/adarsh/data + +#deleteing the core +$ ./solr delete -c adarsh + +# To extract solr dir from zip +$ tar xopf solr-6.6.0.tar + +#to delete the solr data +select core-> document -> xml -> +*:* + +http://localhost:8983/solr/#/oak/documents +DOCUMENTTYPE:XML +*:* \ No newline at end of file diff --git a/APPLICATIONS/solr-client-query-example/pom.xml b/APPLICATIONS/solr-client-query-example/pom.xml new file mode 100644 index 00000000..87748c73 --- /dev/null +++ b/APPLICATIONS/solr-client-query-example/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + solr-client-query-example + solr-client-query-example + 1.0-SNAPSHOT + + + + Java8BiFunctionExample + UTF-8 + 1.8 + 1.6.1 + 1.2.17 + + + + + + org.apache.solr + solr-solrj + 7.7.0 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + log4j + log4j + ${log4j.version} + + + + + + + ${project.name} + target/classes + + + src/main/resources + true + + + + + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + \ No newline at end of file diff --git a/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/DataFeeder.java b/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/DataFeeder.java new file mode 100644 index 00000000..bea47c25 --- /dev/null +++ b/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/DataFeeder.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.solr; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.common.SolrInputDocument; + +import java.io.IOException; + +public class DataFeeder { + + public static void main(String[] args) throws IOException, SolrServerException { + SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/adarsh").build(); + for(int i=0;i<1000;++i) { + SolrInputDocument doc = new SolrInputDocument(); + doc.addField("cat", "book"); + doc.addField("id", "book-" + i); + doc.addField("name", "The Legend of the Hobbit part " + i); + client.add(doc); + if(i%100==0) client.commit(); // periodically flush + } + client.commit(); + } +} diff --git a/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/SolrJSearcher.java b/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/SolrJSearcher.java new file mode 100644 index 00000000..04fab260 --- /dev/null +++ b/APPLICATIONS/solr-client-query-example/src/main/java/com/espark/adarsh/solr/SolrJSearcher.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.solr; + +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.SolrDocumentList; + +import java.io.IOException; + +public class SolrJSearcher { + public static void main(String[] args) throws IOException, SolrServerException { + + SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/adarsh").build(); + + SolrQuery query = new SolrQuery(); + query.setQuery("book query"); + query.addFilterQuery("cat:book"); + query.addFilterQuery("name:The Legend of the Hobbit part 200"); + query.setFields("id", "price", "merchant", "cat"); + query.setStart(0); + query.addSort("id", SolrQuery.ORDER.desc); + + QueryResponse response = client.query(query); + SolrDocumentList results = response.getResults(); + for (int i = 0; i < results.size(); ++i) { + System.out.println(results.get(i)); + } + } +} diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/.gitignore b/APPLICATIONS/sprinboot-sqs-elastic-queue/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/pom.xml b/APPLICATIONS/sprinboot-sqs-elastic-queue/pom.xml new file mode 100644 index 00000000..a9e0b0e4 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + com.aws.msg + sprinboot-sqs-elastic-queue + 0.0.1-SNAPSHOT + jar + + sprinboot-sqs-elastic-queue + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.amazonaws + amazon-sqs-java-messaging-lib + 1.0.4 + + + + org.elasticmq + elasticmq-rest-sqs_2.12 + 0.13.9 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework + spring-jms + 5.0.5.RELEASE + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/ApplicationSqsElasticQueue.java b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/ApplicationSqsElasticQueue.java new file mode 100644 index 00000000..5c2679ab --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/ApplicationSqsElasticQueue.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationSqsElasticQueue { + + public static void main(String[] args) { + SpringApplication.run(ApplicationSqsElasticQueue.class, args); + } +} diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/config/Configuration.java b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/config/Configuration.java new file mode 100644 index 00000000..b561ebe0 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/config/Configuration.java @@ -0,0 +1,100 @@ +package com.espark.adarsh.config; + +import com.amazon.sqs.javamessaging.ProviderConfiguration; +import com.amazon.sqs.javamessaging.SQSConnectionFactory; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.auth.profile.internal.BasicProfile; +import com.amazonaws.auth.profile.internal.ProfileStaticCredentialsProvider; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.sqs.AmazonSQSClient; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; +import org.elasticmq.rest.sqs.SQSRestServer; +import org.elasticmq.rest.sqs.SQSRestServerBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Profile; +import org.springframework.jms.config.DefaultJmsListenerContainerFactory; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.jms.support.destination.DynamicDestinationResolver; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.jms.ConnectionFactory; +import javax.jms.Session; +import java.util.HashMap; + +@org.springframework.context.annotation.Configuration +public class Configuration { + + @Value("${aws.sqsAccessKeyId}") + String sqsAwsAccessKeyId; + + @Value("${aws.sqsSecretAccessKey}") + String sqsAwsSecretAccessKey; + + @Value("${amzSQSPublishEventListener.workDestination}") + private String workDestination; + + @Value("${elastic.server.url}") + public String mqEndpoint; + + private SQSRestServer server; + + @PostConstruct + public void init() { + server = SQSRestServerBuilder.withPort(9324).withInterface("localhost").start(); + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")); + amazonSQSClient.setEndpoint(mqEndpoint); + amazonSQSClient.createQueue(workDestination); + + } + + @Profile("dev") + @Bean(name = "connection") + ConnectionFactory sqsConnectionFactory() { + return new SQSConnectionFactory(new ProviderConfiguration(), + AmazonSQSClientBuilder.standard() + .withRegion(Regions.US_EAST_1) + .withCredentials(new ProfileStaticCredentialsProvider(new BasicProfile("default", + new HashMap() { + { + put("aws_access_key_id", sqsAwsAccessKeyId); + put("aws_secret_access_key", sqsAwsSecretAccessKey); + } + } + )))); + } + + @Profile("local") + @Bean(name = "connection") + ConnectionFactory mqConnectionFactory() { + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")); + amazonSQSClient.setEndpoint(mqEndpoint); + return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQSClient); + } + + @Bean + @Autowired + JmsTemplate sqsJmsTemplate(ConnectionFactory connectionFactory) { + return new JmsTemplate(connectionFactory); + } + + @Bean + @Autowired + public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(@Qualifier("connection") ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + factory.setDestinationResolver(new DynamicDestinationResolver()); + factory.setConcurrency("3-10"); + factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); + return factory; + } + + @PreDestroy + public void destroy() { + server.stopAndGetFuture(); + } + +} diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/producer/Producer.java b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/producer/Producer.java new file mode 100644 index 00000000..658b5922 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/producer/Producer.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.producer; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jms.core.JmsTemplate; +import org.springframework.jms.core.MessageCreator; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Session; + + +@Component +public class Producer { + + @Autowired + private JmsTemplate jmsTemplate; + + @Value("${amzSQSPublishEventListener.workDestination}") + private String workDestination; + + @PostConstruct + public void init(){ + sendMessage(); + } + + public void sendMessage(){ + int var = 10; + while(var>0) { + jmsTemplate.send(workDestination, new MessageCreator() { + @Override + public Message createMessage(Session session) throws JMSException { + return session.createObjectMessage("my message "); + } + }); + var--; + } + } + +} diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/reciver/Consumer.java b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/reciver/Consumer.java new file mode 100644 index 00000000..9d4e1e75 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/java/com/espark/adarsh/reciver/Consumer.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.reciver; + +import org.springframework.jms.annotation.JmsListener; +import org.springframework.stereotype.Component; + + +@Component +public class Consumer { + + @JmsListener(destination = "${amzSQSPublishEventListener.workDestination}") + void onMessageReceived(String message) { + try { + System.out.println("Received: " +new String(message)); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/application.properties b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/application.properties new file mode 100644 index 00000000..6c857196 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=9090 +aws.sqsAccessKeyId=AKIAJ4JUDHPOLHJTBBYA +aws.sqsSecretAccessKey=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 + +spring.profiles.active=local +amzSQSPublishEventListener.workDestination=IRIS-DEV-akumar38-PUB + +elastic.server.url=http://localhost:9324 \ No newline at end of file diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/logback.xml b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/logback.xml new file mode 100644 index 00000000..29bcf350 --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/main/resources/logback.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/sprinboot-sqs-elastic-queue/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/sprinboot-sqs-elastic-queue/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-admin/README.md b/APPLICATIONS/spring-boot-admin/README.md new file mode 100644 index 00000000..622533a6 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/README.md @@ -0,0 +1,17 @@ +## 1. Spring Boot Admin Server + +* mvn clean install +* mvn spring-boot:run +* starts on port 8080 +* login with admin/admin +* to activate mail notifications uncomment the starter mail dependency +and the mail configuration from application.properties +* add some real credentials if you want the app to send emails +* to activate Hipchat notifications proceed same as for email + +## 2. Spring Boot App Client + +* mvn clean install +* mvn spring-boot:run +* starts on port 8081 +* basic auth client/client \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/pom.xml b/APPLICATIONS/spring-boot-admin/pom.xml new file mode 100644 index 00000000..a9f60685 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.espark.adarsh + spring-boot-admin + 0.0.1-SNAPSHOT + pom + + + UTF-8 + 1.5.8.RELEASE + + + + spring-boot-admin-server + spring-boot-admin-client + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/.gitignore b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/.gitignore new file mode 100644 index 00000000..2af7cefb --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/pom.xml b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/pom.xml new file mode 100644 index 00000000..121cd099 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + spring-boot-admin-client + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-client + Spring Boot Admin Client + + + spring-boot-admin + com.espark.adarsh + 0.0.1-SNAPSHOT + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-security + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + build-info + + + + + + + + + diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/java/com/espark/adarsh/SpringBootAdminClientApplication.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/java/com/espark/adarsh/SpringBootAdminClientApplication.java new file mode 100644 index 00000000..aad2b93c --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/java/com/espark/adarsh/SpringBootAdminClientApplication.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootAdminClientApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminClientApplication.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties new file mode 100644 index 00000000..7ad5e0f9 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/application.properties @@ -0,0 +1,20 @@ +#basic auth creddentials +security.user.name=client +security.user.password=client + +#configs to connect to a secured server +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=admin +spring.boot.admin.password=admin + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#app config +spring.application.name=spring-boot-admin-client +server.port=8081 + +spring.boot.admin.client.management-url= +spring.boot.admin.client.health-url= +spring.boot.admin.client.service-url= \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml new file mode 100644 index 00000000..ff96acae --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/test/java/com/espark/adarsh/SpringBootAdminClientApplicationIntegrationTest.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/test/java/com/espark/adarsh/SpringBootAdminClientApplicationIntegrationTest.java new file mode 100644 index 00000000..06c845a2 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-client/src/test/java/com/espark/adarsh/SpringBootAdminClientApplicationIntegrationTest.java @@ -0,0 +1,55 @@ +package com.espark.adarsh; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT) +public class SpringBootAdminClientApplicationIntegrationTest { + + @Autowired Environment environment; + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenEnvironmentAvailable_ThenAdminServerPropertiesExist() { + assertEquals(environment.getProperty("spring.boot.admin.url"), "http://localhost:8080"); + assertEquals(environment.getProperty("spring.boot.admin.username"), "admin"); + assertEquals(environment.getProperty("spring.boot.admin.password"), "admin"); + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("client", "client"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("client", "invalid"))) + .andExpect(status().isUnauthorized()); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/.gitignore b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/.gitignore new file mode 100644 index 00000000..2af7cefb --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/pom.xml b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/pom.xml new file mode 100644 index 00000000..5d4a776f --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/pom.xml @@ -0,0 +1,98 @@ + + + 4.0.0 + + spring-boot-admin-server + 0.0.1-SNAPSHOT + jar + + spring-boot-admin-server + Spring Boot Admin Server + + + spring-boot-admin + com.espark.adarsh + 0.0.1-SNAPSHOT + + + + UTF-8 + UTF-8 + 1.8 + 1.5.4 + 1.5.4 + + + + + org.springframework.boot + spring-boot-starter + + + + + de.codecentric + spring-boot-admin-server + ${spring-boot-admin-server.version} + + + de.codecentric + spring-boot-admin-server-ui + ${spring-boot-admin-server.version} + + + + + de.codecentric + spring-boot-admin-server-ui-login + ${spring-boot-admin-server.version} + + + org.springframework.boot + spring-boot-starter-security + + + com.hazelcast + hazelcast + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin-starter-client.version} + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.security + spring-security-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/SpringBootAdminServerApplication.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/SpringBootAdminServerApplication.java new file mode 100644 index 00000000..eb9eb681 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/SpringBootAdminServerApplication.java @@ -0,0 +1,14 @@ +package com.espark.adarsh; + +import de.codecentric.boot.admin.config.EnableAdminServer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@EnableAdminServer +@SpringBootApplication +public class SpringBootAdminServerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootAdminServerApplication.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/HazelcastConfig.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/HazelcastConfig.java new file mode 100644 index 00000000..0729050c --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/HazelcastConfig.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.configs; + +import com.hazelcast.config.Config; +import com.hazelcast.config.EvictionPolicy; +import com.hazelcast.config.ListConfig; +import com.hazelcast.config.MapConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class HazelcastConfig { + + @Bean + public Config hazelcast() { + return new Config() + .setProperty("hazelcast.jmx", "true") + .addMapConfig(new MapConfig("spring-boot-admin-application-store") + .setBackupCount(1) + .setEvictionPolicy(EvictionPolicy.NONE)) + .addListConfig(new ListConfig("spring-boot-admin-event-store") + .setBackupCount(1) + .setMaxSize(1000)); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/NotifierConfiguration.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/NotifierConfiguration.java new file mode 100644 index 00000000..db0461dc --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/NotifierConfiguration.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.configs; + +import de.codecentric.boot.admin.notify.LoggingNotifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +import java.util.concurrent.TimeUnit; + +@Configuration +@EnableScheduling +public class NotifierConfiguration { + + // @Autowired + // private Notifier notifier; + + @Bean + public LoggingNotifier notifier() { + return new LoggingNotifier(); + } + + @Bean + public FilteringNotifier filteringNotifier() { + return new FilteringNotifier(notifier()); + } + + @Bean + @Primary + public RemindingNotifier remindingNotifier() { + RemindingNotifier remindingNotifier = new RemindingNotifier(filteringNotifier()); + remindingNotifier.setReminderPeriod(TimeUnit.MINUTES.toMillis(5)); + return remindingNotifier; + } + + @Scheduled(fixedRate = 60000L) + public void remind() { + remindingNotifier().sendReminders(); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/WebSecurityConfig.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/WebSecurityConfig.java new file mode 100644 index 00000000..a5f60654 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/java/com/espark/adarsh/configs/WebSecurityConfig.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.configs; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .permitAll(); + http + .logout() + .logoutUrl("/logout"); + http + .csrf() + .disable(); + http + .authorizeRequests() + .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**") + .permitAll(); + http + .authorizeRequests() + .antMatchers("/**") + .authenticated(); + http.httpBasic(); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties new file mode 100644 index 00000000..362f6428 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=spring-boot-admin-server + +security.user.name=admin +security.user.password=admin + +#configs to connect to self register the admin server as a client +spring.boot.admin.url=http://localhost:8080 +spring.boot.admin.username=${security.user.name} +spring.boot.admin.password=${security.user.password} + +#configs to give secured server info +spring.boot.admin.client.metadata.user.name=${security.user.name} +spring.boot.admin.client.metadata.user.password=${security.user.password} + +#mail notifications +#spring.mail.host=smtp.gmail.com +#spring.mail.username=test@gmail.com +#spring.mail.password=password +#spring.mail.port=587 +#spring.mail.properties.mail.smtp.auth=true +#spring.mail.properties.mail.smtp.starttls.enable=true + +#spring.boot.admin.notify.mail.to=test@gmail.com + +#hipchat notifications +#spring.boot.admin.notify.hipchat.auth-token= +#spring.boot.admin.notify.hipchat.room-id= +#spring.boot.admin.notify.hipchat.url=https://youcompany.hipchat.com/v2/ \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml new file mode 100644 index 00000000..ff96acae --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + + %date [%thread] %-5level %logger{25} - %msg%n + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/HazelcastConfigIntegrationTest.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/HazelcastConfigIntegrationTest.java new file mode 100644 index 00000000..03852bec --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/HazelcastConfigIntegrationTest.java @@ -0,0 +1,24 @@ +package com.espark.adarsh; + +import com.espark.adarsh.configs.HazelcastConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE) +public class HazelcastConfigIntegrationTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStarts_HazelcastConfigBeanExists() { + assertNotEquals(applicationContext.getBean("hazelcast"), null); + } +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/NotifierConfigurationIntegrationTest.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/NotifierConfigurationIntegrationTest.java new file mode 100644 index 00000000..613593e3 --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/NotifierConfigurationIntegrationTest.java @@ -0,0 +1,41 @@ +package com.espark.adarsh; + +import com.espark.adarsh.configs.NotifierConfiguration; +import de.codecentric.boot.admin.notify.Notifier; +import de.codecentric.boot.admin.notify.RemindingNotifier; +import de.codecentric.boot.admin.notify.filter.FilteringNotifier; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE) +public class NotifierConfigurationIntegrationTest { + + @Autowired private ApplicationContext applicationContext; + + @Test + public void whenApplicationContextStart_ThenNotifierBeanExists() { + Notifier notifier = (Notifier) applicationContext.getBean("notifier"); + assertNotEquals(notifier, null); + } + + @Test + public void whenApplicationContextStart_ThenFilteringNotifierBeanExists() { + FilteringNotifier filteringNotifier = (FilteringNotifier) applicationContext.getBean("filteringNotifier"); + assertNotEquals(filteringNotifier, null); + } + + @Test + public void whenApplicationContextStart_ThenRemindingNotifierBeanExists() { + RemindingNotifier remindingNotifier = (RemindingNotifier) applicationContext.getBean("remindingNotifier"); + assertNotEquals(remindingNotifier, null); + } + +} diff --git a/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/WebSecurityConfigIntegrationTest.java b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/WebSecurityConfigIntegrationTest.java new file mode 100644 index 00000000..c55834ea --- /dev/null +++ b/APPLICATIONS/spring-boot-admin/spring-boot-admin-server/src/test/java/com/espark/adarsh/WebSecurityConfigIntegrationTest.java @@ -0,0 +1,71 @@ +package com.espark.adarsh; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebSecurityConfigIntegrationTest { + + @Autowired WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .build(); + } + + @Test + public void whenApplicationStarts_ThenGetLoginPageWithSuccess() throws Exception { + mockMvc + .perform(get("/login.html")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + public void whenFormLoginAttempted_ThenSuccess() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + } + + @Test + public void whenFormLoginWithSuccess_ThenApiEndpointsAreAccessible() throws Exception { + mockMvc.perform(formLogin("/login") + .user("admin") + .password("admin")); + + mockMvc + .perform(get("/api/applications/")) + .andExpect(status().is2xxSuccessful()); + + } + + @Test + public void whenHttpBasicAttempted_ThenSuccess() throws Exception { + mockMvc.perform(get("/env").with(httpBasic("admin", "admin"))); + } + + @Test + public void whenInvalidHttpBasicAttempted_ThenUnauthorized() throws Exception { + mockMvc + .perform(get("/env").with(httpBasic("admin", "invalid"))) + .andExpect(status().isUnauthorized()); + } + +} diff --git a/APPLICATIONS/spring-boot-angular-monolithic/.gitignore b/APPLICATIONS/spring-boot-angular-monolithic/.gitignore new file mode 100644 index 00000000..299e7bba --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/.gitignore @@ -0,0 +1,40 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +/angulrjs-ui/dist +/angulrjs-ui/node_modules +/angulrjs-ui/node + +.DS_Store +*.DS_Store +/*.DS_Store + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-angular-monolithic/README.md b/APPLICATIONS/spring-boot-angular-monolithic/README.md new file mode 100644 index 00000000..8467db74 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/README.md @@ -0,0 +1,234 @@ +# spring-boot-angular-monolithic +--- + +## STEP TO CREATE PROJECT STRUCTURE +* create `spring-boot-angular-monolithic` + * create a pom file with below tags +```` + + + 4.0.0 + pom + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + com.esprak.adarsh + spring-boot-angular-monolithic + 0.0.1-SNAPSHOT + spring-boot-angular-monolithic + Demo project for Spring Boot + + + springboot-services + angularjs-ui + + + + +```` +* create `springboot-services` maven module inside the `spring-boot-angular-monolithic` project + * create a pom file with below tags +```` + + + + spring-boot-angular-monolithic + com.esprak.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + springboot-services + 0.0.1-SNAPSHOT + + + 1.8 + + + + + com.esprak.adarsh + angularjs-ui + 0.0.1-SNAPSHOT + runtime + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + maven-resources-plugin + + + copy-resources + validate + copy-resources + + ${project.build.directory}/classes/resources/ + + + ${project.parent.basedir}/angularjs-ui/dist/adarsh/ + + + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + +```` +* create `angularjs-ui` maven module inside the `spring-boot-angular-monolithic` project + * create a pom file with below tags +```` + + + + spring-boot-angular-monolithic + com.esprak.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + angularjs-ui + 0.0.1-SNAPSHOT + + + + + ./dist/adarsh + static + + + + + com.github.eirslett + frontend-maven-plugin + 1.7.6 + + ./ + v10.16.0 + 6.10.2 + + + + install node and npm + + install-node-and-npm + + + + npm install + + npm + + + + npm run build + + npm + + + run build + + + + + + + +```` + * execute the below cmd inside the main project `spring-boot-angular-monolithic` + * cd spring-boot-angular-monolithic + * :spring-boot-angular-monolithic $ ng new angularjs-ui + * ? Would you like to add Angular routing? Yes + * ? Which stylesheet format would you like to use ? + * select SCSS option +```` + CSS + SCSS [ https://sass-lang.com/documentation/syntax#scss ] <- selet scss + Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ] + Less [ http://lesscss.org ] + Stylus [ http://stylus-lang.com ] +```` + * import the bootstarp in the project + * npm i bootstrap --save + * import the boot srap in angularjs application + * spring-boot-angular-monolithic/angularjs-ui/src/app/app.component.html which is starting point for the angular + * NOTE: clean the file and only leave the <'router-outlet> +``` +
+

welcome to espark angularjs monotlithic application

+
+ +``` + * spring-boot-angular-monolithic/angularjs-ui/src/style.cass bootstrap has to be added into the +``` + @import '~bootstrap/dist/css/bootstrap.min.css'; +``` + +### Test the angular +* cd angularjs-ui +* angularjs-ui $ ng serve +* to access angularjs page `http://localhost:4200/` +### To Build the code +* spring-boot-angular-monolithic $ mvn clean package +* spring-boot-angular-monolithic $ java -jar ./springboot-services/target/springboot-services-0.0.1-SNAPSHOT.jar +* to access ui page `http://localhost:8080/` + + +### To access the web api +* `http://localhost:8080/wish` \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-angular-monolithic/pom.xml b/APPLICATIONS/spring-boot-angular-monolithic/pom.xml new file mode 100644 index 00000000..3ad46980 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + pom + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + com.esprak.adarsh + spring-boot-angular-monolithic + 0.0.1-SNAPSHOT + spring-boot-angular-monolithic + Demo project for Spring Boot + + + springboot-services + angularjs-ui + + + diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/pom.xml b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/pom.xml new file mode 100644 index 00000000..1cea3b18 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/pom.xml @@ -0,0 +1,92 @@ + + + + spring-boot-angular-monolithic + com.esprak.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + springboot-services + 0.0.1-SNAPSHOT + + + 1.8 + + + + + + com.esprak.adarsh + angularjs-ui + 0.0.1-SNAPSHOT + runtime + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + maven-resources-plugin + + + copy-resources + validate + copy-resources + + ${project.build.directory}/classes/resources/ + + + ${project.parent.basedir}/angularjs-ui/dist/angularjs-ui/ + + + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java new file mode 100644 index 00000000..dea70077 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.resource.PathResourceResolver; + +import java.io.IOException; + +@Configuration +public class ApplicationWebConfig implements WebMvcConfigurer { + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + + registry.addResourceHandler("/", "/*.html", "/*.js", "/*.css", "/*.png", "/*.ico", "*.svg", "*.json") + .addResourceLocations("classpath:/static/") + .resourceChain(true) + .addResolver(new PathResourceResolver() { + @Override + protected Resource getResource(String resourcePath, Resource location) throws IOException { + Resource requestedResource = location.createRelative(resourcePath); + return requestedResource.exists() && requestedResource.isReadable() ? requestedResource + : new ClassPathResource("/static/index.html"); + } + }); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..62bb1aee --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalTime; +import java.util.HashMap; +import java.util.Map; + +@RestController +public class ApplicationController { + + @GetMapping("/wish") + public Map getWishMessage(){ + return new HashMap(){ + { + put("message","welcome to espark "); + put("time", LocalTime.now().toString()); + } + }; + } +} diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/resources/application.properties b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/resources/static/text.html b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/main/resources/static/text.html new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/spring-boot-angular-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/.gitignore b/APPLICATIONS/spring-boot-file-upload-rest/.gitignore new file mode 100644 index 00000000..a5c0e7bb --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/.gitignore @@ -0,0 +1,38 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +.DS_Store +*.DS_Store +*/.DS_Store +/*.DS_Store + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-file-upload-rest/README.md b/APPLICATIONS/spring-boot-file-upload-rest/README.md new file mode 100644 index 00000000..fcf11f39 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/README.md @@ -0,0 +1,23 @@ +# spring-boot file upload rest example + +--- + +### h2 db console url +* http://localhost:9090/h2-console +* root/root + + +## api post url +* http://localhost:9090/api/image +* form param name "image" +## curl cmd +* curl --location --request POST 'http://localhost:9090/api/image' \ + --form 'image=@"/Users/us-guest/Documents/Untitled.jpg"' + +![img](./image/1img.png) +![img](./image/2img.png) + +## api get url +* http://localhost:9090/api/image/Untitled.jpg +## curl cmd +* curl --location --request GET 'http://localhost:9090/api/image/Untitled.jpg' \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-file-upload-rest/image/1img.png b/APPLICATIONS/spring-boot-file-upload-rest/image/1img.png new file mode 100644 index 00000000..b08bd11a Binary files /dev/null and b/APPLICATIONS/spring-boot-file-upload-rest/image/1img.png differ diff --git a/APPLICATIONS/spring-boot-file-upload-rest/image/2img.png b/APPLICATIONS/spring-boot-file-upload-rest/image/2img.png new file mode 100644 index 00000000..68cb15dd Binary files /dev/null and b/APPLICATIONS/spring-boot-file-upload-rest/image/2img.png differ diff --git a/APPLICATIONS/spring-boot-file-upload-rest/pom.xml b/APPLICATIONS/spring-boot-file-upload-rest/pom.xml new file mode 100644 index 00000000..b2fed1e0 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.3 + + + com.espark.adarsh + spring-boot-file-upload-rest + 0.0.1-SNAPSHOT + spring-boot-file-upload-rest + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/SpringBootFileUploadRestApplication.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/SpringBootFileUploadRestApplication.java new file mode 100644 index 00000000..74363386 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/SpringBootFileUploadRestApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootFileUploadRestApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootFileUploadRestApplication.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/entity/ImageEntity.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/entity/ImageEntity.java new file mode 100644 index 00000000..e8faa96e --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/entity/ImageEntity.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import javax.persistence.*; + + +@Entity +@Table(name = "ImageEntity") +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class ImageEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + private String type; + @Lob + @Column(name = "image",length = 1000) + private byte[] imageData; + +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/repository/ImageRepository.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/repository/ImageRepository.java new file mode 100644 index 00000000..b1a07450 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/repository/ImageRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.ImageEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface ImageRepository extends JpaRepository { + + Optional findByName(String fileName); +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/service/ImageService.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/service/ImageService.java new file mode 100644 index 00000000..1465b52f --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/service/ImageService.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.ImageEntity; +import com.espark.adarsh.repository.ImageRepository; +import com.espark.adarsh.util.ImageUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.Optional; + +@Service +public class ImageService { + + @Autowired + ImageRepository imageRepository; + + public String uploadImage(MultipartFile file) throws IOException { + + ImageEntity imageData = imageRepository.save(ImageEntity.builder() + .name(file.getOriginalFilename()) + .type(file.getContentType()) + .imageData(ImageUtils.compressImage(file.getBytes())).build()); + if (imageData != null) { + return "file uploaded successfully : " + file.getOriginalFilename(); + } + return null; + } + + public byte[] downloadImage(String fileName) { + Optional dbImageData = imageRepository.findByName(fileName); + byte[] images = ImageUtils.decompressImage(dbImageData.get().getImageData()); + return images; + } +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/util/ImageUtils.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/util/ImageUtils.java new file mode 100644 index 00000000..77173123 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/util/ImageUtils.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.util; + +import lombok.extern.slf4j.Slf4j; + +import java.io.ByteArrayOutputStream; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +@Slf4j +public class ImageUtils { + + + public static byte[] compressImage(byte[] data) { + Deflater deflater = new Deflater(); + deflater.setLevel(Deflater.BEST_COMPRESSION); + deflater.setInput(data); + deflater.finish(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); + byte[] tmp = new byte[4 * 1024]; + while (!deflater.finished()) { + int size = deflater.deflate(tmp); + outputStream.write(tmp, 0, size); + } + try { + outputStream.close(); + } catch (Exception ignored) { + log.error(ignored.getLocalizedMessage()); + } + return outputStream.toByteArray(); + } + + + public static byte[] decompressImage(byte[] data) { + Inflater inflater = new Inflater(); + inflater.setInput(data); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); + byte[] tmp = new byte[4 * 1024]; + try { + while (!inflater.finished()) { + int count = inflater.inflate(tmp); + outputStream.write(tmp, 0, count); + } + outputStream.close(); + } catch (Exception ignored) { + log.error(ignored.getLocalizedMessage()); + } + return outputStream.toByteArray(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/web/ImageController.java b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/web/ImageController.java new file mode 100644 index 00000000..aa51b432 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/java/com/espark/adarsh/web/ImageController.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.ImageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@RestController +public class ImageController { + + @Autowired + private ImageService service; + + @PostMapping("/image") + public ResponseEntity uploadImage(@RequestParam("image") MultipartFile file) throws IOException { + String uploadImage = service.uploadImage(file); + return ResponseEntity.status(HttpStatus.OK) + .body(uploadImage); + } + + @GetMapping("/image/{fileName}") + public ResponseEntity downloadImage(@PathVariable String fileName){ + byte[] imageData=service.downloadImage(fileName); + return ResponseEntity.status(HttpStatus.OK) + .contentType(MediaType.valueOf("image/png")) + .body(imageData); + + } +} diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/main/resources/application.yaml b/APPLICATIONS/spring-boot-file-upload-rest/src/main/resources/application.yaml new file mode 100644 index 00000000..72a84496 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/main/resources/application.yaml @@ -0,0 +1,22 @@ + +server: + port: 9090 + servlet: + context-path: /api + +spring: + application: + name: spring-boot-rest-file-upload + h2: + console: + enabled: true + datasource: + url: jdbc:h2:mem:testdb + username: root + password: root + driver-class-name: org.h2.Driver + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-file-upload-rest/src/test/java/com/espark/adarsh/SpringBootFileUploadRestApplicationTests.java b/APPLICATIONS/spring-boot-file-upload-rest/src/test/java/com/espark/adarsh/SpringBootFileUploadRestApplicationTests.java new file mode 100644 index 00000000..cffeed61 --- /dev/null +++ b/APPLICATIONS/spring-boot-file-upload-rest/src/test/java/com/espark/adarsh/SpringBootFileUploadRestApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringBootFileUploadRestApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-hystrix/pom.xml b/APPLICATIONS/spring-boot-hystrix/pom.xml new file mode 100644 index 00000000..356f6c15 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + com.espark.adarsh + spring-boot-hystrix + 0.0.1-SNAPSHOT + + pom + + spring-boot-hystrix + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + springboot-eureka + springboot-service + springboot-service-client + springboot-hystrix-dashboard + + + + UTF-8 + UTF-8 + Finchley.RC2 + 1.8 + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-eureka/pom.xml b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/pom.xml new file mode 100644 index 00000000..dbf5d57d --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/pom.xml @@ -0,0 +1,29 @@ + + + + spring-boot-hystrix + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + springboot-eureka + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/java/com/espark/adarsh/EurekaServer.java b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/java/com/espark/adarsh/EurekaServer.java new file mode 100644 index 00000000..fd88ef97 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/java/com/espark/adarsh/EurekaServer.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + + +@SpringBootApplication +@EnableEurekaServer +public class EurekaServer { + + public static void main(String[] args) { + SpringApplication.run(EurekaServer.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/resources/application.yml b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/resources/application.yml new file mode 100644 index 00000000..562b56f7 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-eureka/src/main/resources/application.yml @@ -0,0 +1,11 @@ +server: + port: ${PORT:8761} + +eureka: + instance: + hostname: localhost + client: + registerWithEureka: false + fetchRegistry: false + server: + enableSelfPreservation: false diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/pom.xml b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/pom.xml new file mode 100644 index 00000000..c0da9b7c --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/pom.xml @@ -0,0 +1,68 @@ + + + + spring-boot-hystrix + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + springboot-hystrix-dashboard + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix-dashboard + + + + org.springframework.cloud + spring-cloud-commons + + + + org.springframework.cloud + spring-cloud-netflix-core + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.cloud + spring-cloud-netflix-turbine + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..30cfbf7e --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,19 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; +import org.springframework.cloud.netflix.turbine.EnableTurbine; + +@EnableHystrixDashboard +@EnableEurekaClient +@SpringBootApplication +@EnableTurbine +@EnableAutoConfiguration +public class ApplicationMain { + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/resources/application.properties b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/resources/application.properties new file mode 100644 index 00000000..df3c9732 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-hystrix-dashboard/src/main/resources/application.properties @@ -0,0 +1,19 @@ +server.port=8090 +spring.application.name=springboot-hystrix-dashboard + +management.endpoint.health.enabled=true +#management.endpoints.jmx.exposure.include=* +management.endpoints.web.exposure.include=* +#management.endpoints.web.base-path=/actuator +management.endpoints.web.base-path=/ +management.endpoints.web.cors.allowed-origins=true +management.endpoint.health.show-details=always +eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka} +eureka.instance.lease-expiration-duration-in-seconds=5 +eureka.instance.lease-renewal-interval-in-seconds=5 + +turbine.aggregator.cluster-config=default +turbine.app-config=SPRINGBOOT-SERVICE-CLIENT +turbine.cluster-name-expression= new String("default") +#turbine.combine-host-port=true +#turbine.instanceUrlSuffix.default=actuator/hystrix.stream diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/pom.xml b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/pom.xml new file mode 100644 index 00000000..2d07dc5e --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/pom.xml @@ -0,0 +1,75 @@ + + + + spring-boot-hystrix + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + springboot-service-client + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + + + + + org.springframework.cloud + spring-cloud-starter-feign + 1.4.5.RELEASE + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + org.springframework.cloud + spring-cloud-commons + + + + org.springframework.cloud + spring-cloud-netflix-core + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..7280a6c2 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,17 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; +import org.springframework.cloud.openfeign.EnableFeignClients; + +@EnableFeignClients +@EnableCircuitBreaker +@EnableEurekaClient +@SpringBootApplication +public class ApplicationMain { + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientFallback.java b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientFallback.java new file mode 100644 index 00000000..9ce679d4 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientFallback.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.client; + +import org.springframework.stereotype.Component; + +@Component +public class ClientFallback implements ClientService{ + + @Override + public String greeting(String username){ + return String.format("Hello From Fallback %s!\n", username); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientService.java b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientService.java new file mode 100644 index 00000000..2be4e739 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/client/ClientService.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.client; + + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +@FeignClient( + name = "springboot-service" + ,fallback = ClientFallback.class +) +public interface ClientService { + + @GetMapping("/message/{username}") + public String greeting(@PathVariable("username") String username); +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..ea713e8c --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.client.ClientService; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +@RestController +public class ApplicationController { + + + @Autowired + private ClientService clientService; + + @GetMapping("/message/{username}") + public String greeting(@PathVariable("username") String username) { + return this.clientService.greeting(username); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/resources/application.properties b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/resources/application.properties new file mode 100644 index 00000000..75dd0a61 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service-client/src/main/resources/application.properties @@ -0,0 +1,47 @@ +server.port=8080 +spring.application.name=springboot-service-cient + +eureka.instance.lease-expiration-duration-in-seconds=5 +eureka.instance.lease-renewal-interval-in-seconds=5 +eureka.client.service-url.default-zone=http://localhost:8761/eureka + +fegin.hystrix.enable=true + +springboot-service.ribbon.listOfServers=http://localhost:9090 + +eureka.client.fetchRegistry=true +management.endpoint.health.enabled=true +management.endpoints.web.exposure.include=*\ +management.endpoints.web.base-path=/actuator +management.endpoints.web.cors.allowed-origins=true +management.endpoint.health.show-details=always + +#turbine.aggregator.clusterConfig=SPRINGBOOT-SERVICE +#turbine.appConfig=SPRINGBOOT-SERVICE +#turbine.aggregator.cluster-config=default +#turbine.cluster-name-expression= new String("default") +#turbine.combine-host-port=true +#turbine.instanceUrlSuffix.default=actuator/hystrix.stream + + + +#feign.hystrix.enabled=true +hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=1500 + +# Max number of retries on the same server (excluding the first try) +springboot-service.ribbon.MaxAutoRetries=0 + +# Max number of next servers to retry (excluding the first server) +springboot-service.ribbon.MaxAutoRetriesNextServer=1 + +# Whether all operations can be retried for this client +springboot-service.ribbon.OkToRetryOnAllOperations=true + +# Interval to refresh the server list from the source +springboot-service.ribbon.ServerListRefreshInterval=100 + +# Connect timeout used by Apache HttpClient +springboot-service.ribbon.ConnectTimeout=200 + +# Read timeout used by Apache HttpClient +springboot-service.ribbon.ReadTimeout=200 diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service/pom.xml b/APPLICATIONS/spring-boot-hystrix/springboot-service/pom.xml new file mode 100644 index 00000000..98873201 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service/pom.xml @@ -0,0 +1,42 @@ + + + + spring-boot-hystrix + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + springboot-service + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..fe425da4 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@EnableEurekaClient +@SpringBootApplication +public class ApplicationMain { + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..6dbb86b6 --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.controller; + +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.RestController; + +@RestController +public class ApplicationController { + + @GetMapping("/message/{username}") + public String greeting(@PathVariable("username") String username) { + return String.format("Hello %s!\n", username); + } +} diff --git a/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/resources/application.properties b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/resources/application.properties new file mode 100644 index 00000000..e40d964c --- /dev/null +++ b/APPLICATIONS/spring-boot-hystrix/springboot-service/src/main/resources/application.properties @@ -0,0 +1,22 @@ +server.port=9090 +spring.application.name=springboot-service + +eureka.instance.lease-expiration-duration-in-seconds=5 +eureka.instance.lease-renewal-interval-in-seconds=5 +eureka.client.service-url.default-zone=http://localhost:8761/eureka + +ribbon.eureka.enabled=true +management.endpoint.health.enabled=true +#management.endpoints.jmx.exposure.include=* +management.endpoints.web.exposure.include=* +#management.endpoints.web.base-path=/actuator +#management.endpoints.web.cors.allowed-origins=true +#management.endpoint.health.show-details=always + +#turbine.aggregator.clusterConfig=SPRINGBOOT-SERVICE +#turbine.appConfig=SPRINGBOOT-SERVICE +#turbine.aggregator.cluster-config=default +#turbine.cluster-name-expression= new String("default") +#turbine.combine-host-port=true +#turbine.instanceUrlSuffix.default: actuator/hystrix.stream + diff --git a/APPLICATIONS/spring-boot-liquidbase/.gitignore b/APPLICATIONS/spring-boot-liquidbase/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-liquidbase/README.md b/APPLICATIONS/spring-boot-liquidbase/README.md new file mode 100644 index 00000000..306b619a --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/README.md @@ -0,0 +1,9 @@ +# To build the application +* $ mvn clean package + +# To run the Application +* $ mvn spring-boot:run + +# log into the homepage of db +* http://localhost:8080/h2-console +* username, pwd , dburl and db driver class is mentioned in application.properties file \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-liquidbase/pom.xml b/APPLICATIONS/spring-boot-liquidbase/pom.xml new file mode 100644 index 00000000..8bff31ac --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.5.5 + + + com.espark.adarsh + spring-boot-liquidbase + 0.0.1-SNAPSHOT + spring-boot-liquidbase + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.liquibase + liquibase-core + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..5b2ce322 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..3973ecd6 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("sql/create_schema.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/resources/application.properties b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/application.properties new file mode 100644 index 00000000..58746746 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/application.properties @@ -0,0 +1,21 @@ + +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.generate-ddl=false +spring.jpa.hibernate.ddl-auto=none + +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml +spring.liquibase.drop-first=true +# spring.datasource.url=jdbc:h2:~/liquibase;DB_CLOSE_ON_EXIT=FALSE + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/resources/db/changelog/db.changelog-master.xml b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 00000000..ca80d29c --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/create_schema.sql b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/create_schema.sql new file mode 100644 index 00000000..91a99377 --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/create_schema.sql @@ -0,0 +1,13 @@ +DROP TABLE IF EXISTS employee; +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee ( first_name, last_name, career) +VALUES ('adarsh', 'kumar', 'It') +,('radha', 'singh', 'IT') +,( 'sonu', 'singh', 'IT') +,( 'amit', 'kumar', 'Finance'); diff --git a/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/insert_data.sql b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/insert_data.sql new file mode 100644 index 00000000..5ef06e2f --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/main/resources/sql/insert_data.sql @@ -0,0 +1,5 @@ +INSERT INTO employee ( first_name, last_name, career) +VALUES ('adarsh1', 'kumar', 'It') +,('radha1', 'singh', 'IT') +,( 'sonu1', 'singh', 'IT') +,( 'amit1', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-liquidbase/src/test/java/com/espark/adarsh/SpringBootLiquidbaseApplicationTests.java b/APPLICATIONS/spring-boot-liquidbase/src/test/java/com/espark/adarsh/SpringBootLiquidbaseApplicationTests.java new file mode 100644 index 00000000..7c6eb1cc --- /dev/null +++ b/APPLICATIONS/spring-boot-liquidbase/src/test/java/com/espark/adarsh/SpringBootLiquidbaseApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringBootLiquidbaseApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/.gitignore b/APPLICATIONS/spring-boot-prototype-self-destruction/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/README.md b/APPLICATIONS/spring-boot-prototype-self-destruction/README.md new file mode 100644 index 00000000..4d573a50 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/README.md @@ -0,0 +1,13 @@ +# spring-boot-prototype-self-destruction + +### To Build the Appliation +For further reference, please consider the following sections: +* mvn clean package + +### To run the Application +The following guides illustrate how to use some features concretely: +* mvn spring-boot:run + + +### Call the ulr +* http://localhost:8080/instantiate/1000 diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/pom.xml b/APPLICATIONS/spring-boot-prototype-self-destruction/pom.xml new file mode 100644 index 00000000..96392005 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + com.espark.adarsh + spring-boot-prototype-self-destruction + 0.0.1-SNAPSHOT + spring-boot-prototype-self-destruction + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..0c70931f --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,17 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +@EnableAsync +@EnableScheduling +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/bean/PrototypeSampleBean.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/bean/PrototypeSampleBean.java new file mode 100644 index 00000000..59d81482 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/bean/PrototypeSampleBean.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.util.PrototypeMarker; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; + +@Slf4j +public class PrototypeSampleBean implements PrototypeMarker, DisposableBean { + + private boolean protoType = true; + + public PrototypeSampleBean() { + log.info("PrototypeSampleBean Object Created {}", this.hashCode()); + } + + @Override + public void setProtoType(boolean protoTypeValue) { + this.protoType = protoTypeValue; + } + + @Override + public boolean getProtoType() { + return this.protoType; + } + + @Override + public void destroy() throws Exception { + log.info("destroyed method called {}", this.hashCode()); + } +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java new file mode 100644 index 00000000..72ef95ca --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.bean.PrototypeSampleBean; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +@Configuration +public class ApplicationConfiguration { + + @Bean("prototypeSampleBean") + @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public PrototypeSampleBean getPrototypeSampleBean() { + return new PrototypeSampleBean(); + } +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..5a0ca371 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.PrototypeSampleBean; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.Arrays; + +import static java.lang.Thread.sleep; + +@Slf4j +@Async +@Service +public class ApplicationService { + + @Autowired + ApplicationContext applicationContext; + + public void operator(Integer number) throws InterruptedException { + for (int i = 0; i < number; i++) { + PrototypeSampleBean prototypeSampleBean = applicationContext.getBean(PrototypeSampleBean.class); + sleep(500); + prototypeSampleBean.setProtoType(false); + } + + + String[] allBeanNames = applicationContext.getBeanDefinitionNames(); + Arrays.stream(allBeanNames).sequential().forEach(bean -> log.info(bean)); + } +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/DestroyPrototypeBeansPostProcessor.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/DestroyPrototypeBeansPostProcessor.java new file mode 100644 index 00000000..d77ef42d --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/DestroyPrototypeBeansPostProcessor.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.stereotype.Component; +import java.util.LinkedList; +import java.util.List; + +@Slf4j +@Component +public class DestroyPrototypeBeansPostProcessor implements BeanPostProcessor, BeanFactoryAware, DisposableBean { + + private BeanFactory beanFactory; + + private final static List prototypeBeans = new LinkedList<>(); + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (beanFactory.isPrototype(beanName)) { + synchronized (prototypeBeans) { + prototypeBeans.add(bean); + } + } + return bean; + } + + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + + @Override + public void destroy() throws Exception { + synchronized (prototypeBeans) { + for (Object bean : prototypeBeans) { + if (bean instanceof DisposableBean) { + DisposableBean disposable = (DisposableBean) bean; + try { + disposable.destroy(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + prototypeBeans.clear(); + } + } + + public static List getPrototypeBeans() { + return prototypeBeans; + } +} \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeBeanDestructorJob.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeBeanDestructorJob.java new file mode 100644 index 00000000..551cc16d --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeBeanDestructorJob.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.util; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +public class PrototypeBeanDestructorJob { + + @Scheduled(fixedRate = 1000) + public void prototypeClearing() { + List protoTypeBeanList = DestroyPrototypeBeansPostProcessor.getPrototypeBeans(); + protoTypeBeanList.stream().forEach(bean -> { + if (bean instanceof PrototypeMarker && !((PrototypeMarker) bean).getProtoType()) { + if (bean instanceof DisposableBean) { + DisposableBean disposable = (DisposableBean) bean; + try { + log.info("clear prototype {}", bean.hashCode()); + disposable.destroy(); + } catch (Exception e) { + log.error(e.getLocalizedMessage()); + } + } + } + }); + protoTypeBeanList.removeIf(bean -> bean instanceof PrototypeMarker && !((PrototypeMarker) bean).getProtoType()); + } +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeMarker.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeMarker.java new file mode 100644 index 00000000..3f686548 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/util/PrototypeMarker.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.util; + +public interface PrototypeMarker { + + void setProtoType(boolean protoTypeValue); + + boolean getProtoType(); +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..54ed347b --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.PrototypeSampleBean; +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + + +@RestController +public class ApplicationController { + + @Autowired + ApplicationService applicationService; + + @GetMapping("/instantiate/{number}") + public String operator(@PathVariable("number") Integer number) throws InterruptedException { + applicationService.operator(number); + return "operation started with number " + number; + } +} diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/resources/application.properties b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/spring-boot-prototype-self-destruction/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/spring-boot-prototype-self-destruction/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/spring-boot-prototype-self-destruction/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/.gitignore b/APPLICATIONS/spring-boot-reacjs-monolithic/.gitignore new file mode 100644 index 00000000..d8fe1a56 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/.gitignore @@ -0,0 +1,45 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +/reactjs-ui/build/ +/reactjs-ui/node/ +/reactjs-ui/node/ +/reactjs-ui/node_modules/ +/reactjs-ui/package-lock.json +/reactjs-ui/target/ +/reactjs-ui/yarn.lock + +.DS_Store +*.DS_Store +/*.DS_Store + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/README.md b/APPLICATIONS/spring-boot-reacjs-monolithic/README.md new file mode 100644 index 00000000..23f46e7e --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/README.md @@ -0,0 +1,239 @@ +# spring-boot-reactjs-monolithic + +--- + +## STEP TO CREATE PROJECT STRUCTURE +* create `spring-boot-reactjs-monolithic` + * create a pom file with below tags +```` + + + + 4.0.0 + pom + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + com.espark.adarsh + springboot-reacjs-monolithic + 0.0.1-SNAPSHOT + springboot-reacjs-monolithic + Demo project for Spring Boot + + + springboot-services + reactjs-ui + + + +```` + +* create `springboot-services` maven module inside the `spring-boot-reactjs-monolithic` project + * create a pom file with below tags +```` + + + + springboot-reacjs-monolithic + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + springboot-services + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + maven-resources-plugin + + + copy-resources + validate + copy-resources + + ${project.build.directory}/classes/resources/ + + + ${project.parent.basedir}/reactjs-ui/build/ + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + +```` +* create `reactjs-ui` maven module inside the `spring-boot-reactjs-monolithic` project + * execute the below cmd inside the main project `spring-boot-ractjs-monolithic` + * spring-boot-ractjs-monolithic $ create-react-app reactjs-ui +```` +Installing packages. This might take a couple of minutes. +Installing react, react-dom, and react-scripts with cra-template... +```` + * `reactjs-ui/src/App.js` modify the code +```` +function App() { + return ( +
+
+ logo +

+

WELCOME TO THE ESPARK REACTJS

+

+
+
+ ); +} +```` + * change the test case for the App.js + * reactjs-ui/src/App.test.js +```` +import { render, screen } from '@testing-library/react'; +import App from './App'; + +test('renders learn react link', () => { + render(); + const linkElement = screen.getByText(/WELCOME TO THE ESPARK REACTJS/i); + expect(linkElement).toBeInTheDocument(); +}); + +```` + * To test the reactjs application running + * npm start + * http://localhost:3000 + * create a pom file with below tags +```` + + + + springboot-reacjs-monolithic + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + 0.0.1-SNAPSHOT + reactjs-ui + + + v14.18.0 + v1.12.1 + + + + + com.github.eirslett + frontend-maven-plugin + 1.12.1 + + ./ + v14.7.0 + 6.14.8 + ${node.version} + ${yarn.version} + + + + install node + + install-node-and-yarn + + + + yarn install + + yarn + + generate-resources + + + yarn test + + yarn + + test + + test + + true + + + + + yarn build + + yarn + + compile + + build + + + + + + + +```` + +### Test only the reactjs +* spring-boot-reactjs-monolithic $ cd reactjs-ui +* reactjs-ui $ npm start + +### To Build the code +* spring-boot-reactjs-monolithic $ mvn clean package +* spring-boot-reactjs-monolithic $ java -jar ./springboot-services/target/springboot-services-0.0.1-SNAPSHOT.jar +* to access ui page `http://localhost:8080/` + + +### To access the web api +* `http://localhost:8080/wish` \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/pom.xml b/APPLICATIONS/spring-boot-reacjs-monolithic/pom.xml new file mode 100644 index 00000000..40263a62 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/pom.xml @@ -0,0 +1,27 @@ + + + + 4.0.0 + pom + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + com.espark.adarsh + spring-boot-reacjs-monolithic + 0.0.1-SNAPSHOT + spring-boot-reacjs-monolithic + Demo project for Spring Boot + + + springboot-services + reactjs-ui + + + diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/.gitignore b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/.gitignore new file mode 100644 index 00000000..4d29575d --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/README.md b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/README.md new file mode 100644 index 00000000..58beeacc --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/README.md @@ -0,0 +1,70 @@ +# Getting Started with Create React App + +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.\ +Open [http://localhost:3000](http://localhost:3000) to view it in your browser. + +The page will reload when you make changes.\ +You may also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.\ +See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.\ +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.\ +Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can't go back!** + +If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. + +You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). + +### Code Splitting + +This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) + +### Analyzing the Bundle Size + +This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) + +### Making a Progressive Web App + +This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) + +### Advanced Configuration + +This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) + +### Deployment + +This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) + +### `npm run build` fails to minify + +This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/package.json b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/package.json new file mode 100644 index 00000000..a115a4df --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/package.json @@ -0,0 +1,38 @@ +{ + "name": "reactjs-ui", + "version": "0.1.0", + "private": true, + "dependencies": { + "@testing-library/jest-dom": "^5.16.2", + "@testing-library/react": "^12.1.2", + "@testing-library/user-event": "^13.5.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "react-scripts": "5.0.0", + "web-vitals": "^2.1.4" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/pom.xml b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/pom.xml new file mode 100644 index 00000000..d89ac9b1 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/pom.xml @@ -0,0 +1,79 @@ + + + + spring-boot-reacjs-monolithic + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + 0.0.1-SNAPSHOT + reactjs-ui + + + v14.18.0 + v1.12.1 + + + + + ./build/ + static + + + + + com.github.eirslett + frontend-maven-plugin + 1.12.1 + + ./ + v14.7.0 + 6.14.8 + ${node.version} + ${yarn.version} + + + + install node + + install-node-and-yarn + + + + yarn install + + yarn + + generate-resources + + + yarn test + + yarn + + test + + test + + true + + + + + yarn build + + yarn + + compile + + build + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/favicon.ico b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/favicon.ico new file mode 100644 index 00000000..a11777cc Binary files /dev/null and b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/favicon.ico differ diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/index.html b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/index.html new file mode 100644 index 00000000..aa069f27 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo192.png b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo192.png new file mode 100644 index 00000000..fc44b0a3 Binary files /dev/null and b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo192.png differ diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo512.png b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo512.png new file mode 100644 index 00000000..a4e47a65 Binary files /dev/null and b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/logo512.png differ diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/manifest.json b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/manifest.json new file mode 100644 index 00000000..080d6c77 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/robots.txt b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/robots.txt new file mode 100644 index 00000000..e9e57dc4 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.css b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.css new file mode 100644 index 00000000..74b5e053 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.css @@ -0,0 +1,38 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; + pointer-events: none; +} + +@media (prefers-reduced-motion: no-preference) { + .App-logo { + animation: App-logo-spin infinite 20s linear; + } +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #61dafb; +} + +@keyframes App-logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.js b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.js new file mode 100644 index 00000000..a769746f --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.js @@ -0,0 +1,16 @@ +import logo from './logo.svg'; +import './App.css'; + +function App() { + return ( +
+
+ logo +

+

WELCOME TO THE ESPARK REACTJS

+

+
+
+ ); +} +export default App; diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.test.js b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.test.js new file mode 100644 index 00000000..f500cf26 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/App.test.js @@ -0,0 +1,8 @@ +import { render, screen } from '@testing-library/react'; +import App from './App'; + +test('renders learn react link', () => { + render(); + const linkElement = screen.getByText(/WELCOME TO THE ESPARK REACTJS/i); + expect(linkElement).toBeInTheDocument(); +}); diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.css b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.css new file mode 100644 index 00000000..ec2585e8 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.js b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.js new file mode 100644 index 00000000..ef2edf8e --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/index.js @@ -0,0 +1,17 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import './index.css'; +import App from './App'; +import reportWebVitals from './reportWebVitals'; + +ReactDOM.render( + + + , + document.getElementById('root') +); + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals(); diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/logo.svg b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/logo.svg new file mode 100644 index 00000000..9dfc1c05 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/reportWebVitals.js b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/reportWebVitals.js new file mode 100644 index 00000000..5253d3ad --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/reportWebVitals.js @@ -0,0 +1,13 @@ +const reportWebVitals = onPerfEntry => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } +}; + +export default reportWebVitals; diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/setupTests.js b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/setupTests.js new file mode 100644 index 00000000..8f2609b7 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/reactjs-ui/src/setupTests.js @@ -0,0 +1,5 @@ +// jest-dom adds custom jest matchers for asserting on DOM nodes. +// allows you to do things like: +// expect(element).toHaveTextContent(/react/i) +// learn more: https://github.com/testing-library/jest-dom +import '@testing-library/jest-dom'; diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/pom.xml b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/pom.xml new file mode 100644 index 00000000..cc5bd509 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/pom.xml @@ -0,0 +1,80 @@ + + + + spring-boot-reacjs-monolithic + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + 0.0.1-SNAPSHOT + springboot-services + + + 1.8 + + + + + + com.espark.adarsh + reactjs-ui + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + maven-resources-plugin + + + copy-resources + validate + copy-resources + + ${project.build.directory}/classes/resources/ + + + ${project.parent.basedir}/reactjs-ui/build/ + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java new file mode 100644 index 00000000..dea70077 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/config/ApplicationWebConfig.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.resource.PathResourceResolver; + +import java.io.IOException; + +@Configuration +public class ApplicationWebConfig implements WebMvcConfigurer { + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + + registry.addResourceHandler("/", "/*.html", "/*.js", "/*.css", "/*.png", "/*.ico", "*.svg", "*.json") + .addResourceLocations("classpath:/static/") + .resourceChain(true) + .addResolver(new PathResourceResolver() { + @Override + protected Resource getResource(String resourcePath, Resource location) throws IOException { + Resource requestedResource = location.createRelative(resourcePath); + return requestedResource.exists() && requestedResource.isReadable() ? requestedResource + : new ClassPathResource("/static/index.html"); + } + }); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..62bb1aee --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalTime; +import java.util.HashMap; +import java.util.Map; + +@RestController +public class ApplicationController { + + @GetMapping("/wish") + public Map getWishMessage(){ + return new HashMap(){ + { + put("message","welcome to espark "); + put("time", LocalTime.now().toString()); + } + }; + } +} diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/resources/application.properties b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/spring-boot-reacjs-monolithic/springboot-services/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-retry/.gitignore b/APPLICATIONS/spring-boot-retry/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/spring-boot-retry/README.md b/APPLICATIONS/spring-boot-retry/README.md new file mode 100644 index 00000000..346f8a52 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/README.md @@ -0,0 +1,13 @@ +# spring-boot-retry +--- + +## To Build the code +* mvn clean package + +## To run +* mvn spring-boot:run + +## Api endpoint +* curl http://localhost:8080/wish/DELAY/adarsh +* curl http://localhost:8080/wish/NODELAY/adarsh +* curl http://localhost:8080/wish/ERROR/adarsh diff --git a/APPLICATIONS/spring-boot-retry/pom.xml b/APPLICATIONS/spring-boot-retry/pom.xml new file mode 100644 index 00000000..a3057d4d --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.0.3 + + + com.espark.adarsh + spring-boot-retry + 0.0.1-SNAPSHOT + spring-boot-retry + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.retry + spring-retry + + + + org.springframework + spring-aspects + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/SpringBootRetryApplication.java b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/SpringBootRetryApplication.java new file mode 100644 index 00000000..c16c329c --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/SpringBootRetryApplication.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.retry.annotation.EnableRetry; + +@EnableRetry +@SpringBootApplication +public class SpringBootRetryApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRetryApplication.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..6e8e2614 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Service +public class ApplicationService { + + RestTemplate restTemplate = new RestTemplate(); + + + // Backoff is used to define the delay time between each retry call. + // multiplier is used to increase delay time 2 times after each retry call. + @Retryable(maxAttempts = 2, backoff = @Backoff(delay = 1000, multiplier = 2)) + public Map wish(String type, String name){ + log.info("request for remote server "); + return restTemplate.getForObject("http://localhost:8080/message/"+name+"/"+type, HashMap.class); + } + + @Recover + public Map backupRecoverWish(String type, String name){ + log.info("backup recover executed "); + return new HashMap(){ + { + put("msg","welcome to espark locally"); + put("name",name); + } + }; + } + +} diff --git a/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/RemoteApplicationService.java b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/RemoteApplicationService.java new file mode 100644 index 00000000..df9bf08d --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/service/RemoteApplicationService.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Service +public class RemoteApplicationService { + + public Map wish(String name, String type) throws InterruptedException { + if (type.equals("DELAY")) { + log.info("delay executed "); + Thread.currentThread().sleep(10000); + return new HashMap() { + { + put("msg", "welcome to espark "); + put("name", name); + } + }; + } + if (type.equals("ERROR")) { + log.info("error executed "); + throw new RuntimeException("Server not willing to respond ..."); + } else { + log.info("normal executed "); + return new HashMap() { + { + put("msg", "welcome to espark "); + put("name", name); + } + }; + } + } +} diff --git a/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..b9909918 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +public class ApplicationController { + + @Autowired + ApplicationService applicationService; + + @GetMapping("/wish/{type}/{name}") + public Map wish(@PathVariable("type") String type, @PathVariable("name") String name) { + return this.applicationService.wish(type, name); + } + +} diff --git a/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/RemoteApplicationController.java b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/RemoteApplicationController.java new file mode 100644 index 00000000..a9589606 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/java/com/espark/adarsh/web/RemoteApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.RemoteApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +public class RemoteApplicationController { + + + @Autowired + RemoteApplicationService remoteApplicationService; + + @GetMapping("/message/{name}/{type}") + public Map wish(@PathVariable("name") String name,@PathVariable("type") String type) throws InterruptedException { + return this.remoteApplicationService.wish(name,type); + } +} diff --git a/APPLICATIONS/spring-boot-retry/src/main/resources/application.properties b/APPLICATIONS/spring-boot-retry/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/spring-boot-retry/src/test/java/com/espark/adarsh/SpringBootRetryApplicationTests.java b/APPLICATIONS/spring-boot-retry/src/test/java/com/espark/adarsh/SpringBootRetryApplicationTests.java new file mode 100644 index 00000000..97919102 --- /dev/null +++ b/APPLICATIONS/spring-boot-retry/src/test/java/com/espark/adarsh/SpringBootRetryApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringBootRetryApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-boot-sonarquibe/.gitignore b/APPLICATIONS/spring-boot-sonarquibe/.gitignore new file mode 100644 index 00000000..72d0dbe0 --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/.gitignore @@ -0,0 +1,39 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +.DS_Stpre +/*.DS_Stpre + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +/sonarqube-* +*.zip \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-sonarquibe/README.md b/APPLICATIONS/spring-boot-sonarquibe/README.md new file mode 100644 index 00000000..322eda97 --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/README.md @@ -0,0 +1,194 @@ +# springboot-sonaarquibe + +--- + +### To Build +* mvn clean package + +### To run +* mvn spring-boot:run + +### To access api +* $ curl http://localhost:8080/api/wish/adarsh +``` +{"connected at ":"23:39","name":"welcome to espark adarsh"} +``` + +### To generate code coverage report by Jacoco +* mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install + +### To download sonar +* https://www.sonarqube.org/downloads/ +* opt for "Community Edition" + +### To Start sonarquibe server +* cd sonarqube-9.7.1.62043/bin/macosx-universal-64 +* to start sonarquibe server + * $ sh sonar.sh start +``` +/usr/bin/java +Starting SonarQube... +Started SonarQube. +``` + +* To login into the sonarquibe server + * http://localhost:9000 + * admin/admin + * changed pwd it will use for next time login after server start + +* create project manually +* provide the project name "spring-boot-sonarquibe" click on setup +* select the option locally for the code +* provided a token genenrate the projct token + * copy the token generated for the project name provided earleir "spring-boot-sonarquibe" +``` +Analyze "spring-boot-sonarquibe": sqp_02213f86c6ac6e4583098085732527045276796a +``` +* click on continue +* select run analysis on project maven option + * copy the maven cmd for the project +``` +mvn clean verify sonar:sonar \ + -Dsonar.projectKey=spring-boot-sonarquibe \ + -Dsonar.host.url=http://localhost:9000 \ + -Dsonar.login=sqp_02213f86c6ac6e4583098085732527045276796a +``` +* execute the mvn cmd on the project root dir from terminal + +``` +[INFO] --------------< com.espark.adarsh:spring-boot-sonarquibe >-------------- +[INFO] Building spring-boot-sonarquibe 0.0.1-SNAPSHOT +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- sonar-maven-plugin:3.8.0.2131:sonar (default-cli) @ spring-boot-sonarquibe --- +[INFO] User cache: /Users/us-guest/.sonar/cache +[INFO] SonarQube version: 9.7.1.62043 +[INFO] Default locale: "en_US", source code encoding: "UTF-8" +[INFO] Load global settings +[INFO] Load global settings (done) | time=94ms +[INFO] Server id: 147B411E-AYSOawLuTukZ56DVsNDw +[INFO] User cache: /Users/us-guest/.sonar/cache +[INFO] Load/download plugins +[INFO] Load plugins index +[INFO] Load plugins index (done) | time=63ms +[INFO] Load/download plugins (done) | time=154ms +[INFO] Process project properties +[INFO] Process project properties (done) | time=8ms +[INFO] Execute project builders +[INFO] Execute project builders (done) | time=1ms +[INFO] Project key: spring-boot-sonarquibe +[INFO] Base dir: /Users/us-guest/Downloads/spring-boot-sonarquibe +[INFO] Working dir: /Users/us-guest/Downloads/spring-boot-sonarquibe/target/sonar +[INFO] Load project settings for component key: 'spring-boot-sonarquibe' +[INFO] Load project settings for component key: 'spring-boot-sonarquibe' (done) | time=37ms +[WARNING] SCM provider autodetection failed. Please use "sonar.scm.provider" to define SCM of your project, or disable the SCM Sensor in the project settings. +[INFO] Load quality profiles +[INFO] Load quality profiles (done) | time=102ms +[INFO] Load active rules +[INFO] Load active rules (done) | time=1630ms +[INFO] Load analysis cache +[INFO] Load analysis cache (404) | time=8ms +[INFO] Load project repositories +[INFO] Load project repositories (done) | time=17ms +[INFO] Indexing files... +[INFO] Project configuration: +[INFO] 4 files indexed +[INFO] Quality profile for java: Sonar way +[INFO] Quality profile for xml: Sonar way +[INFO] ------------- Run sensors on module spring-boot-sonarquibe +[INFO] Load metrics repository +[INFO] Load metrics repository (done) | time=16ms +[INFO] Sensor JavaSensor [java] +[INFO] Configured Java source version (sonar.java.source): 8 +[INFO] JavaClasspath initialization +[INFO] JavaClasspath initialization (done) | time=14ms +[INFO] JavaTestClasspath initialization +[INFO] JavaTestClasspath initialization (done) | time=2ms +[INFO] Server-side caching is enabled. The Java analyzer will not try to leverage data from a previous analysis. +[INFO] Using ECJ batch to parse 2 Main java source files with batch size 214 KB. +[INFO] Starting batch processing. +[INFO] The Java analyzer cannot skip unchanged files in this context. A full analysis is performed for all files. +[INFO] 100% analyzed +[INFO] Batch processing: Done. +[INFO] Did not optimize analysis for any files, performed a full analysis for all 2 files. +[INFO] Using ECJ batch to parse 1 Test java source files with batch size 214 KB. +[INFO] Starting batch processing. +[INFO] 100% analyzed +[INFO] Batch processing: Done. +[INFO] Did not optimize analysis for any files, performed a full analysis for all 1 files. +[INFO] No "Generated" source files to scan. +[INFO] Sensor JavaSensor [java] (done) | time=888ms +[INFO] Sensor JaCoCo XML Report Importer [jacoco] +[INFO] 'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml +[INFO] Importing 1 report(s). Turn your logs in debug mode in order to see the exhaustive list. +[INFO] Sensor JaCoCo XML Report Importer [jacoco] (done) | time=15ms +[INFO] Sensor CSS Rules [javascript] +[INFO] No CSS, PHP, HTML or VueJS files are found in the project. CSS analysis is skipped. +[INFO] Sensor CSS Rules [javascript] (done) | time=1ms +[INFO] Sensor C# Project Type Information [csharp] +[INFO] Sensor C# Project Type Information [csharp] (done) | time=0ms +[INFO] Sensor C# Analysis Log [csharp] +[INFO] Sensor C# Analysis Log [csharp] (done) | time=18ms +[INFO] Sensor C# Properties [csharp] +[INFO] Sensor C# Properties [csharp] (done) | time=0ms +[INFO] Sensor SurefireSensor [java] +[INFO] parsing [/Users/us-guest/Downloads/spring-boot-sonarquibe/target/surefire-reports] +[INFO] Sensor SurefireSensor [java] (done) | time=85ms +[INFO] Sensor HTML [web] +[INFO] Sensor HTML [web] (done) | time=2ms +[INFO] Sensor XML Sensor [xml] +[INFO] 1 source file to be analyzed +[INFO] 1/1 source file has been analyzed +[INFO] Sensor XML Sensor [xml] (done) | time=149ms +[INFO] Sensor Text Sensor [text] +[INFO] 4 source files to be analyzed +[INFO] 4/4 source files have been analyzed +[INFO] Sensor Text Sensor [text] (done) | time=5ms +[INFO] Sensor VB.NET Project Type Information [vbnet] +[INFO] Sensor VB.NET Project Type Information [vbnet] (done) | time=1ms +[INFO] Sensor VB.NET Analysis Log [vbnet] +[INFO] Sensor VB.NET Analysis Log [vbnet] (done) | time=17ms +[INFO] Sensor VB.NET Properties [vbnet] +[INFO] Sensor VB.NET Properties [vbnet] (done) | time=1ms +[INFO] ------------- Run sensors on project +[INFO] Sensor Analysis Warnings import [csharp] +[INFO] Sensor Analysis Warnings import [csharp] (done) | time=1ms +[INFO] Sensor Zero Coverage Sensor +[INFO] Sensor Zero Coverage Sensor (done) | time=0ms +[INFO] Sensor Java CPD Block Indexer +[INFO] Sensor Java CPD Block Indexer (done) | time=11ms +[INFO] SCM Publisher No SCM system was detected. You can use the 'sonar.scm.provider' property to explicitly specify it. +[INFO] CPD Executor 2 files had no CPD blocks +[INFO] CPD Executor Calculating CPD for 0 files +[INFO] CPD Executor CPD calculation finished (done) | time=0ms +[INFO] Analysis report generated in 52ms, dir size=132.0 kB +[INFO] Analysis report compressed in 24ms, zip size=22.2 kB +[INFO] Analysis report uploaded in 30ms +[INFO] ANALYSIS SUCCESSFUL, you can find the results at: http://localhost:9000/dashboard?id=spring-boot-sonarquibe +[INFO] Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report +[INFO] More about the report processing at http://localhost:9000/api/ce/task?id=AYSOerN2q3cQPGRpKQoj +[INFO] Analysis total time: 5.107 s +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 13.422 s +[INFO] Finished at: 2022-11-19T00:01:56-06:00 +[INFO] ------------------------------------------------------------------------ +``` +* in log it will tell the url where we can find the project result +* http://localhost:9000/dashboard?id=spring-boot-sonarquibe +``` +[INFO] ANALYSIS SUCCESSFUL, you can find the results at: http://localhost:9000/dashboard?id=spring-boot-sonarquibe +[INFO] Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report +[INFO] More about the report processing at http://localhost:9000/api/ce/task?id=AYSOerN2q3cQPGRpKQoj +``` +* we can find the analysis for the project with all the issued present + + +* To stop sonarquibe server + * $ sh sonar.sh stop +``` +/usr/bin/java +Gracefully stopping SonarQube... +Stopped SonarQube. +``` \ No newline at end of file diff --git a/APPLICATIONS/spring-boot-sonarquibe/pom.xml b/APPLICATIONS/spring-boot-sonarquibe/pom.xml new file mode 100644 index 00000000..0fe37edb --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.5 + + + com.espark.adarsh + spring-boot-sonarquibe + 0.0.1-SNAPSHOT + spring-boot-sonarquibe + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + 3.8.0.2131 + + + org.jacoco + jacoco-maven-plugin + 0.8.5 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + + + + + diff --git a/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/SpringBootSonarquibeApplication.java b/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/SpringBootSonarquibeApplication.java new file mode 100644 index 00000000..845dbad7 --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/SpringBootSonarquibeApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSonarquibeApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSonarquibeApplication.class, args); + } + +} diff --git a/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..bc2afefd --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.web; + +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.RestController; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @GetMapping("/wish/{name}") + public Map getWish(@PathVariable("name") String name){ + LocalDateTime localDateTime = LocalDateTime.now(); + + return new HashMap() { + { + put("name","welcome to espark "+name); + put("connected at ",localDateTime.getHour()+":"+localDateTime.getMinute()); + } + }; + } +} diff --git a/APPLICATIONS/spring-boot-sonarquibe/src/main/resources/application.yml b/APPLICATIONS/spring-boot-sonarquibe/src/main/resources/application.yml new file mode 100644 index 00000000..78c9de1b --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/src/main/resources/application.yml @@ -0,0 +1,9 @@ +server: + port: 8080 + + +spring: + application: + name: spring-boot-sonarquibe + + diff --git a/APPLICATIONS/spring-boot-sonarquibe/src/test/java/com/espark/adarsh/SpringBootSonarquibeApplicationTests.java b/APPLICATIONS/spring-boot-sonarquibe/src/test/java/com/espark/adarsh/SpringBootSonarquibeApplicationTests.java new file mode 100644 index 00000000..2f3dac2e --- /dev/null +++ b/APPLICATIONS/spring-boot-sonarquibe/src/test/java/com/espark/adarsh/SpringBootSonarquibeApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringBootSonarquibeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/README.md b/APPLICATIONS/spring-data-jpa-postgresql/README.md new file mode 100644 index 00000000..11ea258c --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/README.md @@ -0,0 +1,2 @@ +# Spring Boot + Spring data JPA + PostgreSQL example + diff --git a/APPLICATIONS/spring-data-jpa-postgresql/document/help.txt b/APPLICATIONS/spring-data-jpa-postgresql/document/help.txt new file mode 100644 index 00000000..609461db --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/document/help.txt @@ -0,0 +1,9 @@ + + + +$ sudo -u postgres psql +$ sudo -u postgres createdb espark +$ sudo -u postgres createuser admin +$ sudo -u postgres psql +$ alter user admin with encrypted password 'admin'; +$ grant all privileges on database espark to admin ; \ No newline at end of file diff --git a/APPLICATIONS/spring-data-jpa-postgresql/pom.xml b/APPLICATIONS/spring-data-jpa-postgresql/pom.xml new file mode 100644 index 00000000..ecee15d5 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/pom.xml @@ -0,0 +1,113 @@ + + + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + spring-data-jpa-postgresql + spring-data-jpa-postgresql + 1.0 + + jar + spring-data-jpa-postgresql + + + 1.8 + true + true + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.apache.tomcat + tomcat-jdbc + + + + + + + com.ryantenney.metrics + metrics-spring + 3.1.3 + + + com.codahale.metrics + metrics-core + + + org.springframework + spring-core + + + + + + org.springframework.boot + spring-boot-starter-actuator + 2.2.6.RELEASE + + + + io.dropwizard.metrics + metrics-core + 3.1.2 + + + + io.dropwizard.metrics + metrics-annotation + 3.1.2 + + + + + org.projectlombok + lombok + 1.18.12 + + + + org.postgresql + postgresql + 42.2.12 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..a7f3e617 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,44 @@ +package com.espark.adarsh; + +import com.espark.adarsh.persistance.entity.Employee; +import com.espark.adarsh.persistance.repository.EmployeeRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain implements CommandLineRunner { + + private static final Logger log = LoggerFactory.getLogger(ApplicationMain.class); + + @Autowired + private EmployeeRepository repository; + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + + @Override + public void run(String... args) { + + log.info("StartApplication..."); + + repository.save(new Employee("adarsh")); + repository.save(new Employee("radha")); + repository.save(new Employee("amit")); + + System.out.println("\nfindAll()"); + repository.findAll().forEach(x -> System.out.println(x)); + + System.out.println("\nfindById(1L)"); + repository.findById(1l).ifPresent(x -> System.out.println(x)); + + System.out.println("\nfindByName('adarsh')"); + repository.findByName("Node").forEach(x -> System.out.println(x)); + + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/PostgresDatasourceConfigurer.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/PostgresDatasourceConfigurer.java new file mode 100644 index 00000000..332835a8 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/PostgresDatasourceConfigurer.java @@ -0,0 +1,95 @@ +package com.espark.adarsh.persistance; + + +import com.codahale.metrics.health.HealthCheckRegistry; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.sql.DataSource; +import java.util.Properties; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; + +@Slf4j +@Component +public class PostgresDatasourceConfigurer implements HealthIndicator { + + HikariDataSource ds; + + SpringDropwizardHealthCheckAdapter postgresPoolHealthCheck; + + @Autowired + HealthCheckRegistry healthCheckRegistry; + + @Value("${espark.driver.class}") + String datasourceClass; + + @Value("${espark.datasource.db.name}") + String databaseName; + + @Value("${espark.datasource.host.name}") + String databaseHost; + + @Value("${espark.datasource.host.port}") + String databasePort; + + @Value("${espark.datasource.username}") + String datasourceUsername; + + @Value("${espark.datasource.password}") + String datasourcePassword; + + @Value("${espark.datasource.pool.name}") + String poolName; + + @Value("${espark.datasource.db.schema}") + String schema; + + @PostConstruct + public void init() { + Properties props = new Properties(); + props.setProperty("dataSourceClassName", datasourceClass); + props.setProperty("dataSource.user", datasourceUsername); + props.setProperty("dataSource.password", datasourcePassword); + props.setProperty("dataSource.databaseName", databaseName); + props.setProperty("dataSource.serverName", databaseHost); + props.setProperty("dataSource.portNumber", databasePort); + props.setProperty("dataSource.currentSchema", schema); + + log.info("label=postgresDatasourceProperties user={} host={} port={} database={}", datasourceUsername, + databaseHost, databasePort, databaseName); + + HikariConfig config = new HikariConfig(props); + config.setPoolName(poolName); + config.addHealthCheckProperty("expected99thPercentileMs", "10"); + if (healthCheckRegistry != null) { + config.setHealthCheckRegistry(healthCheckRegistry); + postgresPoolHealthCheck = new SpringDropwizardHealthCheckAdapter(healthCheckRegistry, + String.format("%s.pool.ConnectivityCheck", poolName)); + } + ds = new HikariDataSource(config); + } + + @Bean + public DataSource getDataSource() { + return (DataSource) ds; + } + + @Override + public Health health() { + return postgresPoolHealthCheck.health(); + } + + @PreDestroy + public void destroy() { + if (ds != null) { + ds.close(); + } + } +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/SpringDropwizardHealthCheckAdapter.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/SpringDropwizardHealthCheckAdapter.java new file mode 100644 index 00000000..3596f6c5 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/SpringDropwizardHealthCheckAdapter.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.persistance; + + +import com.codahale.metrics.health.HealthCheck; +import com.codahale.metrics.health.HealthCheckRegistry; +import org.springframework.boot.actuate.health.Health; + +public class SpringDropwizardHealthCheckAdapter { + + + HealthCheckRegistry dropWizardHealthCheckRegistry; + String dropWizardHealthCheckName; + + public Health health() { + if (dropWizardHealthCheckRegistry != null && dropWizardHealthCheckName != null) { + HealthCheck.Result result = dropWizardHealthCheckRegistry.runHealthCheck(dropWizardHealthCheckName); + if (result.isHealthy()) { + return Health.up().withDetail("message", result.getMessage() != null ? result.getMessage() : "null") + .build(); + } + return Health.down(result.getError() instanceof Exception ? (Exception) result.getError() : + new Exception(result.getError())) + .withDetail("message", result.getMessage() != null ? result.getMessage() : "null").build(); + } + return null; + } + + + public SpringDropwizardHealthCheckAdapter( + HealthCheckRegistry dropWizardHealthCheckRegistry, String dropWizardHealthCheckName) { + this.dropWizardHealthCheckRegistry = dropWizardHealthCheckRegistry; + this.dropWizardHealthCheckName = dropWizardHealthCheckName; + } +} + diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/config/ApplicationConfiguration.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/config/ApplicationConfiguration.java new file mode 100644 index 00000000..e1e66ffc --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/config/ApplicationConfiguration.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.persistance.config; + +import com.codahale.metrics.health.HealthCheckRegistry; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfiguration { + + @Bean + HealthCheckRegistry dropWizardHealthCheckRegistry() { + return new HealthCheckRegistry(); + } + +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/entity/Employee.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/entity/Employee.java new file mode 100644 index 00000000..ccc2a436 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/entity/Employee.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.persistance.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String name; + + public Employee() { + } + + public Employee(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/repository/EmployeeRepository.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/repository/EmployeeRepository.java new file mode 100644 index 00000000..e98bda29 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/persistance/repository/EmployeeRepository.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.persistance.repository; + +import com.espark.adarsh.persistance.entity.Employee; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; + +public interface EmployeeRepository extends CrudRepository { + + List findByName(String name); + +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..f7e6ec66 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.persistance.entity.Employee; +import com.espark.adarsh.persistance.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + private EmployeeRepository repository; + + public Employee getEmployee(Long empId){ + return this.repository.findById(empId).get(); + } + + public List getEmployee(String empName){ + return this.repository.findByName(empName); + } +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..1fbc168a --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.persistance.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + public Employee getEmployee(Long empId){ + return this.employeeService.getEmployee(empId); + } + + public List getEmployee(String empName){ + return this.employeeService.getEmployee(empName); + } +} diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/main/resources/application.properties b/APPLICATIONS/spring-data-jpa-postgresql/src/main/resources/application.properties new file mode 100644 index 00000000..6251c91c --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/main/resources/application.properties @@ -0,0 +1,33 @@ +logging.level.org.springframework=INFO +logging.level.com.espark.adars=INFO +logging.level.com.zaxxer=DEBUG +logging.level.root=ERROR +logging.pattern.console=%-5level %logger{36} - %msg%n + + +## PostgreSQL +#spring.datasource.url=jdbc:postgresql://localhost:5432/postgres +##spring.datasource.username=admin +spring.datasource.password=admin + +#hikari connection pool +#spring.datasource.hikari.connectionTimeout=20000 +#spring.datasource.hikari.maximumPoolSize=5 + + +#drop n create table again, good for testing, comment this in production +spring.jpa.hibernate.ddl-auto=create +spring.jpa.show-sql=true + + +espark.driver.class=org.postgresql.ds.PGSimpleDataSource +espark.datasource.username=admin +espark.datasource.password=admin +espark.datasource.db.name=espark +espark.datasource.host.name=localhost +espark.datasource.host.port=5432 +espark.datasource.db.schema=public +espark.datasource.pool.name=espark + +espark.datasource.hikari.connectionTimeout=20000 +espark.datasource.hikari.maximumPoolSize=5 \ No newline at end of file diff --git a/APPLICATIONS/spring-data-jpa-postgresql/src/test/java/com/espark/adarsh/EmployeeRepositoryTest.java b/APPLICATIONS/spring-data-jpa-postgresql/src/test/java/com/espark/adarsh/EmployeeRepositoryTest.java new file mode 100644 index 00000000..4e9713a6 --- /dev/null +++ b/APPLICATIONS/spring-data-jpa-postgresql/src/test/java/com/espark/adarsh/EmployeeRepositoryTest.java @@ -0,0 +1,34 @@ +package com.espark.adarsh; + +import com.espark.adarsh.persistance.entity.Employee; +import com.espark.adarsh.persistance.repository.EmployeeRepository; +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +//@RunWith(SpringRunner.class) +//@SpringBootTest(classes = ApplicationMain.class) +public class EmployeeRepositoryTest { + + + /* @Autowired + private EmployeeRepository repository; + + @Test + public void testFindByName() { + repository.save(new Employee("C++")); + List books = repository.findByName("C++"); + assertEquals(1, books.size()); + Assertions.assertThat(books).extracting(Employee::getName).containsOnly("C++"); + }*/ + +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/.gitignore b/APPLICATIONS/spring-kafka-producer-consumer/.gitignore new file mode 100644 index 00000000..c158cc96 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/.gitignore @@ -0,0 +1,9 @@ +target/ +.settings/ +.springBeans +.classpath +.project +.idea/ +*.iml +build/ +.gradle/ diff --git a/APPLICATIONS/spring-kafka-producer-consumer/README.adoc b/APPLICATIONS/spring-kafka-producer-consumer/README.adoc new file mode 100644 index 00000000..3c7b71d8 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/README.adoc @@ -0,0 +1,41 @@ +## Getting Started +These instructions will show how to run kafka locally and how to install kafkacat, a tool to display messages in a kafka topic + +### Run kafka locally +In a terminal cd to the root of this project and run +``` +docker-compose up -d +``` +Check both kafka and zookeeper are running +``` +docker ps +``` +### Install kafkacat +Install kafkacat utility using the local package manager. + +``` +sudo apt-get install kafkacat +``` + +# Start up the Producer, from the root of the project + +[source, java] +---- +cd sample-spring-kafka-producer +../gradlew bootRun +---- + +# Start up the Consumer + +[source, java] +---- +cd sample-spring-kafka-consumer +../gradlew bootRun +---- + + +## At this point some sample messages can be generated using this endpoint: + +http://localhost:8080/generateWork?id=1&definition=thisIsCool + +The producer should print a message on the console that the Work unit has been dispatched and the consumer should receive and process the Work unit \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/build.gradle b/APPLICATIONS/spring-kafka-producer-consumer/build.gradle new file mode 100644 index 00000000..6a255134 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/build.gradle @@ -0,0 +1,35 @@ +buildscript { + ext { + springBootVersion = '1.5.4.RELEASE' + } + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + } +} + +subprojects { + + apply plugin: 'java' + apply plugin: 'org.springframework.boot' + + repositories { + mavenCentral() + jcenter() + maven { + url 'https://repo.spring.io/libs-snapshot' + } + } + + dependencies { + compile "org.apache.kafka:kafka-clients:0.10.2.0" + compile "org.springframework.kafka:spring-kafka:1.2.2.RELEASE" + compile('org.springframework.boot:spring-boot-starter-web') + compile 'com.google.guava:guava:20.0' + testCompile('org.springframework.boot:spring-boot-starter-test') + testCompile "org.springframework.kafka:spring-kafka-test:1.2.2.RELEASE" + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/docker-compose.yml b/APPLICATIONS/spring-kafka-producer-consumer/docker-compose.yml new file mode 100644 index 00000000..f6cae2c4 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/docker-compose.yml @@ -0,0 +1,15 @@ +version: '2' +services: + zookeeper: + image: wurstmeister/zookeeper + ports: + - "2181:2181" + kafka: + image: wurstmeister/kafka + ports: + - "9092:9092" + environment: + KAFKA_ADVERTISED_HOST_NAME: localhost + KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 + volumes: + - /var/run/docker.sock:/var/run/docker.sock diff --git a/APPLICATIONS/spring-kafka-producer-consumer/gradle/wrapper/gradle-wrapper.properties b/APPLICATIONS/spring-kafka-producer-consumer/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..b41319db --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Nov 07 19:07:08 PST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-bin.zip diff --git a/APPLICATIONS/spring-kafka-producer-consumer/gradlew b/APPLICATIONS/spring-kafka-producer-consumer/gradlew new file mode 100644 index 00000000..9aa616c2 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/gradlew @@ -0,0 +1,169 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/APPLICATIONS/spring-kafka-producer-consumer/gradlew.bat b/APPLICATIONS/spring-kafka-producer-consumer/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/build.gradle b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/build.gradle new file mode 100644 index 00000000..c288c996 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/build.gradle @@ -0,0 +1,7 @@ +jar { + baseName = project.name + version = '1.2.1-M1' +} + +dependencies { +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/MainApp.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/MainApp.java new file mode 100644 index 00000000..8cd5b799 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/MainApp.java @@ -0,0 +1,14 @@ +package sample.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import sample.consumer.config.KafkaConsumerProperties; + +@SpringBootApplication +@EnableConfigurationProperties(KafkaConsumerProperties.class) +public class MainApp { + public static void main(String[] args) { + SpringApplication.run(MainApp.class, args); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/WorkUnitsConsumer.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/WorkUnitsConsumer.java new file mode 100644 index 00000000..4d6d3084 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/WorkUnitsConsumer.java @@ -0,0 +1,22 @@ +package sample.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Service; +import sample.consumer.domain.WorkUnit; + +@Service +public class WorkUnitsConsumer { + private static final Logger log = LoggerFactory.getLogger(WorkUnitsConsumer.class); + + @KafkaListener(topics = "workunits") + public void onReceiving(WorkUnit workUnit, @Header(KafkaHeaders.OFFSET) Integer offset, + @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition, + @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Processing topic = {}, partition = {}, offset = {}, workUnit = {}", + topic, partition, offset, workUnit); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaConsumerProperties.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaConsumerProperties.java new file mode 100644 index 00000000..bf68cbe6 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaConsumerProperties.java @@ -0,0 +1,37 @@ +package sample.consumer.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "kafka.consumer") +public class KafkaConsumerProperties { + + private String bootstrap; + private String group; + private String topic; + + public String getBootstrap() { + return bootstrap; + } + + public void setBootstrap(String bootstrap) { + this.bootstrap = bootstrap; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaListenerConfig.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaListenerConfig.java new file mode 100644 index 00000000..ead6d991 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/config/KafkaListenerConfig.java @@ -0,0 +1,61 @@ +package sample.consumer.config; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.Deserializer; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; +import sample.consumer.domain.WorkUnit; + +import java.util.HashMap; +import java.util.Map; + +@Configuration +@EnableKafka +public class KafkaListenerConfig { + + @Autowired + private KafkaConsumerProperties kafkaConsumerProperties; + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = + new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConcurrency(1); + factory.setConsumerFactory(consumerFactory()); + return factory; + } + + @Bean + public ConsumerFactory consumerFactory() { + return new DefaultKafkaConsumerFactory<>(consumerProps(), stringKeyDeserializer(), workUnitJsonValueDeserializer()); + } + + + @Bean + public Map consumerProps() { + Map props = new HashMap<>(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConsumerProperties.getBootstrap()); + props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConsumerProperties.getGroup()); + props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); + props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100"); + props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); + return props; + } + + @Bean + public Deserializer stringKeyDeserializer() { + return new StringDeserializer(); + } + + @Bean + public Deserializer workUnitJsonValueDeserializer() { + return new JsonDeserializer(WorkUnit.class); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/domain/WorkUnit.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/domain/WorkUnit.java new file mode 100644 index 00000000..1cfecb68 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/java/sample/consumer/domain/WorkUnit.java @@ -0,0 +1,35 @@ +package sample.consumer.domain; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.MoreObjects; + +public class WorkUnit { + + private final String id; + private final String definition; + + @JsonCreator + public WorkUnit(@JsonProperty("id") String id, + @JsonProperty("definition") String definition) { + this.id = id; + this.definition = definition; + } + + public String getId() { + return id; + } + + + public String getDefinition() { + return definition; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("id", id) + .add("definition", definition) + .toString(); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/resources/application.yml b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/resources/application.yml new file mode 100644 index 00000000..63742bb3 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-consumer/src/main/resources/application.yml @@ -0,0 +1,8 @@ +server: + port: 8081 + +kafka: + consumer: + bootstrap: localhost:9092 + group: WorkUnitApp + topic: workunits \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/build.gradle b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/build.gradle new file mode 100644 index 00000000..cdc40dc5 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/build.gradle @@ -0,0 +1,4 @@ +jar { + baseName = project.name + version = '1.2.0-M1' +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/MainApp.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/MainApp.java new file mode 100644 index 00000000..65904fa7 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/MainApp.java @@ -0,0 +1,13 @@ +package sample.producer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MainApp { + + public static void main(String[] args) { + SpringApplication.run(MainApp.class, args); + } + +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerConfig.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerConfig.java new file mode 100644 index 00000000..6dcb406e --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerConfig.java @@ -0,0 +1,52 @@ +package sample.producer.config; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.Serializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; +import sample.producer.domain.WorkUnit; + +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class KafkaProducerConfig { + + @Autowired + private KafkaProducerProperties kafkaProducerProperties; + + @Bean + public ProducerFactory producerFactory() { + return new DefaultKafkaProducerFactory<>(producerConfigs(), stringKeySerializer(), workUnitJsonSerializer()); + } + + @Bean + public Map producerConfigs() { + Map props = new HashMap<>(); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProducerProperties.getBootstrap()); + return props; + } + + @Bean + public KafkaTemplate workUnitsKafkaTemplate() { + KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory()); + kafkaTemplate.setDefaultTopic(kafkaProducerProperties.getTopic()); + return kafkaTemplate; + } + + @Bean + public Serializer stringKeySerializer() { + return new StringSerializer(); + } + + @Bean + public Serializer workUnitJsonSerializer() { + return new JsonSerializer(); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerProperties.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerProperties.java new file mode 100644 index 00000000..9381dadf --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/config/KafkaProducerProperties.java @@ -0,0 +1,28 @@ +package sample.producer.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "kafka.producer") +public class KafkaProducerProperties { + + private String bootstrap; + private String topic; + + public String getBootstrap() { + return bootstrap; + } + + public void setBootstrap(String bootstrap) { + this.bootstrap = bootstrap; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/domain/WorkUnit.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/domain/WorkUnit.java new file mode 100644 index 00000000..10e5ce3b --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/domain/WorkUnit.java @@ -0,0 +1,46 @@ +package sample.producer.domain; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.MoreObjects; + +public class WorkUnit { + + private String id; + private String definition; + + public WorkUnit() { + //for Spring-Web binding + } + @JsonCreator + public WorkUnit(@JsonProperty("id") String id, + @JsonProperty("definition") String definition) { + this.id = id; + this.definition = definition; + } + + public String getId() { + return id; + } + + + public String getDefinition() { + return definition; + } + + public void setId(String id) { + this.id = id; + } + + public void setDefinition(String definition) { + this.definition = definition; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("id", id) + .add("definition", definition) + .toString(); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/service/WorkUnitDispatcher.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/service/WorkUnitDispatcher.java new file mode 100644 index 00000000..d4cc84a6 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/service/WorkUnitDispatcher.java @@ -0,0 +1,36 @@ +package sample.producer.service; + + +import org.apache.kafka.clients.producer.RecordMetadata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.stereotype.Service; +import sample.producer.config.KafkaProducerProperties; +import sample.producer.domain.WorkUnit; + +@Service +public class WorkUnitDispatcher { + + @Autowired + private KafkaTemplate workUnitsKafkaTemplate; + + @Autowired + private KafkaProducerProperties kafkaProducerProperties; + + private static final Logger LOGGER = LoggerFactory.getLogger(WorkUnitDispatcher.class); + + public boolean dispatch(WorkUnit workUnit) { + try { + SendResult sendResult = workUnitsKafkaTemplate.sendDefault(workUnit.getId(), workUnit).get(); + RecordMetadata recordMetadata = sendResult.getRecordMetadata(); + LOGGER.info("topic = {}, partition = {}, offset = {}, workUnit = {}", + recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(), workUnit); + return true; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/web/SampleKafkaMessageController.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/web/SampleKafkaMessageController.java new file mode 100644 index 00000000..0b9886bb --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/java/sample/producer/web/SampleKafkaMessageController.java @@ -0,0 +1,19 @@ +package sample.producer.web; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import sample.producer.domain.WorkUnit; +import sample.producer.service.WorkUnitDispatcher; + +@RestController +public class SampleKafkaMessageController { + + @Autowired + private WorkUnitDispatcher workUnitDispatcher; + + @GetMapping("/generateWork") + public boolean sendMessage(WorkUnit workUnit) { + return this.workUnitDispatcher.dispatch(workUnit); + } +} diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/resources/application.yml b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/resources/application.yml new file mode 100644 index 00000000..9cb3bb39 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: 8080 + +kafka: + producer: + bootstrap: localhost:9092 + topic: workunits \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/java/sample/producer/embed/EmbedKafkaTest.java b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/java/sample/producer/embed/EmbedKafkaTest.java new file mode 100644 index 00000000..3ec75f5c --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/java/sample/producer/embed/EmbedKafkaTest.java @@ -0,0 +1,113 @@ +package sample.producer.embed; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.junit.ClassRule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.listener.AcknowledgingMessageListener; +import org.springframework.kafka.listener.KafkaMessageListenerContainer; +import org.springframework.kafka.listener.config.ContainerProperties; +import org.springframework.kafka.test.rule.KafkaEmbedded; +import org.springframework.kafka.test.utils.KafkaTestUtils; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +public class EmbedKafkaTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(EmbedKafkaTest.class); + + @ClassRule + public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(2, true, 2, "messages"); + + @Test + public void testSpringKafka() throws Exception { + Map consumerProps = KafkaTestUtils.consumerProps("sampleConsumer", "false", embeddedKafka); + consumerProps.put("auto.offset.reset", "earliest"); + DefaultKafkaConsumerFactory cf = new DefaultKafkaConsumerFactory<>(consumerProps); + ContainerProperties containerProps = new ContainerProperties("messages"); + + final CountDownLatch latch = new CountDownLatch(4); + containerProps.setMessageListener((AcknowledgingMessageListener) (message, ack) -> { + LOGGER.info("Receiving: " + message); + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + latch.countDown(); + }); + KafkaMessageListenerContainer container = + new KafkaMessageListenerContainer<>(cf, containerProps); + container.setBeanName("sampleConsumer"); + + + container.start(); +// ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic()); + + Map senderProps = KafkaTestUtils.producerProps(embeddedKafka); + ProducerFactory pf = new DefaultKafkaProducerFactory(senderProps); + KafkaTemplate template = new KafkaTemplate<>(pf); + template.setDefaultTopic("messages"); + template.sendDefault(0, 0, "message1"); + template.sendDefault(0, 1, "message2"); + template.sendDefault(1, 2, "message3"); + template.sendDefault(1, 3, "message4"); + template.flush(); + assertThat(latch.await(20, TimeUnit.SECONDS)).isTrue(); + container.stop(); + } + + @Test + public void testEmbeddedRawKafka() throws Exception { + + + Map senderProps = KafkaTestUtils.producerProps(embeddedKafka); + KafkaProducer producer = new KafkaProducer<>(senderProps); + producer.send(new ProducerRecord<>("messages", 0, 0, "message0")).get(); + producer.send(new ProducerRecord<>("messages", 0, 1, "message1")).get(); + producer.send(new ProducerRecord<>("messages", 1, 2, "message2")).get(); + producer.send(new ProducerRecord<>("messages", 1, 3, "message3")).get(); + + + Map consumerProps = KafkaTestUtils.consumerProps("sampleRawConsumer", "false", embeddedKafka); + consumerProps.put("auto.offset.reset", "earliest"); + + final CountDownLatch latch = new CountDownLatch(4); + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService.execute(() -> { + KafkaConsumer kafkaConsumer = new KafkaConsumer<>(consumerProps); + kafkaConsumer.subscribe(Collections.singletonList("messages")); + try { + while (true) { + ConsumerRecords records = kafkaConsumer.poll(100); + for (ConsumerRecord record : records) { + LOGGER.info("consuming from topic = {}, partition = {}, offset = {}, key = {}, value = {}", + record.topic(), record.partition(), record.offset(), record.key(), record.value()); + latch.countDown(); + } + } + } finally { + kafkaConsumer.close(); + } + }); + + assertThat(latch.await(90, TimeUnit.SECONDS)).isTrue(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/resources/logback.xml b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/resources/logback.xml new file mode 100644 index 00000000..6ef9f625 --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/sample-spring-kafka-producer/src/test/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-kafka-producer-consumer/settings.gradle b/APPLICATIONS/spring-kafka-producer-consumer/settings.gradle new file mode 100644 index 00000000..0b0edafb --- /dev/null +++ b/APPLICATIONS/spring-kafka-producer-consumer/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name="sample-spring-kafka-producer-consumer" +include('sample-spring-kafka-producer', 'sample-spring-kafka-consumer') diff --git a/APPLICATIONS/spring-mvc-annoation/document/help.txt b/APPLICATIONS/spring-mvc-annoation/document/help.txt new file mode 100644 index 00000000..c20a3a92 --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/document/help.txt @@ -0,0 +1,5 @@ +$ mvn clean package + +$ mvn jetty:run + +$ curl http://localhost:8080/spring-mvc-annoation/welcome \ No newline at end of file diff --git a/APPLICATIONS/spring-mvc-annoation/pom.xml b/APPLICATIONS/spring-mvc-annoation/pom.xml new file mode 100644 index 00000000..27616725 --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + org.example + spring-mvc-annoation + 1.0-SNAPSHOT + + + spring-mvc-annoation + UTF-8 + 1.8 + 4.1.6.RELEASE + + + + + + org.springframework + spring-webmvc + ${spring.version} + + + + javax.servlet + javax.servlet-api + 3.0.1 + + + + + + ${project.name} + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + org.eclipse.jetty + jetty-maven-plugin + 9.2.11.v20150529 + + 10 + + /${project.name} + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/AppInitializer.java b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/AppInitializer.java new file mode 100644 index 00000000..de265ea3 --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/AppInitializer.java @@ -0,0 +1,30 @@ +package com.espark.adarsh; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + WebApplicationContext context = getContext(); + servletContext.addListener(new ContextLoaderListener(context)); + ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/*"); + } + + private AnnotationConfigWebApplicationContext getContext() { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("com.espark.adarsh.config"); + return context; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/AppConfig.java b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/AppConfig.java new file mode 100644 index 00000000..18fe2111 --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/AppConfig.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.espark.adarsh") +public class AppConfig { +} diff --git a/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/WebMvcConfig.java b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/WebMvcConfig.java new file mode 100644 index 00000000..ba09921e --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/config/WebMvcConfig.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@EnableWebMvc +@Configuration +public class WebMvcConfig extends WebMvcConfigurerAdapter { + +} diff --git a/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..f2714b27 --- /dev/null +++ b/APPLICATIONS/spring-mvc-annoation/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class ApplicationController { + + @RequestMapping(value = "/welcome", method = RequestMethod.GET) + @ResponseBody + public String welcome() { + return "Hello world"; + } + +} diff --git a/APPLICATIONS/spring-reflection/.gitignore b/APPLICATIONS/spring-reflection/.gitignore new file mode 100644 index 00000000..81a33ed4 --- /dev/null +++ b/APPLICATIONS/spring-reflection/.gitignore @@ -0,0 +1,25 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/spring-reflection/pom.xml b/APPLICATIONS/spring-reflection/pom.xml new file mode 100644 index 00000000..fea88076 --- /dev/null +++ b/APPLICATIONS/spring-reflection/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + spring-reflection + spring-reflection + 0.0.1-SNAPSHOT + jar + + spring-reflection + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework + spring-context-support + 4.2.2.RELEASE + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/dao/GenericDao.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/dao/GenericDao.java new file mode 100644 index 00000000..22d2600a --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/dao/GenericDao.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.dao; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +public class GenericDao { + + private List store = new LinkedList<>(); + + private Class entityClass; + + public GenericDao(Class entityClass) { + this.entityClass = entityClass; + } + + public List findAll() { + return store; + } + + public Optional persist(E toPersist) { + store.add(toPersist); + return (Optional) Optional.of(toPersist).orElse(null); + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Account.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Account.java new file mode 100644 index 00000000..130137ce --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Account.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.entity; + +public class Account { + + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Person.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Person.java new file mode 100644 index 00000000..98848670 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/entity/Person.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.entity; + +public class Person { + + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessAnnotationProcessor.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessAnnotationProcessor.java new file mode 100644 index 00000000..93a04055 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessAnnotationProcessor.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.processor; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.stereotype.Component; +import org.springframework.util.ReflectionUtils; + +@Component +public class DataAccessAnnotationProcessor implements BeanPostProcessor { + + + @Autowired + private ConfigurableListableBeanFactory configurableBeanFactory; + + public DataAccessAnnotationProcessor(ConfigurableListableBeanFactory beanFactory) { + this.configurableBeanFactory = beanFactory; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { + this.scanDataAccessAnnotation(bean, beanName); + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { + return bean; + } + + protected void scanDataAccessAnnotation(Object bean, String beanName) { + this.configureFieldInjection(bean); + } + + private void configureFieldInjection(Object bean) { + Class managedBeanClass = bean.getClass(); + //for the field annotation + ReflectionUtils.FieldCallback fieldCallback = + new DataAccessFieldCallback(configurableBeanFactory, bean); + ReflectionUtils.doWithFields(managedBeanClass, fieldCallback); + + //for the method annotation + ReflectionUtils.MethodCallback methodCallback = + new DataAccessMethodCallback(configurableBeanFactory, bean); + ReflectionUtils.doWithMethods(managedBeanClass, methodCallback); + } +} \ No newline at end of file diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessFieldCallback.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessFieldCallback.java new file mode 100644 index 00000000..171817a1 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessFieldCallback.java @@ -0,0 +1,98 @@ +package com.espark.adarsh.processor; + +import com.espark.adarsh.processor.annotation.DataAccess; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public class DataAccessFieldCallback implements ReflectionUtils.FieldCallback { + + + private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); + + private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; + + private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + + "value should have same type with injected generic type."; + private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + + "to raw (non-generic) declaration. This will make your code less type-safe."; + private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + + "type '{}' or instance creation is failed because: {}"; + + private ConfigurableListableBeanFactory configurableBeanFactory; + private Object bean; + + public DataAccessFieldCallback(ConfigurableListableBeanFactory bf, Object bean) { + configurableBeanFactory = bf; + this.bean = bean; + } + + @Override + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + + // @DataAccess processing + if (field.isAnnotationPresent(DataAccess.class)) { + ReflectionUtils.makeAccessible(field); + Type fieldGenericType = field.getGenericType(); + // get actual "GenericDAO' type. + Class generic = field.getType(); + Class classValue = field.getDeclaredAnnotation(DataAccess.class).entity(); + + if (genericTypeIsValid(classValue, fieldGenericType)) { + String beanName = classValue.getSimpleName() + generic.getSimpleName(); + Object beanInstance = getBeanInstance(beanName, generic, classValue); + field.set(bean, beanInstance); + } else { + throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME); + } + + } else { + return; + } + } + + public boolean genericTypeIsValid(Class clazz, Type field) { + if (field instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) field; + Type type = parameterizedType.getActualTypeArguments()[0]; + return type.equals(clazz); + } else { + logger.warn(WARN_NON_GENERIC_VALUE); + return true; + } + } + + public Object getBeanInstance( + String beanName, Class genericClass, Class paramClass) { + Object daoInstance = null; + if (!configurableBeanFactory.containsBean(beanName)) { + logger.info("Creating new DataAccess bean named '{}'.", beanName); + + Object toRegister = null; + try { + Constructor ctr = genericClass.getConstructor(Class.class); + toRegister = ctr.newInstance(paramClass); + } catch (Exception e) { + logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e); + throw new RuntimeException(e); + } + + daoInstance = configurableBeanFactory.initializeBean(toRegister, beanName); + configurableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true); + configurableBeanFactory.registerSingleton(beanName, daoInstance); + logger.info("Bean named '{}' created successfully.", beanName); + } else { + daoInstance = configurableBeanFactory.getBean(beanName); + logger.info( + "Bean named '{}' already exists used as current bean reference.", beanName); + } + return daoInstance; + } +} \ No newline at end of file diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessMethodCallback.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessMethodCallback.java new file mode 100644 index 00000000..382cdf85 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/DataAccessMethodCallback.java @@ -0,0 +1,103 @@ +package com.espark.adarsh.processor; + +import com.espark.adarsh.processor.annotation.DataAccess; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.ReflectionUtils; +import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl; + +import java.lang.reflect.*; + +public class DataAccessMethodCallback implements ReflectionUtils.MethodCallback { + + private static Logger logger = LoggerFactory.getLogger(DataAccessMethodCallback.class); + + private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; + + private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + + "value should have same type with injected generic type."; + private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + + "to raw (non-generic) declaration. This will make your code less type-safe."; + private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + + "type '{}' or instance creation is failed because: {}"; + + private ConfigurableListableBeanFactory configurableBeanFactory; + private Object bean; + + public DataAccessMethodCallback(ConfigurableListableBeanFactory bf, Object bean) { + configurableBeanFactory = bf; + this.bean = bean; + } + + @Override + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + + // @DataAccess processing + if (method.isAnnotationPresent(DataAccess.class)) { + ReflectionUtils.makeAccessible(method); + + Type[] methodParamType = method.getGenericParameterTypes(); + Class classValue = method.getDeclaredAnnotation(DataAccess.class).entity(); + + Type fieldGenericType = methodParamType[0]; + + // get actual "GenericDAO' type. + Class generic = ((ParameterizedTypeImpl) methodParamType[0]).getRawType(); + + if (genericTypeIsValid(classValue, fieldGenericType)) { + String beanName = classValue.getSimpleName() + generic.getSimpleName(); + Object beanInstance = getBeanInstance(beanName, generic, classValue); + try { + method.invoke(bean,beanInstance); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } + } else { + throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME); + } + + } else { + return; + } + } + + public boolean genericTypeIsValid(Class clazz, Type field) { + if (field instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) field; + Type type = parameterizedType.getActualTypeArguments()[0]; + return type.equals(clazz); + } else { + logger.warn(WARN_NON_GENERIC_VALUE); + return true; + } + } + + public Object getBeanInstance( + String beanName, Class genericClass, Class paramClass) { + Object daoInstance = null; + if (!configurableBeanFactory.containsBean(beanName)) { + logger.info("Creating new DataAccess bean named '{}'.", beanName); + + Object toRegister = null; + try { + Constructor ctr = genericClass.getConstructor(Class.class); + toRegister = ctr.newInstance(paramClass); + } catch (Exception e) { + logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e); + throw new RuntimeException(e); + } + + daoInstance = configurableBeanFactory.initializeBean(toRegister, beanName); + configurableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true); + configurableBeanFactory.registerSingleton(beanName, daoInstance); + logger.info("Bean named '{}' created successfully.", beanName); + } else { + daoInstance = configurableBeanFactory.getBean(beanName); + logger.info( + "Bean named '{}' already exists used as current bean reference.", beanName); + } + return daoInstance; + } +} \ No newline at end of file diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/annotation/DataAccess.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/annotation/DataAccess.java new file mode 100644 index 00000000..22941704 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/processor/annotation/DataAccess.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.processor.annotation; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) +@Documented +public @interface DataAccess { + Class entity(); +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldService.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldService.java new file mode 100644 index 00000000..da42ef30 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldService.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Account; +import com.espark.adarsh.entity.Person; + +import java.util.List; +import java.util.Optional; + +public interface FieldService { + + Optional createPerson(Person person); + + List getAllPerson(); + + Optional createAccount(Account account); + + List getAllAccount(); + + +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldServiceImpl.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldServiceImpl.java new file mode 100644 index 00000000..457bd9fe --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/FieldServiceImpl.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Account; +import com.espark.adarsh.processor.annotation.DataAccess; +import com.espark.adarsh.dao.GenericDao; +import com.espark.adarsh.entity.Person; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class FieldServiceImpl implements FieldService { + + @DataAccess(entity=Person.class) + private GenericDao personGenericDao; + + @DataAccess(entity=Account.class) + private GenericDao accountGenericDao; + + @Override + public Optional createPerson(Person person) { + return this.personGenericDao.persist(person); + } + + @Override + public List getAllPerson() { + return this.personGenericDao.findAll(); + } + + @Override + public Optional createAccount(Account account) { + return this.accountGenericDao.persist(account); + } + + @Override + public List getAllAccount() { + return this.accountGenericDao.findAll(); + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodService.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodService.java new file mode 100644 index 00000000..46b273c8 --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodService.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Account; +import com.espark.adarsh.entity.Person; + +import java.util.List; +import java.util.Optional; + +public interface MethodService { + + Optional createPerson(Person person); + + List getAllPerson(); + + Optional createAccount(Account account); + + List getAllAccount(); + + +} diff --git a/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodServiceImpl.java b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodServiceImpl.java new file mode 100644 index 00000000..9db9933d --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/main/java/com/espark/adarsh/service/MethodServiceImpl.java @@ -0,0 +1,47 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.dao.GenericDao; +import com.espark.adarsh.entity.Account; +import com.espark.adarsh.entity.Person; +import com.espark.adarsh.processor.annotation.DataAccess; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class MethodServiceImpl implements MethodService { + + private GenericDao personGenericDao; + private GenericDao accountGenericDao; + + @DataAccess(entity=Person.class) + public void setPersonGenericDao( GenericDao personGenericDao){ + this.personGenericDao=personGenericDao; + } + + @DataAccess(entity=Account.class) + private void setAccountGenericDao(GenericDao accountGenericDao){ + this.accountGenericDao=accountGenericDao; + } + + @Override + public Optional createPerson(Person person) { + return this.personGenericDao.persist(person); + } + + @Override + public List getAllPerson() { + return this.personGenericDao.findAll(); + } + + @Override + public Optional createAccount(Account account) { + return this.accountGenericDao.persist(account); + } + + @Override + public List getAllAccount() { + return this.accountGenericDao.findAll(); + } +} diff --git a/APPLICATIONS/spring-reflection/src/main/resources/application.properties b/APPLICATIONS/spring-reflection/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/spring-reflection/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/spring-reflection/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..a23b0c3e --- /dev/null +++ b/APPLICATIONS/spring-reflection/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,41 @@ +package com.espark.adarsh; + +import com.espark.adarsh.processor.annotation.DataAccess; +import com.espark.adarsh.dao.GenericDao; +import com.espark.adarsh.entity.Account; +import com.espark.adarsh.entity.Person; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @DataAccess(entity=Person.class) + private GenericDao personGenericDao; + + @DataAccess(entity=Account.class) + private GenericDao accountGenericDao; + + private GenericDao personGenericDaoMethod; + private GenericDao accountGenericDaoMethod; + + @DataAccess(entity=Person.class) + public void setPersonGenericDaoMethod(GenericDao personGenericDaoMethod){ + this.personGenericDaoMethod = personGenericDaoMethod; + } + + @DataAccess(entity=Account.class) + private void setAccountGenericDaoMethod(GenericDao accountGenericDaoMethod){ + this.accountGenericDaoMethod = accountGenericDaoMethod; + } + + + @Test + public void contextLoads() { + System.out.println("welcome to the appliation "); + } + +} diff --git a/APPLICATIONS/springbboot-openapi-security/.gitignore b/APPLICATIONS/springbboot-openapi-security/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springbboot-openapi-security/Dockerfile b/APPLICATIONS/springbboot-openapi-security/Dockerfile new file mode 100644 index 00000000..cdf7bec5 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8 +MAINTAINER adarsh.kumar@gmail.com +COPY target/springbboot-openapi-security.jar springbboot-openapi-security.jar +EXPOSE 8080 +ENTRYPOINT ["java","-jar","springbboot-openapi-security.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springbboot-openapi-security/README.md b/APPLICATIONS/springbboot-openapi-security/README.md new file mode 100644 index 00000000..cf95a461 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/README.md @@ -0,0 +1,61 @@ + +# spring boot openapi security + +### to build the application +* $ mvn clean package +```` + mvn -X \ + -Djavax.net.debug=ssl \ + -Dmaven.wagon.http.ssl.insecure=true \ + -Dmaven.wagon.http.ssl.allowall=true \ + -Dmaven.wagon.http.ssl.ignore.validity.dates=true \ + clean package +```` + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +springdoc.api-docs.path = /espark-openapi + +## swagger ui json meta data url +* http://localhost:8080/espark-openapi/ + +## swagger ui url +* http://localhost:8080/swagger-ui.html + * admin/admin + +### To Build the docker tag +* $ docker build -f Dockerfile -t adarshkumarsingh83/springbboot-openapi-security . +``` +[+] Building 2.2s (8/8) FINISHED + => [internal] load build definition from Dockerfile 0.0s + => => transferring dockerfile: 37B 0.0s + => [internal] load .dockerignore 0.0s + => => transferring context: 2B 0.0s + => [internal] load metadata for docker.io/library/openjdk:8 1.3s + => [auth] library/openjdk:pull token for registry-1.docker.io 0.0s + => [internal] load build context 0.4s + => => transferring context: 48.72MB 0.4s + => CACHED [1/2] FROM docker.io/library/openjdk:8@sha256:86e863cc57215cfb181bd319736d0baf625fe8f150577f9eb58bd937f5452cb8 0.0s + => [2/2] COPY target/springboot-splunk.jar springboot-splunk.jar 0.1s + => exporting to image 0.2s + => => exporting layers 0.2s + => => writing image sha256:6ef0d66ca9bd6fbb780120063ff99bdcce99a727afee5a852e0f8ed3af628b7c 0.0s + => => naming to docker.io/adarshkumarsingh83/springboot-splunk +``` +### To push to the docker hub +* $ docker push adarshkumarsingh83/springbboot-openapi-security + +### To Run +* docker-compose up +## To stop +* docker-compose down + +### To Test the Api +* curl -X GET http://localhost:8080/employees \ No newline at end of file diff --git a/APPLICATIONS/springbboot-openapi-security/pom.xml b/APPLICATIONS/springbboot-openapi-security/pom.xml new file mode 100644 index 00000000..a1a60545 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + com.espark.adarsh + springbboot-openapi-security + 0.0.1-SNAPSHOT + springbboot-openapi-security + Demo project for Spring Boot + + 1.8 + 2021.0.4 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springdoc + springdoc-openapi-ui + 1.6.11 + + + + org.springframework.boot + spring-boot-starter-security + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..acbf3972 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,23 @@ +package com.espark.adarsh; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +@SecurityScheme(name = "espark-api", scheme = "basic", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER) +@OpenAPIDefinition(info = @Info(title = "Employee API", version = "2.0", description = "Employee Details")) +public class ApplicationMain { + + + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..17eec522 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfig { + +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/SecurityConfiguration.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/SecurityConfiguration.java new file mode 100644 index 00000000..3e7efceb --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/config/SecurityConfiguration.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@EnableWebSecurity +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/swagger-ui*/**", "/espark-openapi/**").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("admin") + .password(passwordEncoder().encode("admin")) + .authorities("ADMIN"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..57a3e3de --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..5a452947 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.exception; + +public class EmployeeNotFoundException extends RuntimeException{ + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..e22a132e --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.function.Predicate; + +@RestController +@SecurityRequirement(name = "epsark-api") +public class EmployeeController { + + private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class); + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + logger.info("EmployeeController getAllEmployee() "); + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) throws EmployeeNotFoundException { + return this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) throws EmployeeNotFoundException { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) throws EmployeeNotFoundException { + if (this.employeeRepository.existsById(id)) { + return this.employeeRepository.save(employee); + } else { + throw new EmployeeNotFoundException("employee not found"); + } + } + +} diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/resources/application.yml b/APPLICATIONS/springbboot-openapi-security/src/main/resources/application.yml new file mode 100644 index 00000000..489e2d49 --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/resources/application.yml @@ -0,0 +1,32 @@ + +logging: + level: + root: INFO + org.springframework.web: INFO + com.espark.adarsh: INFO + org.hibernate: INFO + +#spring.datasource.url=jdbc:h2:file:/data/demo +server: + port: 8080 + +spring: + application: + name: springbboot-openapi-security + config: + activate: + on-profile: + - default + - docker + - kubernates + datasource: + url: jdbc:h2:mem:testdb + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + h2: + console: + enabled: true + diff --git a/APPLICATIONS/springbboot-openapi-security/src/main/resources/data.sql b/APPLICATIONS/springbboot-openapi-security/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springbboot-openapi-security/src/test/java/com/espark/adarsh/SpringbbootOpenapiSecurityApplicationTests.java b/APPLICATIONS/springbboot-openapi-security/src/test/java/com/espark/adarsh/SpringbbootOpenapiSecurityApplicationTests.java new file mode 100644 index 00000000..e9bfe79b --- /dev/null +++ b/APPLICATIONS/springbboot-openapi-security/src/test/java/com/espark/adarsh/SpringbbootOpenapiSecurityApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbbootOpenapiSecurityApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-3-example/.gitignore b/APPLICATIONS/springboot-3-example/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-3-example/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-3-example/README.md b/APPLICATIONS/springboot-3-example/README.md new file mode 100644 index 00000000..6d5862fc --- /dev/null +++ b/APPLICATIONS/springboot-3-example/README.md @@ -0,0 +1,8 @@ +# springboot-3-example +--- +### To build +* mvn clean package + +### To Test +* mvn spring-boot:run +* seq 1 10 | xargs -n1 -P1 curl -X GET "http://localhost:8080/api/wish/adarsh" \ No newline at end of file diff --git a/APPLICATIONS/springboot-3-example/pom.xml b/APPLICATIONS/springboot-3-example/pom.xml new file mode 100644 index 00000000..d1a7e2ab --- /dev/null +++ b/APPLICATIONS/springboot-3-example/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.0.0 + + + com.espark.adarsh + springboot-3-example + 0.0.1-SNAPSHOT + springboot-3-example + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java new file mode 100644 index 00000000..0a8616e1 --- /dev/null +++ b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Springboot3ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot3ExampleApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/service/WishService.java new file mode 100644 index 00000000..a2bd39b5 --- /dev/null +++ b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/service/WishService.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.service; + +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@Service +public class WishService { + + public Map wish(String name) { + int hour = LocalDateTime.now().getHour(); + if (hour > 0 && hour < 11) { + return new HashMap() { + { + { + put("message", " Good morning " + name); + } + } + }; + } else if (hour > 11 && hour < 16) { + return new HashMap() { + { + { + put("message", " Good After noon " + name); + } + } + }; + } else { + return new HashMap() { + { + { + put("message", " Good Evening " + name); + } + } + }; + } + } +} diff --git a/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..efb92a6e --- /dev/null +++ b/APPLICATIONS/springboot-3-example/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.WishService; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + WishService wishService; + + @GetMapping("/wish/{name}") + public ResponseEntity> wish(@PathVariable("name") String name) { + return ResponseEntity.ok(wishService.wish(name)); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-3-example/src/main/resources/application.properties b/APPLICATIONS/springboot-3-example/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-3-example/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-3-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java b/APPLICATIONS/springboot-3-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java new file mode 100644 index 00000000..e18b0619 --- /dev/null +++ b/APPLICATIONS/springboot-3-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot3ExampleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-annotation-module/.gitignore b/APPLICATIONS/springboot-annotation-module/.gitignore new file mode 100644 index 00000000..153c9335 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/MavenWrapperDownloader.java b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..72308aa4 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/APPLICATIONS/springboot-annotation-module/pom.xml b/APPLICATIONS/springboot-annotation-module/pom.xml new file mode 100644 index 00000000..22f9156b --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.4.RELEASE + + + com.espark.adarsh + springboot-annotation-module + 0.0.1-SNAPSHOT + springboot-annotation-module + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + 1.18.4 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..888cdc38 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,17 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ApplicationMain { + + + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + + } + +} diff --git a/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/annotation/EsparkMethod.java b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/annotation/EsparkMethod.java new file mode 100644 index 00000000..84ecf69d --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/annotation/EsparkMethod.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.annotation; + + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface EsparkMethod { +} diff --git a/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/AnnotationUtil.java b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/AnnotationUtil.java new file mode 100644 index 00000000..23561159 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/AnnotationUtil.java @@ -0,0 +1,211 @@ +package com.espark.adarsh.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AssignableTypeFilter; +import org.springframework.stereotype.Component; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; + +@Slf4j +@Component +public class AnnotationUtil { + + + @Qualifier("packageScan") + @Autowired + private List packageScan; + + + @Qualifier("classAnnotationToScan") + @Autowired + private List classAnnotationToScan; + + + @Qualifier("methodAnnotationToScan") + @Autowired + private List methodAnnotationToScan; + + + private Map> classAnnotationStore = new HashMap<>(); + private Map>> methodAnnotationStore = new HashMap<>(); + + + @PostConstruct + public void init() { + log.info("Package to scan={}", packageScan); + log.info("Class Annotation to scan={}", classAnnotationToScan); + log.info("Method Annotation to scan={}", methodAnnotationToScan); + List annotationClass = this.getClassFromName(classAnnotationToScan); + log.info("Annotation Classes in System={}", annotationClass); + if (annotationClass != null && !annotationClass.isEmpty()) { + classAnnotationStore = this.getClassesAnnotation(annotationClass); + log.info("Annotation and Classes Found classAnnotationStore={}", classAnnotationStore); + } + + if (classAnnotationStore != null && !classAnnotationStore.isEmpty()) { + List annotationMethod = this.getClassFromName(methodAnnotationToScan); + if (annotationMethod != null && !annotationMethod.isEmpty()) { + findMethodWithAnnotation(annotationMethod, classAnnotationStore); + log.info("Annotated Classes And Method Found methodAnnotationStore={}", methodAnnotationStore); + } + } + } + + + public List getClassFromName(List annotatedList) { + return annotatedList.stream().map(annotationClassName -> { + Class clazz = null; + try { + clazz = Class.forName(annotationClassName); + } catch (Exception e) { + log.error("Error while finding annotation from name exception={}", e); + } + return clazz; + }).filter(clazz -> clazz != null).collect(Collectors.toList()); + } + + + public Map> getClassesAnnotation(List annotationClass) { + Map> store = new HashMap<>(); + try { + for (String packageName : packageScan) { + final ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(true); + scanner.addIncludeFilter(new AssignableTypeFilter(Object.class)); + final Set beanDefinitionSet = scanner.findCandidateComponents(packageName); + try { + for (BeanDefinition beanDefinition : beanDefinitionSet) { + final Class clazz = Class.forName(beanDefinition.getBeanClassName()); + this.checkAnnotationExist(clazz, annotationClass, store); + } + } catch (ClassNotFoundException e) { + log.error("ClassNotFoundException getClassesAnnotation() e={}", e); + } + } + } catch (Exception e) { + log.error("Exception getClassesAnnotation() e={}", e); + } + return store; + } + + private void checkAnnotationExist( + Class clazz, List annotationClassSet, Map> store) { + + if (annotationClassSet != null && !annotationClassSet.isEmpty()) { + for (Class annotationClass : annotationClassSet) { + if (clazz.getAnnotation(annotationClass) != null) { + Annotation annotation = clazz.getAnnotation(annotationClass); + if (store.containsKey(annotation)) { + List annotationList = store.get(annotation); + annotationList.add(clazz); + store.put(annotation, annotationList); + } else { + List annotationList = new LinkedList<>(); + annotationList.add(clazz); + store.put(annotation, annotationList); + } + } + } + } + } + + + private void findMethodWithAnnotation( + List methodAnnotationList, + Map> classAnnotationStore) { + if (classAnnotationStore != null && !classAnnotationStore.isEmpty()) { + for (Map.Entry> annotationClassEntry : classAnnotationStore.entrySet()) { + List classList = annotationClassEntry.getValue(); + classList.stream().map(clazz -> { + Method[] declaredMethod = clazz.getDeclaredMethods(); + if (declaredMethod != null) { + Map> methodMetaData + = findAnnotatedMethod(declaredMethod, methodAnnotationList); + if (!methodMetaData.isEmpty()) { + return new HashMap>>() { + { + put(clazz, methodMetaData); + } + }; + } else { + return null; + } + } else { + return null; + } + }).filter((Map map) -> map != null) + .forEach(map -> addValueToStore(map)); + + } + } + } + + + private void addValueToStore(Map>> newClasMethodStore) { + + for (Map.Entry>> entryNewClassMethodStore : newClasMethodStore.entrySet()) { + + // class check in existing store + if (methodAnnotationStore.containsKey(entryNewClassMethodStore.getKey())) { + + Map> existingClassMethodStore = + methodAnnotationStore.get(entryNewClassMethodStore.getKey()); + Map> newClassMethodStore = entryNewClassMethodStore.getValue(); + + for (Map.Entry> newAnnotationMethodEntry : newClassMethodStore.entrySet()) { + + //checking for annotation exist or not + if (existingClassMethodStore.containsKey(newAnnotationMethodEntry.getKey())) { + List methodList = existingClassMethodStore.get(newAnnotationMethodEntry.getKey()); + methodList.addAll(newAnnotationMethodEntry.getValue()); + existingClassMethodStore + .put(newAnnotationMethodEntry.getKey(), methodList); + } else { + existingClassMethodStore + .put(newAnnotationMethodEntry.getKey(), newAnnotationMethodEntry.getValue()); + } + } + } else { + methodAnnotationStore.put(entryNewClassMethodStore.getKey(), entryNewClassMethodStore.getValue()); + } + } + } + + private Map> findAnnotatedMethod( + Method[] declaredMethod, List methodAnnotationList) { + Map> store = new HashMap<>(); + List declaredMethodList = Arrays.asList(declaredMethod); + for (Method method : declaredMethodList) { + Annotation[] declaredAnnotations = method.getDeclaredAnnotations(); + for (Annotation annotation : declaredAnnotations) { + if (methodAnnotationList.contains(annotation.annotationType())) { + if (store.containsKey(annotation)) { + List methodList = store.get(annotation); + methodList.add(method); + store.put(annotation.annotationType(), methodList); + } else { + List methodList = new LinkedList<>(); + methodList.add(method); + store.put(annotation.annotationType(), methodList); + } + } + } + + } + return store; + } +} diff --git a/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/ConfigParams.java b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/ConfigParams.java new file mode 100644 index 00000000..10192ec3 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/java/com/espark/adarsh/util/ConfigParams.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.annotation.EsparkMethod; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Configuration +public class ConfigParams { + + public static final String PACKAGE_NAME = "package.name"; + + + @EsparkMethod + @Bean(name = "packageScan") + @ConfigurationProperties( prefix = "espark.packages" ) + public List ignoreFileNames(){ + return new ArrayList(); + } + + + @EsparkMethod + @Bean(name = "classAnnotationToScan") + @ConfigurationProperties( prefix = "espark.annotation.class" ) + public List classAnnotationToScan(){ + return new ArrayList(); + } + + + @EsparkMethod + @Bean(name = "methodAnnotationToScan") + @ConfigurationProperties( prefix = "espark.annotation.method" ) + public List methodAnnotationToScan(){ + return new ArrayList(); + } + +} diff --git a/APPLICATIONS/springboot-annotation-module/src/main/resources/application.properties b/APPLICATIONS/springboot-annotation-module/src/main/resources/application.properties new file mode 100644 index 00000000..9a49403d --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/resources/application.properties @@ -0,0 +1,12 @@ +espark.packages[0]=com.espark.adarsh +espark.packages[1]=com.espark.adarsh.web +espark.packages[2]=com.espark.adarsh.manger +espark.packages[3]=com.espark.adarsh.service +espark.packages[4]=com.espark.adarsh.core + + +espark.annotation.class[0]=org.springframework.context.annotation.Configuration +espark.annotation.class[1]=org.springframework.stereotype.Component + +espark.annotation.method[0]=org.springframework.context.annotation.Bean +espark.annotation.method[1]=com.espark.adarsh.annotation.EsparkMethod \ No newline at end of file diff --git a/APPLICATIONS/springboot-annotation-module/src/main/resources/logback.xml b/APPLICATIONS/springboot-annotation-module/src/main/resources/logback.xml new file mode 100644 index 00000000..26beb6d5 --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-annotation-module/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-annotation-module/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-annotation-module/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-async-example/.gitignore b/APPLICATIONS/springboot-async-example/.gitignore new file mode 100644 index 00000000..153c9335 --- /dev/null +++ b/APPLICATIONS/springboot-async-example/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-async-example/pom.xml b/APPLICATIONS/springboot-async-example/pom.xml new file mode 100644 index 00000000..5d73dafa --- /dev/null +++ b/APPLICATIONS/springboot-async-example/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.4.RELEASE + + + com.espark.adarsh + springboot-async-example + 0.0.1-SNAPSHOT + springboot-async-example + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1311d655 --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@EnableAsync +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..d1e11883 --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + // http://localhost:9090/application/10 + + @Autowired + private ApplicationService applicationService; + + @GetMapping(value = "/application/{number}") + public String startCounter(@PathVariable("number") long number) { + + this.applicationService.startCounter(number); + return "Application Counter is started "; + } +} diff --git a/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..3786636f --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,7 @@ +package com.espark.adarsh.service; + + +public interface ApplicationService { + + public void startCounter(long max); +} diff --git a/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationServiceImpl.java b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationServiceImpl.java new file mode 100644 index 00000000..bab62d26 --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/main/java/com/espark/adarsh/service/ApplicationServiceImpl.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.service; + +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +public class ApplicationServiceImpl implements ApplicationService { + + @Async + @Override + public void startCounter(long max) { + + try { + while (max > 0) { + Thread.currentThread().sleep(1000); + System.out.println(max); + max--; + } + } catch (InterruptedException ae) { + ae.printStackTrace(); + } finally { + System.out.println("counter execution completed"); + } + } +} diff --git a/APPLICATIONS/springboot-async-example/src/main/resources/application.properties b/APPLICATIONS/springboot-async-example/src/main/resources/application.properties new file mode 100644 index 00000000..51ad5ebf --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=9090 diff --git a/APPLICATIONS/springboot-async-example/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-async-example/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-async-example/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-async-exception-handler/.gitignore b/APPLICATIONS/springboot-async-exception-handler/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-async-exception-handler/README.md b/APPLICATIONS/springboot-async-exception-handler/README.md new file mode 100644 index 00000000..00087192 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/README.md @@ -0,0 +1,15 @@ +### springboot async exception handling + +### To build +* mvn clean package + + +### To Run +* mvn spring-boot:run + + +### api url +* with exception call + * curl -X GET http://localhost:8080/wish/0 +* without exception call + * curl -X GET http://localhost:8080/wish/1 \ No newline at end of file diff --git a/APPLICATIONS/springboot-async-exception-handler/pom.xml b/APPLICATIONS/springboot-async-exception-handler/pom.xml new file mode 100644 index 00000000..b82c8093 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.0 + + + com.espark.adarsh + springboot-async-exception-handler + 0.0.1-SNAPSHOT + springboot-async-exception-handler + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1311d655 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@EnableAsync +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..a2af276f --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.exception.handler.ApplicationExceptionHandler; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +public class ApplicationConfig implements AsyncConfigurer { + + @Bean(name = "threadPoolTaskExecutor") + public Executor threadPoolTaskExecutor() { + return new ThreadPoolTaskExecutor(); + } + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); + threadPoolTaskExecutor.initialize(); + return threadPoolTaskExecutor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new ApplicationExceptionHandler(); + } +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/ApplicationException.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/ApplicationException.java new file mode 100644 index 00000000..39928248 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/ApplicationException.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.exception; + +public class ApplicationException extends RuntimeException{ + + public ApplicationException() { + } + + public ApplicationException(String message) { + super(message); + } + + public ApplicationException(String message, Throwable cause) { + super(message, cause); + } + + public ApplicationException(Throwable cause) { + super(cause); + } + + public ApplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/handler/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/handler/ApplicationExceptionHandler.java new file mode 100644 index 00000000..c9b376f5 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/exception/handler/ApplicationExceptionHandler.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.exception.handler; + +import com.espark.adarsh.exception.ApplicationException; +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import java.lang.reflect.Method; +import java.net.http.HttpRequest; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@ControllerAdvice +public class ApplicationExceptionHandler implements AsyncUncaughtExceptionHandler { + + + @ExceptionHandler(value = {ApplicationException.class}) + public Map handleApplicationException(HttpServletRequest request, ApplicationException ex) { + log.error("ApplicationExceptionHandler {} ", ex.getMessage()); + String reqUrl = request.getRequestURL().toString(); + return new HashMap<>() { + { + put("exception", ex.getMessage()); + put("request-url", reqUrl); + } + }; + } + + + @Override + public void handleUncaughtException(Throwable ex, Method method, Object... params) { + log.error("ApplicationExceptionHandler ASYNC {} ", ex.getMessage()); + } +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..1991d2e9 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.exception.ApplicationException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class ApplicationService { + + @Async + public void doWork() throws InterruptedException { + int counter = 0; + while (counter < 100) { + log.info("value of counter is {} Thread Name {}", counter, Thread.currentThread().getName()); + Thread.sleep(1000); + if (counter == 10) { + throw new ApplicationException("10 VALUE is not a good value "); + } + counter++; + } + } + +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..37d4d610 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.exception.ApplicationException; +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @Autowired + ApplicationService applicationService; + + @GetMapping("/wish/{value}") + public String doWork(@PathVariable Integer value) throws Exception { + if (value == 0) { + throw new ApplicationException("it's time for exception "); + } + this.applicationService.doWork(); + return "do work request accepted "; + } +} diff --git a/APPLICATIONS/springboot-async-exception-handler/src/main/resources/application.properties b/APPLICATIONS/springboot-async-exception-handler/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-async-exception-handler/src/test/java/com/espark/adarsh/SpringbootAsyncExceptionHandlerApplicationTests.java b/APPLICATIONS/springboot-async-exception-handler/src/test/java/com/espark/adarsh/SpringbootAsyncExceptionHandlerApplicationTests.java new file mode 100644 index 00000000..ea93e332 --- /dev/null +++ b/APPLICATIONS/springboot-async-exception-handler/src/test/java/com/espark/adarsh/SpringbootAsyncExceptionHandlerApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootAsyncExceptionHandlerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/.gitignore b/APPLICATIONS/springboot-awssqs-elasticmq/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/document/custom.conf b/APPLICATIONS/springboot-awssqs-elasticmq/document/custom.conf new file mode 100644 index 00000000..4a1da6fe --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/document/custom.conf @@ -0,0 +1,35 @@ +include classpath("application.conf") + +// What is the outside visible address of this ElasticMQ node +// Used to create the queue URL (may be different from bind address!) +node-address { + protocol = http + host = localhost + port = 9325 + context-path = "" +} + +rest-sqs { + enabled = true + bind-port = 9325 + bind-hostname = "0.0.0.0" + // Possible values: relaxed, strict + sqs-limits = strict +} + +// Should the node-address be generated from the bind port/hostname +// Set this to true e.g. when assigning port automatically by using port 0. +generate-node-address = false + +queues { + queue1 { + defaultVisibilityTimeout = 10 seconds + delay = 5 seconds + receiveMessageWait = 0 seconds + espark { + name = "espark" + maxReceiveCount = 3 // from 1 to 1000 + } + } + espark { } +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/document/help.txt b/APPLICATIONS/springboot-awssqs-elasticmq/document/help.txt new file mode 100644 index 00000000..8f3a2aee --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/document/help.txt @@ -0,0 +1,58 @@ +$ cd document/ + +$ pwd +/springboot-awssqs-elasticmq/document + +$ vi custom.conf +------------------------------------------------- +include classpath("application.conf") + +// What is the outside visible address of this ElasticMQ node +// Used to create the queue URL (may be different from bind address!) +node-address { + protocol = http + host = localhost + port = 9325 + context-path = "" +} + +rest-sqs { + enabled = true + bind-port = 9325 + bind-hostname = "0.0.0.0" + // Possible values: relaxed, strict + sqs-limits = strict +} + +// Should the node-address be generated from the bind port/hostname +// Set this to true e.g. when assigning port automatically by using port 0. +generate-node-address = false + +queues { + queue1 { + defaultVisibilityTimeout = 10 seconds + delay = 5 seconds + receiveMessageWait = 0 seconds + deadLettersQueue { + name = "espark" + maxReceiveCount = 3 // from 1 to 1000 + } + } + espark { } +} + +------------------------------------------------- +$ java -Dconfig.file=custom.conf -Dlogback.configurationFile=my_logback.xml -jar elasticmq-server-0.13.9.jar + + +$ mvn clean package + +http post +http://localhost:9090/espark/msg +{ + "queueName":"espark", + "msg":"radha u r my life" +} + +http get +http://localhost:9090/espark/msg/espark diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/document/my_logback.xml b/APPLICATIONS/springboot-awssqs-elasticmq/document/my_logback.xml new file mode 100644 index 00000000..685be1c4 --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/document/my_logback.xml @@ -0,0 +1,21 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/pom.xml b/APPLICATIONS/springboot-awssqs-elasticmq/pom.xml new file mode 100644 index 00000000..84facd3e --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-awssqs-elasticmq + 0.0.1-SNAPSHOT + jar + + springboot-awssqs-elasticmq + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.amazonaws + aws-java-sdk-sqs + 1.11.312 + + + + com.amazonaws + aws-java-sdk-core + 1.11.312 + + + + com.amazonaws + amazon-sqs-java-messaging-lib + 1.0.3 + + + + org.springframework + spring-jms + 5.0.5.RELEASE + + + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.13.9 + + + + org.projectlombok + lombok + 1.16.0 + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.13.9 + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.13.9 + + + org.elasticmq + elasticmq-rest-sqs_2.11 + 0.13.9 + + + + org.springframework.boot + spring-boot-starter-activemq + 1.4.0.RELEASE + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/controller/MessageController.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/controller/MessageController.java new file mode 100644 index 00000000..ecb69c22 --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/controller/MessageController.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.service.QueueService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +public class MessageController { + + @Autowired + QueueService queueService; + + @RequestMapping(value = "/espark/msg",method = RequestMethod.POST) + public void sendMesage(@RequestBody Map data){ + this.queueService.sendMessage(data.get("queueName"),data.get("msg")); + } + + + @RequestMapping(value = "/espark/msg/{queueName}",method = RequestMethod.GET) + public List recivedMesage(@PathVariable("queueName") String queueName){ + return this.queueService.getMessage(queueName); + } +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasicMqConfiguration.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasicMqConfiguration.java new file mode 100644 index 00000000..cc174c8a --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasicMqConfiguration.java @@ -0,0 +1,94 @@ +package com.espark.adarsh.emq; + +import com.amazon.sqs.javamessaging.ProviderConfiguration; +import com.amazon.sqs.javamessaging.SQSConnectionFactory; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.client.builder.AwsClientBuilder; +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.AmazonSQSClient; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; +import com.amazonaws.services.sqs.model.*; +import com.espark.adarsh.emq.ElasticMQ; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.jms.ConnectionFactory; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Slf4j +@Configuration +public class ElasicMqConfiguration { + + + + @Value("${elastic.mq.name}") + private String[] queueNamesArray ; + + @Value("${elastic.mq.port}") + private int mqPort = 9325; + + @Value("${elastic.mq.host}") + private String mqHost; + + @Value("${elastic.mq.region}") + private String region; + + @Value("${aws.access.key}") + private String accessKey; + + @Value("${aws.secret.key}") + private String secretKey; + + private List queueNames; + + private Map queueMap = new ConcurrentHashMap<>(); + + @PostConstruct + public void init(){ + queueNames = Arrays.asList(queueNamesArray); + AmazonSQS client = AmazonSQSClientBuilder.standard() + .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))) + .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(mqHost+mqPort, region)) + .build(); + for (String queueName : queueNames) { + client.createQueue(queueName); + ElasticMQ sqsQueue = new ElasticMQ(client,client.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl()); + queueMap.put(queueName, sqsQueue); + } + } + + @Bean + ConnectionFactory mqConnectionFactory() { + AmazonSQSClient amazonSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")); + amazonSQSClient.setEndpoint("http://localhost:" + mqPort); + return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQSClient); + } + + @PreDestroy + void destroy() { + queueMap.entrySet().forEach( (Map.Entry entry) -> { + ElasticMQ sqsQueue=entry.getValue(); + sqsQueue.purge(); + System.out.println(sqsQueue); + }); + } + + public ElasticMQ getSqsQueue(String queueName){ + return this.queueMap.get(queueName); + } + + public Map getQueueMap() { + return queueMap; + } +} + + + diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasticMQ.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasticMQ.java new file mode 100644 index 00000000..14cb3465 --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/emq/ElasticMQ.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.emq; + +import com.amazonaws.services.sqs.AmazonSQSClient; +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.model.*; + +import java.util.List; + +public class ElasticMQ { + + private AmazonSQS client; + private String queueUrl; + + public ElasticMQ(AmazonSQS client, String queueUrl) { + this.client = client; + this.queueUrl = queueUrl; + } + + public void send(Message toSend) { + SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, toSend.getBody()); + sendMessageRequest.setMessageAttributes(toSend.getMessageAttributes()); + client.sendMessage(sendMessageRequest); + } + + public List read(int maxMessages) { + ReceiveMessageRequest request = new ReceiveMessageRequest(queueUrl); + request.setMaxNumberOfMessages(maxMessages); + ReceiveMessageResult receiveMessage = client.receiveMessage(request); + return receiveMessage.getMessages(); + } + + public void purge() { + client.purgeQueue(new PurgeQueueRequest(queueUrl)); + } +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/service/QueueService.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/service/QueueService.java new file mode 100644 index 00000000..a2f961b2 --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/java/com/espark/adarsh/service/QueueService.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.service; + +import com.amazonaws.services.sqs.model.Message; +import com.espark.adarsh.emq.ElasicMqConfiguration; +import com.espark.adarsh.emq.ElasticMQ; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +@Service +public class QueueService { + + @Autowired + private ElasicMqConfiguration elasicMqConfiguration; + + private Map queueMap = new ConcurrentHashMap<>(); + + @PostConstruct + public void init(){ + queueMap=this.elasicMqConfiguration.getQueueMap(); + } + + public void sendMessage(String queueName,String data){ + Message message= new Message(); + message.setBody(data); + message.setMessageId(new Date().toString()); + queueMap.get(queueName).send(message); + } + + public List getMessage(String queueName){ + List messageList=queueMap.get(queueName).read(5); + return messageList.stream().map(message->{ + return message.getBody(); + }).collect(Collectors.toList()); + } + +} diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/main/resources/application.properties b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/resources/application.properties new file mode 100644 index 00000000..8078456e --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/main/resources/application.properties @@ -0,0 +1,9 @@ +server.port=9090 + +elastic.mq.port=9325 +elastic.mq.host=http://localhost: +elastic.mq.region=elasticmq +aws.access.key=x +aws.secret.key=x + +elastic.mq.name=espark,adarsh,radha diff --git a/APPLICATIONS/springboot-awssqs-elasticmq/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-awssqs-elasticmq/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..7a2139fb --- /dev/null +++ b/APPLICATIONS/springboot-awssqs-elasticmq/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationMainTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-aync-api-test/.gitignore b/APPLICATIONS/springboot-aync-api-test/.gitignore new file mode 100644 index 00000000..3f950040 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-aync-api-test/README.md b/APPLICATIONS/springboot-aync-api-test/README.md new file mode 100644 index 00000000..ef5b1cc9 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/README.md @@ -0,0 +1,16 @@ +# spring boot async api and test +--- + +### To Build Code +* mvn clean package + + + +### To run +* mvn spring-boot:run + + +### To hit api +* $ curl -X GET http://localhost:8080/wish + + diff --git a/APPLICATIONS/springboot-aync-api-test/pom.xml b/APPLICATIONS/springboot-aync-api-test/pom.xml new file mode 100644 index 00000000..eb9b5f4b --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.0 + + + com.espark.adarsh + springboot-aync-api-test + 0.0.1-SNAPSHOT + springboot-aync-api-test + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java new file mode 100644 index 00000000..fe351007 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootAyncApiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootAyncApiApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..711221ff --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +@Configuration +public class ApplicationConfig implements WebMvcConfigurer { + + public ApplicationConfig() { + } + + @Override + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + configurer.setTaskExecutor(taskExecutor()); + configurer.setDefaultTimeout(30_000); + } + + @Bean + public ThreadPoolTaskExecutor taskExecutor(){ + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setThreadNamePrefix("app-task"); + return taskExecutor; + } +} diff --git a/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..609c7111 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.task.TaskExecutor; +import org.springframework.stereotype.Service; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ThreadLocalRandom; + + +@Slf4j +@Service +public class ApplicationService { + + private final TaskExecutor taskExecutor; + + public ApplicationService(TaskExecutor taskExecutor) { + this.taskExecutor = taskExecutor; + } + + public CompletableFuture wish(){ + return CompletableFuture.supplyAsync(()->{ + randomDelay(); + return System.getProperty("user.name")+" Welcome to the Espark "; + },taskExecutor); + } + + private void randomDelay(){ + try{ + Thread.sleep(ThreadLocalRandom.current().nextInt(5000)); + }catch (InterruptedException e){ + log.error("exception {}",e.getMessage()); + } + } + +} diff --git a/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..bf7aeddf --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.CompletableFuture; + +@RestController +public class ApplicationController { + + @Autowired + ApplicationService applicationService; + + @GetMapping("/wish") + public CompletableFuture wish(){ + return this.applicationService.wish(); + } +} diff --git a/APPLICATIONS/springboot-aync-api-test/src/main/resources/application.properties b/APPLICATIONS/springboot-aync-api-test/src/main/resources/application.properties new file mode 100644 index 00000000..1a060ded --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/main/resources/application.properties @@ -0,0 +1,2 @@ +logging.level.org.springframework=INFO +logging.level.com.espark.adarsh=DEBUG diff --git a/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java b/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java new file mode 100644 index 00000000..a069f15c --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootAyncApiTestApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java b/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java new file mode 100644 index 00000000..9534c460 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api-test/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.SpringbootAyncApiApplication; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@Slf4j +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +public class ApplicationControllerTest { + + + @Autowired + MockMvc mockMvc; + + + @Test + public void testApi() throws Exception { + MvcResult mvcResult = mockMvc.perform(get("/wish") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } +} diff --git a/APPLICATIONS/springboot-aync-api/.gitignore b/APPLICATIONS/springboot-aync-api/.gitignore new file mode 100644 index 00000000..3f950040 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-aync-api/README.md b/APPLICATIONS/springboot-aync-api/README.md new file mode 100644 index 00000000..ef5b1cc9 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/README.md @@ -0,0 +1,16 @@ +# spring boot async api and test +--- + +### To Build Code +* mvn clean package + + + +### To run +* mvn spring-boot:run + + +### To hit api +* $ curl -X GET http://localhost:8080/wish + + diff --git a/APPLICATIONS/springboot-aync-api/pom.xml b/APPLICATIONS/springboot-aync-api/pom.xml new file mode 100644 index 00000000..39464f71 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.0 + + + com.espark.adarsh + springboot-aync-api + 0.0.1-SNAPSHOT + springboot-aync-api + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java new file mode 100644 index 00000000..fe351007 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/SpringbootAyncApiApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootAyncApiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootAyncApiApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..2edd6ec1 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.concurrent.Executor; + +@EnableAsync +@Configuration +public class ApplicationConfig { + + public ApplicationConfig() { + } + + @Bean + public Executor taskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(2); + executor.setMaxPoolSize(2); + executor.setQueueCapacity(500); + executor.setThreadNamePrefix("espark-"); + executor.initialize(); + return executor; + } +} diff --git a/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..47acf14b --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ThreadLocalRandom; + + +@Slf4j +@Service +public class ApplicationService { + + + @Async + public CompletableFuture wish(){ + randomDelay(); + return CompletableFuture.completedFuture(System.getProperty("user.name")+" Welcome to the Espark "); + } + + private void randomDelay(){ + try{ + Thread.sleep(ThreadLocalRandom.current().nextInt(5000)); + }catch (InterruptedException e){ + log.error("exception {}",e.getMessage()); + } + } + +} diff --git a/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..bf7aeddf --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.ApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.concurrent.CompletableFuture; + +@RestController +public class ApplicationController { + + @Autowired + ApplicationService applicationService; + + @GetMapping("/wish") + public CompletableFuture wish(){ + return this.applicationService.wish(); + } +} diff --git a/APPLICATIONS/springboot-aync-api/src/main/resources/application.properties b/APPLICATIONS/springboot-aync-api/src/main/resources/application.properties new file mode 100644 index 00000000..d27f0f45 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/main/resources/application.properties @@ -0,0 +1,4 @@ +logging.level.org.springframework=DEBUG +logging.level.com.espark.adarsh=DEBUG + +enableLoggingRequestDetails=true diff --git a/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java b/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java new file mode 100644 index 00000000..a069f15c --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/SpringbootAyncApiTestApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootAyncApiTestApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java b/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java new file mode 100644 index 00000000..9534c460 --- /dev/null +++ b/APPLICATIONS/springboot-aync-api/src/test/java/com/espark/adarsh/web/ApplicationControllerTest.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.SpringbootAyncApiApplication; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@Slf4j +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +public class ApplicationControllerTest { + + + @Autowired + MockMvc mockMvc; + + + @Test + public void testApi() throws Exception { + MvcResult mvcResult = mockMvc.perform(get("/wish") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } +} diff --git a/APPLICATIONS/springboot-basic-crud-example/.gitignore b/APPLICATIONS/springboot-basic-crud-example/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-basic-crud-example/README.md b/APPLICATIONS/springboot-basic-crud-example/README.md new file mode 100644 index 00000000..7c9304a3 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/README.md @@ -0,0 +1,102 @@ +# SPRINGBOOT-BASIC-CRUD-EXAMPLE + +--- + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +### Get Request +* http://localhost:8080/employees +* curl --location --request GET 'http://localhost:8080/employees' --header 'Content-Type: application/json' +``` +[ + { + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" + }, + { + "id": 2, + "firstName": "radha", + "lastName": "singh", + "career": "IT" + }, + { + "id": 3, + "firstName": "sonu", + "lastName": "singh", + "career": "IT" + }, + { + "id": 4, + "firstName": "amit", + "lastName": "kumar", + "career": "Finance" + } +] +``` + + +### Get Request +* http://localhost:8080/employee/1 +* curl --location --request GET 'http://localhost:8080/employee/1' +``` + { + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" +} +``` + +### Post Request +* http://localhost:8080/employee +* curl --location --request POST 'http://localhost:8080/employee' \ + --header 'Content-Type: application/json' \ + --data-raw '{"id": 5,"firstName": "shakti","lastName": "singh","career": "Operatons" }' +``` + { + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "Operatons" +} +``` + +### Put Request +* http://localhost:8080/employee/5 +* curl --location --request PUT 'http://localhost:8080/employee/5' \ + --header 'Content-Type: application/json' \ + --data-raw '{"id": 5,"firstName": "shakti","lastName": "singh","career": "founder"}' +``` +{ + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "founder" +} +``` + +### Patch Request +* http://localhost:8080/employee/5 +* curl --location --request PATCH 'http://localhost:8080/employee/5' \ + --header 'Content-Type: application/json' \ + --data-raw '{"career": "founder-invester"}' +``` + { + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "founder-invester" +} +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-basic-crud-example/pom.xml b/APPLICATIONS/springboot-basic-crud-example/pom.xml new file mode 100644 index 00000000..904d5d5d --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.5 + + + com.espark.adarsh + springboot-basic-crud-example + 0.0.1-SNAPSHOT + springboot-basic-crud-example + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..ff33a9ed --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,63 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..10b3d390 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.exception; + + +public class EmployeeNotFoundException extends RuntimeException{ + + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..aa11d367 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,62 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.ReflectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.lang.reflect.Field; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } + + public Employee updatePartialEmployee(@PathVariable("id") Long id, Map employee) { + final Optional employeeOptional = this.employeeRepository.findById(id); + if (employeeOptional.isPresent()) { + employee.forEach((key, value) -> { + Field field = ReflectionUtils.findField(Employee.class, key); + field.setAccessible(true); + ReflectionUtils.setField(field, employeeOptional.get(), value); + }); + return this.employeeRepository.save(employeeOptional.get()); + } + return employeeOptional.orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + } + +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..401f83ac --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id,employee); + } + + @PatchMapping("/employee/{id}") + public Employee updatePartialEmployee(@PathVariable("id") Long id, @RequestBody Map employee) { + return this.employeeService.updatePartialEmployee(id,employee); + } + +} diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/resources/application.properties b/APPLICATIONS/springboot-basic-crud-example/src/main/resources/application.properties new file mode 100644 index 00000000..1706201e --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/resources/application.properties @@ -0,0 +1,14 @@ + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true + + diff --git a/APPLICATIONS/springboot-basic-crud-example/src/main/resources/data.sql b/APPLICATIONS/springboot-basic-crud-example/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-basic-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicCrudExampleApplicationTests.java b/APPLICATIONS/springboot-basic-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicCrudExampleApplicationTests.java new file mode 100644 index 00000000..ca0df3e2 --- /dev/null +++ b/APPLICATIONS/springboot-basic-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicCrudExampleApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootBasicCrudExampleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-basic/.gitignore b/APPLICATIONS/springboot-basic/.gitignore new file mode 100644 index 00000000..f7ce4163 --- /dev/null +++ b/APPLICATIONS/springboot-basic/.gitignore @@ -0,0 +1,33 @@ +.mvn +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-basic/README.md b/APPLICATIONS/springboot-basic/README.md new file mode 100644 index 00000000..9c6cbbd3 --- /dev/null +++ b/APPLICATIONS/springboot-basic/README.md @@ -0,0 +1,19 @@ +# 2.x Spring boot Basic Example with Mock Test & Integration Test + +--- + +### To Build the application +* >mvn clean package + +### To Execute the Application +* >mvn spring-boot:run +* >java -jar target/springboot-basic-0.0.1-SNAPSHOT.jar + +### To Build and Run together +* > mvn package && -jar target/springboot-basic-0.0.1-SNAPSHOT.jar + +### To get the output +* url http://localhost:8080/api/welcome + +### To exit from Execution +* ctrl-c diff --git a/APPLICATIONS/springboot-basic/pom.xml b/APPLICATIONS/springboot-basic/pom.xml new file mode 100644 index 00000000..081f8a5d --- /dev/null +++ b/APPLICATIONS/springboot-basic/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.2 + + + com.espark.adarsh + springboot-basic + 0.0.1-SNAPSHOT + springboot-basic + Basic project for Spring Boot + + + ESpark + http://adarshkumarsingh83.blogspot.in/ + + + + + ESpark + http://adarshkumarsingh83.blogspot.in/licenses/LICENSE-2.0.txt + repo + + + + + + adarshkumarsingh83 + Adarsh Kumar + adarshkumarsingh83@gmail.com + + project architect + + + + + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/SpringbootBasicApplication.java b/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/SpringbootBasicApplication.java new file mode 100644 index 00000000..fb0cf6a8 --- /dev/null +++ b/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/SpringbootBasicApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootBasicApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootBasicApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..1c15cc83 --- /dev/null +++ b/APPLICATIONS/springboot-basic/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.web; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + + @Value("${message}") + private String message; + + @GetMapping(value = "/welcome" + , produces = {"application/json"}) + public Map welcomeMessage() { + final Map responseMessage = new HashMap() { + { + put("name", System.getProperty("user.name")); + put("responseMessage", "Hello " + System.getProperty("user.name") + " " + message); + } + }; + return responseMessage; + } + +} diff --git a/APPLICATIONS/springboot-basic/src/main/resources/application.properties b/APPLICATIONS/springboot-basic/src/main/resources/application.properties new file mode 100644 index 00000000..ffc078a7 --- /dev/null +++ b/APPLICATIONS/springboot-basic/src/main/resources/application.properties @@ -0,0 +1,17 @@ + +server.port=8080 +message=Welcome To Spring Boot + + +logging.level.root = DEBUG +logging.level.org.springframework=DEBUG +logging.level.com.espark.adarsh=DEBUG + +#output to a temp_folder/file +logging.file=./log/application.log + +# Logging pattern for the console +logging.pattern.console= %d{yyyy-MM-dd HH:mm:ss} - %msg%n + +# Logging pattern for file +logging.pattern.file= %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg% \ No newline at end of file diff --git a/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationIntegrationTests.java b/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationIntegrationTests.java new file mode 100644 index 00000000..c236ce33 --- /dev/null +++ b/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationIntegrationTests.java @@ -0,0 +1,73 @@ +package com.espark.adarsh; + +import com.espark.adarsh.web.ApplicationController; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@SpringBootTest(classes = SpringbootBasicApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class SpringbootBasicApplicationIntegrationTests { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Value("${message}") + private String message; + + private URL base; + private ObjectMapper jsonMapper; + + @BeforeEach + public void setUp() throws Exception { + this.base = new URL("http://localhost:" + port + "/api/welcome"); + this.jsonMapper = new ObjectMapper(); + } + + + @Test + public void getHello() throws Exception { + ResponseEntity responseEntity = restTemplate.getForEntity(base.toString(), String.class); + assertEquals(200, responseEntity.getStatusCodeValue()); + final String jsonString = responseEntity.getBody(); + Map responseMap = this.jsonMapper.readValue(jsonString, new TypeReference>() { + }); + assertThat(responseMap.get("name"), equalTo(System.getProperty("user.name"))); + assertThat(responseMap.get("msg"), equalTo("Hello " + System.getProperty("user.name") + " " + message)); + } +} diff --git a/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationTests.java b/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationTests.java new file mode 100644 index 00000000..bb099fe3 --- /dev/null +++ b/APPLICATIONS/springboot-basic/src/test/java/com/espark/adarsh/SpringbootBasicApplicationTests.java @@ -0,0 +1,48 @@ +package com.espark.adarsh; + +import com.espark.adarsh.web.ApplicationController; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockServletContext; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +/** + * @author Adarsh Kumar + * @author $LastChangedBy: Adarsh Kumar$ + * @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$ + * @Espark @copyright all right reserve + */ + +@SpringBootTest +@WebAppConfiguration +class SpringbootBasicApplicationTests { + + private MockMvc mvc; + + @Test + void contextLoads() { + } + + + @BeforeEach + public void setUp() throws Exception { + mvc = MockMvcBuilders.standaloneSetup(new ApplicationController()).build(); + } + + @Test + public void getHello() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/api/welcome").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Hello " + System.getProperty("user.name")))); + } +} diff --git a/APPLICATIONS/springboot-batch-example/doc/help.txt b/APPLICATIONS/springboot-batch-example/doc/help.txt new file mode 100644 index 00000000..3e7d6bca --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/doc/help.txt @@ -0,0 +1,40 @@ +cmd line arugments + +preTask=a,b,c task=x,y postTask=p,q + +preTask= +task= +postTask= + +cmd will look like this +preTask=samplePreExecutionTask task=sampleExecutionTask,sampleExecutionOneTask,sampleExecutionTwoTask postTask=samplePostExecutionTask + +task=sampleExecutionOneTask,sampleExecutionTask,sampleExecutionTwoTask postTask=samplePostExecutionTask + +preTask=samplePreExecutionTask task=sampleExecutionTask,sampleExecutionOneTask,sampleExecutionTwoTask + +task=sampleExecutionTask,sampleExecutionOneTask,sampleExecutionTwoTask + +#by default default pre execution and post task will execute. +#all the operation execution will be created under operation dir + +#for preTask +implement the PreExecutionTask +#use annotation and give the bean name +@PreExecutionOperation(name = "defaultPreExecutionTask") + +#for task +implement the ExecutionTask +#use annotation and give the bean name +@ExecutionOperation(name = "defaultExecutionTask") + +#for postTask +implement the PostExecutionTask +#use annotation and give the bean name +@PostExecutionOperation(name = "defaultPostExecutionTask") + +#cmd to build the code +$ mvn clean package + + + diff --git a/APPLICATIONS/springboot-batch-example/pom.xml b/APPLICATIONS/springboot-batch-example/pom.xml new file mode 100644 index 00000000..90c975e2 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + springboot-batch-example + springboot-batch-example + 1.0-SNAPSHOT + + springboot-batch-example + http://maven.apache.org + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-batch + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + 1.18.4 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + repository.spring.release + Spring GA Repository + http://repo.spring.io/release + + + diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..afcc4cce --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,32 @@ +package com.espark.adarsh; + +import org.springframework.batch.core.Job; +import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain implements CommandLineRunner { + + @Autowired + private Job job; + + @Autowired + private JobLauncher jobLauncher; + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + + @Override + public void run(String... args) throws Exception { + JobParameters params = new JobParametersBuilder() + .addString("JobID", String.valueOf(System.currentTimeMillis())) + .toJobParameters(); + jobLauncher.run(job, params); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/ExecutionOperation.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/ExecutionOperation.java new file mode 100644 index 00000000..1690ca43 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/ExecutionOperation.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.annotation; + + +import org.springframework.stereotype.Component; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Component +@Documented +public @interface ExecutionOperation { + + String name() default ""; + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PostExecutionOperation.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PostExecutionOperation.java new file mode 100644 index 00000000..823bfc13 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PostExecutionOperation.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.annotation; + + +import org.springframework.stereotype.Component; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Component +@Documented +public @interface PostExecutionOperation { + + String name() default ""; + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PreExecutionOperation.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PreExecutionOperation.java new file mode 100644 index 00000000..d301acc7 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/annotation/PreExecutionOperation.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.annotation; + + +import org.springframework.stereotype.Component; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Component +@Documented +public @interface PreExecutionOperation { + + String name() default ""; + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfiguration.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfiguration.java new file mode 100644 index 00000000..ecae6cd1 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfiguration.java @@ -0,0 +1,283 @@ +package com.espark.adarsh.config; + +import static com.espark.adarsh.constant.ApplicationConstant.EXECUTION; +import static com.espark.adarsh.constant.ApplicationConstant.POST_EXECUTION; +import static com.espark.adarsh.constant.ApplicationConstant.POST_TASK; +import static com.espark.adarsh.constant.ApplicationConstant.PRE_EXECUTION; +import static com.espark.adarsh.constant.ApplicationConstant.PRE_TASK; +import static com.espark.adarsh.constant.ApplicationConstant.SEPARATOR_COMMA; +import static com.espark.adarsh.constant.ApplicationConstant.SEPARATOR_EQUALS; +import static com.espark.adarsh.constant.ApplicationConstant.TASK; + +import com.espark.adarsh.annotation.ExecutionOperation; +import com.espark.adarsh.annotation.PostExecutionOperation; +import com.espark.adarsh.annotation.PreExecutionOperation; +import com.espark.adarsh.listener.JobCompletionNotificationListener; +import com.espark.adarsh.operation.construct.ExecutionTask; +import com.espark.adarsh.task.OperationPostExecutionTask; +import com.espark.adarsh.task.OperationPreExecutionTask; +import com.espark.adarsh.task.OperationExecutionTask; +import com.espark.adarsh.operation.construct.PostExecutionTask; +import com.espark.adarsh.operation.construct.PreExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.batch.core.launch.support.RunIdIncrementer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.boot.ApplicationArguments; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.type.filter.AssignableTypeFilter; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; + + +@Slf4j +@Configuration +@EnableBatchProcessing +public class BatchConfiguration { + + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Autowired + private ApplicationContext applicationContext; + + @Autowired + private ApplicationArguments applicationArguments; + + @Autowired + private BatchConfigurationValues batchConfigurationValues; + + public Map commandArgs = new HashMap<>(); + + private Map> operations = null; + + private static LinkedHashMap preExecutionOperations = new LinkedHashMap<>(); + private static LinkedHashMap executionOperations = new LinkedHashMap<>(); + private static LinkedHashMap postExecutionOperations = new LinkedHashMap<>(); + + + @PostConstruct + public void init() throws Exception { + + // pre=a,b,c execution=x,y post=p,q + final String args[] = applicationArguments.getSourceArgs(); + + if (args.length == 0) { + throw new RuntimeException("Command line argument is empty"); + } + + for (String cmd : args) { + + String key = cmd.split(SEPARATOR_EQUALS)[0]; + String[] values = cmd.split(SEPARATOR_EQUALS)[1].split(SEPARATOR_COMMA); + commandArgs.put(key, Arrays.asList(values)); + } + + if (operations == null) { + operations = this.scanOperations(); + } + + } + + @Bean + public Step operationPreExecutionTask() { + return steps.get("operationPreExecutionTask") + .tasklet(new OperationPreExecutionTask()) + .build(); + } + + @Bean + public Step operationExecutionTask() { + return steps.get("operationExecutionTask") + .tasklet(new OperationExecutionTask()) + .build(); + } + + + @Bean + public Step operationPostExecutionTask() { + return steps.get("operationPostExecutionTask") + .tasklet(new OperationPostExecutionTask()) + .build(); + } + + + @Bean + public Job operationInitTask() { + return jobs.get("operationInitTask") + .incrementer(new RunIdIncrementer()) + .start(operationPreExecutionTask()) + .next(operationExecutionTask()) + .next(operationPostExecutionTask()) + .listener(listener()) + .build(); + } + + @Bean + public JobCompletionNotificationListener listener() { + return new JobCompletionNotificationListener(); + } + + + @Bean("executionOperationsMap") + public LinkedHashMap executionOperationsMap() { + LinkedHashMap operationClassMap = operations.get(EXECUTION); + if (operationClassMap != null && !operationClassMap.isEmpty()) { + for (Map.Entry entry : operationClassMap.entrySet()) { + Class clazz = entry.getValue(); + ExecutionTask executionTask = (ExecutionTask) applicationContext.getBean(clazz); + executionOperations.put(entry.getKey(), executionTask); + } + } + return executionOperations; + } + + @Bean("preExecutionOperationsMap") + public LinkedHashMap preExecutionOperationsMap() { + LinkedHashMap operationClassMap = operations.get(PRE_EXECUTION); + if (operationClassMap != null && !operationClassMap.isEmpty()) { + for (Map.Entry entry : operationClassMap.entrySet()) { + Class clazz = entry.getValue(); + PreExecutionTask preExecutionTask = (PreExecutionTask) applicationContext.getBean(clazz); + preExecutionOperations.put(entry.getKey(), preExecutionTask); + } + } + return preExecutionOperations; + } + + @Bean("postExecutionOperationsMap") + public LinkedHashMap postExecutionOperationsMap() { + LinkedHashMap operationClassMap = operations.get(POST_EXECUTION); + if (operationClassMap != null && !operationClassMap.isEmpty()) { + for (Map.Entry entry : operationClassMap.entrySet()) { + Class clazz = entry.getValue(); + PostExecutionTask postExecutionTask = (PostExecutionTask) applicationContext.getBean(clazz); + postExecutionOperations.put(entry.getKey(), postExecutionTask); + } + } + return postExecutionOperations; + } + + /** + * + * @return + */ + private Map> scanOperations() { + Map> operations = new HashMap<>(); + LinkedHashMap executionOperations = new LinkedHashMap<>(); + LinkedHashMap preExecutionOperations = new LinkedHashMap<>(); + LinkedHashMap postExecutionOperations = new LinkedHashMap<>(); + String packageName = "com.espark.adarsh.operation"; + + List execution = null; + List pretExecution = null; + List postExecution = null; + + if (this.commandArgs != null && !this.commandArgs.isEmpty()) { + execution = (commandArgs.get(TASK) != null) ? (List) commandArgs.get(TASK) : null; + pretExecution = (commandArgs.get(PRE_TASK) != null) ? (List) commandArgs.get(PRE_TASK) : null; + postExecution = (commandArgs.get(POST_TASK) != null) ? (List) commandArgs.get(POST_TASK) : null; + } + + try { + final ClassPathScanningCandidateComponentProvider scanner = + new ClassPathScanningCandidateComponentProvider(true); + scanner.addIncludeFilter(new AssignableTypeFilter(Object.class)); + final Set beanDefinitionSet = scanner.findCandidateComponents(packageName); + try { + + for (BeanDefinition beanDefinition : beanDefinitionSet) { + final Class clazz = Class.forName(beanDefinition.getBeanClassName()); + if (clazz.getAnnotation(PreExecutionOperation.class) != null) { + PreExecutionOperation annotation = clazz.getAnnotation(PreExecutionOperation.class); + //filter out the based on the cmd line param + if (pretExecution != null && !pretExecution.isEmpty()) { + if (pretExecution.contains(annotation.name())) { + preExecutionOperations.put(annotation.name(), clazz); + } + } else if (annotation.name().equals(batchConfigurationValues.getValue().getPreTask())) { + preExecutionOperations.put(annotation.name(), clazz); + } + } else if (clazz.getAnnotation(ExecutionOperation.class) != null) { + ExecutionOperation annotation = clazz.getAnnotation(ExecutionOperation.class); + //filter out the based on the cmd line param + if (execution != null && !execution.isEmpty()) { + if (execution.contains(annotation.name())) { + executionOperations.put(annotation.name(), clazz); + } + } else if (annotation.name().equals(batchConfigurationValues.getValue().getTask())) { + executionOperations.put(annotation.name(), clazz); + } + } else if (clazz.getAnnotation(PostExecutionOperation.class) != null) { + PostExecutionOperation annotation = clazz.getAnnotation(PostExecutionOperation.class); + //filter out the based on the cmd line param + if (postExecution != null && !postExecution.isEmpty()) { + if (postExecution.contains(annotation.name())) { + postExecutionOperations.put(annotation.name(), clazz); + } + } else if (annotation.name().equals(batchConfigurationValues.getValue().getPostTask())) { + postExecutionOperations.put(annotation.name(), clazz); + } + } + } + } catch (ClassNotFoundException e) { + log.error("exception e={}", e); + } + } catch (Exception e) { + log.error("exception e={}", e); + } finally { + if (!executionOperations.isEmpty()) { + operations.put(EXECUTION, this.orderOperations(execution, executionOperations)); + } + if (!preExecutionOperations.isEmpty()) { + operations.put(PRE_EXECUTION, this.orderOperations(pretExecution, preExecutionOperations)); + } + if (!postExecutionOperations.isEmpty()) { + operations.put(POST_EXECUTION, this.orderOperations(postExecution, postExecutionOperations)); + } + } + return operations; + } + + public LinkedHashMap orderOperations(List orderList, LinkedHashMap operations) { + LinkedHashMap linkedHashMap = new LinkedHashMap(); + if (orderList != null && !orderList.isEmpty()) { + for (String order : orderList) { + linkedHashMap.put(order, operations.get(order)); + } + return linkedHashMap; + } + return operations; + } + + public static LinkedHashMap getPreExecutionOperations() { + return preExecutionOperations; + } + + public static LinkedHashMap getExecutionOperations() { + return executionOperations; + } + + public static LinkedHashMap getPostExecutionOperations() { + return postExecutionOperations; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfigurationValues.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfigurationValues.java new file mode 100644 index 00000000..7841481e --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/config/BatchConfigurationValues.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.config; + + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "espark.default") +public class BatchConfigurationValues { + + private Value value; + + @Data + static class Value { + private String preTask; + private String task; + private String postTask; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/constant/ApplicationConstant.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/constant/ApplicationConstant.java new file mode 100644 index 00000000..0a0fe695 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/constant/ApplicationConstant.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.constant; + + +public interface ApplicationConstant { + + public static final String PRE_TASK = "preTask"; + public static final String TASK = "task"; + public static final String POST_TASK = "postTask"; + + public static final String SEPARATOR_TASK = ";"; + public static final String SEPARATOR_EQUALS = "="; + public static final String SEPARATOR_COMMA = ","; + public static final String EMPTY_STRING = ""; + public static final String EXECUTION_ORDER = "execution_order"; + public static final String EXECUTION = "EXECUTION"; + public static final String PRE_EXECUTION = "PRE-EXECUTION"; + public static final String POST_EXECUTION = "POST-EXECUTION"; +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/listener/JobCompletionNotificationListener.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/listener/JobCompletionNotificationListener.java new file mode 100644 index 00000000..ca3e879e --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/listener/JobCompletionNotificationListener.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.listener; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.BatchStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.listener.JobExecutionListenerSupport; +import org.springframework.batch.item.ExecutionContext; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Slf4j +@Component +public class JobCompletionNotificationListener extends JobExecutionListenerSupport { + + @Override + public void afterJob(JobExecution jobExecution) { + ExecutionContext context = jobExecution.getExecutionContext(); + if (jobExecution.getStatus() == BatchStatus.COMPLETED) { + for (Map.Entry entry : context.entrySet()) { + log.info("==> "+entry.getKey() + " " + entry.getValue()); + } + } + } + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionOneTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionOneTask.java new file mode 100644 index 00000000..d1f1e536 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionOneTask.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.operation; + + +import com.espark.adarsh.annotation.ExecutionOperation; +import com.espark.adarsh.operation.construct.ExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@ExecutionOperation(name = "sampleExecutionOneTask") +public class SampleExecutionOneTask implements ExecutionTask { + + public Object executeTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("sampleExecutionOneTask", "executed "); + log.info("SampleExecutionOneTask task completed"); + return null; + } +} + + diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTask.java new file mode 100644 index 00000000..e36dbf5c --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTask.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.operation; + + +import com.espark.adarsh.annotation.ExecutionOperation; +import com.espark.adarsh.operation.construct.ExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@ExecutionOperation(name = "sampleExecutionTask") +public class SampleExecutionTask implements ExecutionTask { + + public Object executeTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("sampleExecutionTask", "executed "); + log.info("SampleExecutionTask task completed"); + return null; + } +} + + diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTwoTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTwoTask.java new file mode 100644 index 00000000..3df8c511 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SampleExecutionTwoTask.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.operation; + + +import com.espark.adarsh.annotation.ExecutionOperation; +import com.espark.adarsh.operation.construct.ExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@ExecutionOperation(name = "sampleExecutionTwoTask") +public class SampleExecutionTwoTask implements ExecutionTask { + + public Object executeTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("sampleExecutionTwoTask", "executed "); + log.info("SampleExecutionTwoTask task completed"); + return null; + } +} + + diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePostExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePostExecutionTask.java new file mode 100644 index 00000000..94c0d51f --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePostExecutionTask.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.operation; + + +import com.espark.adarsh.annotation.PostExecutionOperation; +import com.espark.adarsh.operation.construct.PostExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@PostExecutionOperation(name = "samplePostExecutionTask") +public class SamplePostExecutionTask implements PostExecutionTask { + + @Override + public Object executePostTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("samplePostExecutionTask", "executed "); + log.info("SamplePostExecutionTask task completed"); + return null; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePreExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePreExecutionTask.java new file mode 100644 index 00000000..a1e57103 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/SamplePreExecutionTask.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.operation; + + +import com.espark.adarsh.annotation.PreExecutionOperation; +import com.espark.adarsh.operation.construct.PreExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@PreExecutionOperation(name = "samplePreExecutionTask") +public class SamplePreExecutionTask implements PreExecutionTask { + + @Override + public Object executePreTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("samplePreExecutionTask", "executed "); + log.info("SamplePreExecutionTask task completed"); + return null; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/ExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/ExecutionTask.java new file mode 100644 index 00000000..eb6d98ad --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/ExecutionTask.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.operation.construct; + + +import org.springframework.batch.core.scope.context.ChunkContext; + +public interface ExecutionTask extends Task { + + Object executeTask(ChunkContext chunkContext); +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PostExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PostExecutionTask.java new file mode 100644 index 00000000..cafc472a --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PostExecutionTask.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.operation.construct; + + +import org.springframework.batch.core.scope.context.ChunkContext; + +public interface PostExecutionTask extends Task { + + Object executePostTask(ChunkContext chunkContext); +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PreExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PreExecutionTask.java new file mode 100644 index 00000000..86cc827e --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/PreExecutionTask.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.operation.construct; + + +import org.springframework.batch.core.scope.context.ChunkContext; + +public interface PreExecutionTask extends Task { + + Object executePreTask(ChunkContext chunkContext); + + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/Task.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/Task.java new file mode 100644 index 00000000..c39349df --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/Task.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.operation.construct; + +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.ExecutionContext; + +public interface Task { + + default ExecutionContext getExecutionContext(ChunkContext chunkContext) { + return chunkContext.getStepContext() + .getStepExecution() + .getJobExecution() + .getExecutionContext(); + } + +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultExecutionTask.java new file mode 100644 index 00000000..0bca9ff9 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultExecutionTask.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.operation.construct.implementation; + + +import com.espark.adarsh.annotation.ExecutionOperation; +import com.espark.adarsh.operation.construct.ExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@ExecutionOperation(name = "defaultExecutionTask") +public class DefaultExecutionTask implements ExecutionTask { + + public Object executeTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("defaultExecutionTask", "executed "); + log.info("DefaultExecutionTask task "); + return null; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPostExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPostExecutionTask.java new file mode 100644 index 00000000..73a5111f --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPostExecutionTask.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.operation.construct.implementation; + + +import com.espark.adarsh.annotation.PostExecutionOperation; +import com.espark.adarsh.operation.construct.PostExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@PostExecutionOperation(name = "defaultPostExecutionTask") +public class DefaultPostExecutionTask implements PostExecutionTask { + + @Override + public Object executePostTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("defaultPostExecutionTask", "executed "); + log.info("DefaultPostExecutionTask task "); + return null; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPreExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPreExecutionTask.java new file mode 100644 index 00000000..841b3dc0 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/operation/construct/implementation/DefaultPreExecutionTask.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.operation.construct.implementation; + + +import com.espark.adarsh.annotation.PreExecutionOperation; +import com.espark.adarsh.operation.construct.PreExecutionTask; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.scope.context.ChunkContext; + +@Slf4j +@PreExecutionOperation(name = "defaultPreExecutionTask") +public class DefaultPreExecutionTask implements PreExecutionTask { + + @Override + public Object executePreTask(ChunkContext chunkContext) { + getExecutionContext(chunkContext).put("defaultPreExecutionTask", "executed "); + log.info("DefaultPreExecutionTask task "); + return null; + } +} diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationExecutionTask.java new file mode 100644 index 00000000..d0447d47 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationExecutionTask.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.task; + +import com.espark.adarsh.config.BatchConfiguration; +import com.espark.adarsh.operation.construct.ExecutionTask; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Data +@Component +public class OperationExecutionTask implements Tasklet { + + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + log.info("OperationExecutionTask start.."); + LinkedHashMap executionOperationsMap = BatchConfiguration.getExecutionOperations(); + if (executionOperationsMap != null) { + for (Map.Entry entry : executionOperationsMap.entrySet()) { + String taskName = entry.getKey(); + ExecutionTask executionTask = entry.getValue(); + log.info("execution is starting for task={}", taskName); + executionTask.executeTask(chunkContext); + log.info("execution is completed for task={}", taskName); + } + } else { + log.info("OperationExecutionTask not found "); + } + + log.info("OperationExecutionTask done.."); + return RepeatStatus.FINISHED; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPostExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPostExecutionTask.java new file mode 100644 index 00000000..3efcfa97 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPostExecutionTask.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.task; + +import com.espark.adarsh.config.BatchConfiguration; +import com.espark.adarsh.operation.construct.PostExecutionTask; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Data +@Component +public class OperationPostExecutionTask implements Tasklet { + + + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + log.info("OperationPostExecutionTask start.."); + LinkedHashMap postExecutionOperationsMap = + BatchConfiguration.getPostExecutionOperations(); + if (postExecutionOperationsMap != null) { + for (Map.Entry entry : postExecutionOperationsMap.entrySet()) { + String taskName = entry.getKey(); + PostExecutionTask postExecutionTask = entry.getValue(); + log.info("execution is starting for task={}", taskName); + postExecutionTask.executePostTask(chunkContext); + log.info("execution is completed for task={}", taskName); + } + } else { + log.info("OperationPostExecutionTask not found "); + } + + log.info("OperationPostExecutionTask done.."); + return RepeatStatus.FINISHED; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPreExecutionTask.java b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPreExecutionTask.java new file mode 100644 index 00000000..856d5d04 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/java/com/espark/adarsh/task/OperationPreExecutionTask.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.task; + +import com.espark.adarsh.config.BatchConfiguration; +import com.espark.adarsh.operation.construct.PreExecutionTask; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Slf4j +@Data +@Component +public class OperationPreExecutionTask implements Tasklet { + + + public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { + log.info("OperationPreExecutionTask start.."); + LinkedHashMap preExecutionOperationsMap = + BatchConfiguration.getPreExecutionOperations(); + if (preExecutionOperationsMap != null) { + for (Map.Entry entry : preExecutionOperationsMap.entrySet()) { + String taskName = entry.getKey(); + PreExecutionTask preExecutionTask = entry.getValue(); + log.info("execution is starting for task={}", taskName); + preExecutionTask.executePreTask(chunkContext); + log.info("execution is completed for task={}", taskName); + } + } else { + log.info("OperationPreExecutionTask not found "); + } + + log.info("OperationPreExecutionTask done.."); + return RepeatStatus.FINISHED; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch-example/src/main/resources/application.properties b/APPLICATIONS/springboot-batch-example/src/main/resources/application.properties new file mode 100644 index 00000000..be0e4972 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.batch.job.enabled=false + diff --git a/APPLICATIONS/springboot-batch-example/src/main/resources/application.yml b/APPLICATIONS/springboot-batch-example/src/main/resources/application.yml new file mode 100644 index 00000000..4ad51229 --- /dev/null +++ b/APPLICATIONS/springboot-batch-example/src/main/resources/application.yml @@ -0,0 +1,7 @@ + +espark: + default: + value: + preTask: 'defaultPreExecutionTask' + task: 'defaultExecutionTask' + postTask: 'defaultPostExecutionTask' \ No newline at end of file diff --git a/APPLICATIONS/springboot-batch/.gitignore b/APPLICATIONS/springboot-batch/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-batch/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-batch/document/help.txt b/APPLICATIONS/springboot-batch/document/help.txt new file mode 100644 index 00000000..15e3372f --- /dev/null +++ b/APPLICATIONS/springboot-batch/document/help.txt @@ -0,0 +1,7 @@ +#build +$ mvn clean package + +program args in run configuration in intellj +--command.line.args=dataDisplayJob + + diff --git a/APPLICATIONS/springboot-batch/pom.xml b/APPLICATIONS/springboot-batch/pom.xml new file mode 100644 index 00000000..07b4579a --- /dev/null +++ b/APPLICATIONS/springboot-batch/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-batch + 0.0.1-SNAPSHOT + springboot-batch + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-batch + + + + org.projectlombok + lombok + 1.18.12 + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.batch + spring-batch-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..e6bbe177 --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,96 @@ +package com.espark.adarsh; + +import com.espark.adarsh.util.FilterUpdateUtil; +import io.micrometer.core.instrument.util.StringUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.*; +import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; +import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; +import org.springframework.batch.core.repository.JobRestartException; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@SpringBootApplication +public class ApplicationMain { + + private static final String EQUALS = "="; + private static final String SPLIT_PATTERN = "||"; + + public static void main(String[] args) { + + ApplicationContext ctx = SpringApplication.run(ApplicationMain.class, args); + String rawCommandLineArgs = getCommandLineArgs(args); + log.info("label=ContentBatchApplication:main - rawCommandLineArgs {}", rawCommandLineArgs); + String jobName = rawCommandLineArgs.contains(SPLIT_PATTERN) ? rawCommandLineArgs.substring(0, + rawCommandLineArgs.indexOf(SPLIT_PATTERN)) : rawCommandLineArgs; + + String params = rawCommandLineArgs.contains(SPLIT_PATTERN) + ? rawCommandLineArgs.substring(rawCommandLineArgs.indexOf(SPLIT_PATTERN) + 2) : ""; + JobLauncher jobLauncher = ctx.getBean("jobLauncher", JobLauncher.class); + Job job = ctx.getBean(jobName, Job.class); + + // Job parameters + Map parameters = new HashMap<>(); + JobParameters jobParameters; + + if (StringUtils.isNotBlank(params)) { + jobParameters = new JobParameters(FilterUpdateUtil.getJobParameters(params)); + } else { + jobParameters = new JobParameters(parameters); + } + + JobExecution jobExecution = null; + try { + jobExecution = jobLauncher.run(job, jobParameters); + BatchStatus batchStatus = jobExecution.getStatus(); + + while (batchStatus.isRunning()) { + log.info(" Job is still running {} ", jobExecution.getJobId()); + Thread.sleep(100); + } + JobInstance jobInstance = jobExecution.getJobInstance(); + log.info(String.format("********* Name of the job %s", jobInstance.getJobName())); + + log.info(String.format("*********** job instance Id: %d", jobInstance.getId())); + } catch (JobExecutionAlreadyRunningException jobExeAlreadyRunningExp) { + log.error("******** JobExecutionAlreadyRunningException : " + + jobExeAlreadyRunningExp.getMessage()); + } catch (JobRestartException jobRestartExp) { + log.error("******** JobRestartException : " + jobRestartExp.getMessage()); + } catch (JobInstanceAlreadyCompleteException jonInsAlreadyComExp) { + log.error("******** JobInstanceAlreadyCompleteException : " + + jonInsAlreadyComExp.getMessage()); + } catch (JobParametersInvalidException jobParamsInvalidExp) { + log.error("******** JobParametersInvalidException : " + + jobParamsInvalidExp.getMessage()); + } catch (InterruptedException inturruptedExp) { + log.error("******** InterruptedException : " + inturruptedExp.getMessage()); + Thread.currentThread().interrupt(); + } finally { + System.exit(0); + } + log.info(String.format("*********** JOB Exit status: %s", jobExecution.getExitStatus().getExitCode())); + JobInstance jobInstance = jobExecution.getJobInstance(); + log.info(String.format("********* Name of the job %s", jobInstance.getJobName())); + + log.info(String.format("*********** job instance Id: %d", jobInstance.getId())); + System.exit(0); + } + + private static String getCommandLineArgs(String[] args) { + return Arrays.asList(args) + .stream() + .filter(str -> str.startsWith("--command.line.args")) + .map(str -> str.substring(str.indexOf(EQUALS) + 1)) + .collect(Collectors.joining()); + } + +} diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/confi/DataDisplayTaskletConfig.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/confi/DataDisplayTaskletConfig.java new file mode 100644 index 00000000..c2438a31 --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/confi/DataDisplayTaskletConfig.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.confi; + +import com.espark.adarsh.listner.CommonBatchJobListener; +import com.espark.adarsh.task.DataTasklet; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Slf4j +@Configuration +@EnableBatchProcessing +public class DataDisplayTaskletConfig { + + + @Autowired + private JobBuilderFactory jobs; + + @Autowired + private StepBuilderFactory steps; + + @Autowired + DataTasklet dataTasklet; + + @Bean + public Step initDataDisplayStep() { + return steps.get("initDataDisplayStep") + .tasklet(dataTasklet) + .build(); + } + + @Bean(name = "dataDisplayJob") + public Job dataDisplayJob() { + return jobs.get("dataDisplayJob") + .start(initDataDisplayStep()) + .listener(new CommonBatchJobListener()) + .preventRestart() + .build(); + } + +} diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/listner/CommonBatchJobListener.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/listner/CommonBatchJobListener.java new file mode 100644 index 00000000..ad6a7479 --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/listner/CommonBatchJobListener.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.listner; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.JobExecutionListener; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Slf4j +public class CommonBatchJobListener implements JobExecutionListener { + + @Override + public void beforeJob(JobExecution jobExecution) { + log.info(" Starting job = {} ", jobExecution.getJobInstance().getJobName()); + } + + @Override + public void afterJob(JobExecution jobExecution) { + + log.info(" Job = {} finished with status = {} ", jobExecution.getJobInstance().getJobName(), + jobExecution.getStatus()); + } +} + diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/service/DataDisplayService.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/service/DataDisplayService.java new file mode 100644 index 00000000..d3acaa4f --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/service/DataDisplayService.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class DataDisplayService { + + public void showData() { + log.info("data is safe in the db"); + } +} diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/task/DataTasklet.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/task/DataTasklet.java new file mode 100644 index 00000000..fa6bd75a --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/task/DataTasklet.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.task; + +import com.espark.adarsh.service.DataDisplayService; +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class DataTasklet implements Tasklet { + + @Autowired + DataDisplayService dataDisplayService; + + @Override + public RepeatStatus execute(StepContribution contribution, + ChunkContext chunkContext) + throws Exception { + this.dataDisplayService.showData(); + return RepeatStatus.FINISHED; + } + +} diff --git a/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/util/FilterUpdateUtil.java b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/util/FilterUpdateUtil.java new file mode 100644 index 00000000..cbeb1004 --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/java/com/espark/adarsh/util/FilterUpdateUtil.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.util; + + + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.batch.core.JobParameter; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class FilterUpdateUtil { + + private static final String SEPARATOR_PATTERN = "\\|\\|"; + public static final String TASK = "task"; + public static final String TASK_NAME_UPDATE = "nameUpdate"; + public static final String TASK_VALUE_UPDATE = "valueUpdate"; + + public static Map getJobParameters(String params) { + List commandParams = Arrays.asList(params.split(SEPARATOR_PATTERN)); + String taskName = commandParams.get(0); + log.info("commandParams size {} | values {}", commandParams.size(), commandParams); + + if ((TASK_NAME_UPDATE.equalsIgnoreCase(taskName) && commandParams.size() != 3) + || (TASK_VALUE_UPDATE.equalsIgnoreCase(taskName) && commandParams.size() != 4)) { + throw new RuntimeException("Invalid Number of Arguments"); + } + + Map parameters = new LinkedHashMap<>(); + parameters.put(TASK, new JobParameter(taskName)); + return parameters; + } +} diff --git a/APPLICATIONS/springboot-batch/src/main/resources/application.properties b/APPLICATIONS/springboot-batch/src/main/resources/application.properties new file mode 100644 index 00000000..cbb42d2a --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.profiles.active=dev diff --git a/APPLICATIONS/springboot-batch/src/test/java/com/espark/adarsh/SpringbootBatchApplicationTests.java b/APPLICATIONS/springboot-batch/src/test/java/com/espark/adarsh/SpringbootBatchApplicationTests.java new file mode 100644 index 00000000..61571cc8 --- /dev/null +++ b/APPLICATIONS/springboot-batch/src/test/java/com/espark/adarsh/SpringbootBatchApplicationTests.java @@ -0,0 +1,7 @@ +package com.espark.adarsh; + + +class SpringbootBatchApplicationTests { + + +} diff --git a/APPLICATIONS/springboot-bean-lifecycle/.gitignore b/APPLICATIONS/springboot-bean-lifecycle/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-bean-lifecycle/pom.xml b/APPLICATIONS/springboot-bean-lifecycle/pom.xml new file mode 100644 index 00000000..6a18a184 --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-bean-lifecycle + 0.0.1-SNAPSHOT + springboot-bean-lifecycle + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.projectlombok + lombok + 1.18.12 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/bean/LifeCycleBean.java b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/bean/LifeCycleBean.java new file mode 100644 index 00000000..22aa1a25 --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/bean/LifeCycleBean.java @@ -0,0 +1,123 @@ +package com.espark.adarsh.bean; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.*; +import org.springframework.context.weaving.LoadTimeWeaverAware; +import org.springframework.core.io.ResourceLoader; +import org.springframework.instrument.classloading.LoadTimeWeaver; +import org.springframework.jmx.export.notification.NotificationPublisher; +import org.springframework.jmx.export.notification.NotificationPublisherAware; +import org.springframework.lang.Nullable; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@Slf4j +public class LifeCycleBean implements InitializingBean, DisposableBean, + ApplicationContextAware, ApplicationEventPublisherAware, + BeanClassLoaderAware, BeanFactoryAware, + BeanNameAware, LoadTimeWeaverAware, + MessageSourceAware, NotificationPublisherAware, + ResourceLoaderAware , BeanPostProcessor { + + @Value("${espark.adarsh.name}") + String name; + + @Override + public void setBeanName(String arg0) { + // TODO Auto-generated method stub 1 + log.info("BeanNameAware setBeanName()"); + } + + @Override + public void setBeanClassLoader(ClassLoader arg0) { + // TODO Auto-generated method stub 2 + log.info("BeanClassLoaderAware setBeanClassLoader()"); + } + + @Override + public void setBeanFactory(BeanFactory arg0) throws BeansException { + // TODO Auto-generated method stub 3 + log.info("BeanFactoryAware setBeanFactory()"); + } + + @Override + public void setResourceLoader(ResourceLoader arg0) { + // TODO Auto-generated method stub 4 + log.info("ResourceLoaderAware setResourceLoader()"); + } + + @Override + public void setApplicationEventPublisher(ApplicationEventPublisher arg0) { + // TODO Auto-generated method stub 5 + log.info("ApplicationEventPublisherAware setApplicationEventPublisher()"); + } + + @Override + public void setMessageSource(MessageSource arg0) { + // TODO Auto-generated method stub 6 + log.info("MessageSourceAware setMessageSource()"); + } + + @Override + public void setApplicationContext(ApplicationContext arg0) + throws BeansException { + // TODO Auto-generated method stub 7 + log.info("ApplicationContextAware setApplicationContext()"); + } + + @PostConstruct + public void initMethod() { + //TODO custom init 8 + log.info("custom init()"); + } + + @Override + public void afterPropertiesSet() throws Exception { + //TODO InitializingBean 9 + log.info("InitializingBean afterPropertiesSet()"); + } + + @Nullable + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + // TODO 10 + log.info("BeanPostProcessor postProcessBeforeInitialization()"); + return bean; + } + + @Nullable + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + //TODO 11 + log.info("BeanPostProcessor postProcessAfterInitialization()"); + return bean; + } + + @PreDestroy + public void destroyMethod() { + //TODO custom destroy 12 + log.info("custom destroy()"); + } + + @Override + public void destroy() throws Exception { + //TODO DisposableBean 13 + log.info("DisposableBean destroy()"); + } + + @Override + public void setNotificationPublisher(NotificationPublisher arg0) { + // TODO only execute in jmx flow + log.info("NotificationPublisherAware setNotificationPublisher()"); + } + + @Override + public void setLoadTimeWeaver(LoadTimeWeaver arg0) { + // TODO execute in aop flow + log.info("LoadTimeWeaverAware setLoadTimeWeaver()"); + } +} diff --git a/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..76cec10d --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.bean.LifeCycleBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfig { + + @Bean + public LifeCycleBean createLifeCycleBean(){ + return new LifeCycleBean(); + } +} diff --git a/APPLICATIONS/springboot-bean-lifecycle/src/main/resources/application.properties b/APPLICATIONS/springboot-bean-lifecycle/src/main/resources/application.properties new file mode 100644 index 00000000..48faab82 --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/src/main/resources/application.properties @@ -0,0 +1,6 @@ +espark.adarsh.name=radha-adarsh + +spring.profiles.active=local + +logging.level.root=INFO +logging.level.com.espark.adarsh=INFO \ No newline at end of file diff --git a/APPLICATIONS/springboot-bean-lifecycle/src/test/java/com/espark/adarsh/SpringBeanLifecycleApplicationTests.java b/APPLICATIONS/springboot-bean-lifecycle/src/test/java/com/espark/adarsh/SpringBeanLifecycleApplicationTests.java new file mode 100644 index 00000000..f566f1b8 --- /dev/null +++ b/APPLICATIONS/springboot-bean-lifecycle/src/test/java/com/espark/adarsh/SpringBeanLifecycleApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringBeanLifecycleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-cassandra/pom.xml b/APPLICATIONS/springboot-cassandra/pom.xml new file mode 100644 index 00000000..953d8c59 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + + springboot-cassandra + springboot-cassandra + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + + jar + + + + 1.3.2.RELEASE + 2.1.5 + 2.1.9.2 + 2.1.9.2 + 2.0-0 + 19.0 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.data + spring-data-cassandra + ${org.springframework.data.version} + + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.projectlombok + lombok + 1.18.4 + + + org.springframework + spring-test + ${spring.version} + test + + + org.cassandraunit + cassandra-unit-spring + ${cassandra-unit-spring.version} + test + + + org.cassandraunit + cassandra-unit + + + + + org.cassandraunit + cassandra-unit-shaded + ${cassandra-unit-shaded.version} + test + + + org.hectorclient + hector-core + ${hector-core.version} + + + commons-logging + commons-logging + + + + + com.datastax.cassandra + cassandra-driver-core + ${cassandra-driver-core.version} + true + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/configuration/CassandraConfig.java b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/configuration/CassandraConfig.java new file mode 100644 index 00000000..d7e34282 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/configuration/CassandraConfig.java @@ -0,0 +1,45 @@ +package com.espark.adarsh.configuration; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.cassandra.config.CassandraClusterFactoryBean; +import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration; +import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; +import org.springframework.data.cassandra.mapping.CassandraMappingContext; +import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; + +@Configuration +@PropertySource(value = { "classpath:cassandra.properties" }) +@EnableCassandraRepositories(basePackages = "com.espark.adarsh.repository") +public class CassandraConfig extends AbstractCassandraConfiguration { + private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); + + @Autowired + private Environment environment; + + @Override + protected String getKeyspaceName() { + return environment.getProperty("cassandra.keyspace"); + } + + @Override + @Bean + public CassandraClusterFactoryBean cluster() { + final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); + cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); + cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); + LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "]."); + return cluster; + } + + @Override + @Bean + public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { + return new BasicCassandraMappingContext(); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/entity/Book.java b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/entity/Book.java new file mode 100644 index 00000000..d120f66f --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/entity/Book.java @@ -0,0 +1,67 @@ +package com.espark.adarsh.entity; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import org.springframework.cassandra.core.Ordering; +import org.springframework.cassandra.core.PrimaryKeyType; +import org.springframework.data.cassandra.mapping.Column; +import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; +import org.springframework.data.cassandra.mapping.Table; + +@Table +public class Book { + + @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) + private UUID id; + + @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) + private String title; + + @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) + private String publisher; + + @Column + private Set tags = new HashSet<>(); + + public Book(final UUID id, final String title, final String publisher, final Set tags) { + this.id = id; + this.title = title; + this.publisher = publisher; + this.tags.addAll(tags); + } + + public UUID getId() { + return id; + } + + public String getTitle() { + return title; + } + + public String getPublisher() { + return publisher; + } + + public Set getTags() { + return tags; + } + + public void setId(final UUID id) { + this.id = id; + } + + public void setTitle(final String title) { + this.title = title; + } + + public void setPublisher(final String publisher) { + this.publisher = publisher; + } + + public void setTags(final Set tags) { + this.tags = tags; + } + +} diff --git a/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/repository/BookRepository.java b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/repository/BookRepository.java new file mode 100644 index 00000000..5b5db967 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/java/com/espark/adarsh/repository/BookRepository.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Book; +import org.springframework.data.cassandra.repository.CassandraRepository; +import org.springframework.data.cassandra.repository.Query; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends CassandraRepository { + + @Query("select * from book where title = ?0 and publisher=?1") + Iterable findByTitleAndPublisher(String title, String publisher); + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/main/resources/application.properties b/APPLICATIONS/springboot-cassandra/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-cassandra/src/main/resources/cassandra.properties b/APPLICATIONS/springboot-cassandra/src/main/resources/cassandra.properties new file mode 100644 index 00000000..1550cdea --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/resources/cassandra.properties @@ -0,0 +1,3 @@ +cassandra.contactpoints=127.0.0.1 +cassandra.port=9142 +cassandra.keyspace=testKeySpace \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/main/resources/logback.xml b/APPLICATIONS/springboot-cassandra/src/main/resources/logback.xml new file mode 100644 index 00000000..ec0dc246 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/BookRepositoryIntegrationTest.java b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/BookRepositoryIntegrationTest.java new file mode 100644 index 00000000..fa7a854e --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/BookRepositoryIntegrationTest.java @@ -0,0 +1,123 @@ +package com.epsark.adarsh; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.IOException; +import java.util.HashMap; + +import com.espark.adarsh.configuration.CassandraConfig; +import com.espark.adarsh.entity.Book; +import com.espark.adarsh.repository.BookRepository; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class BookRepositoryIntegrationTest { + + private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private BookRepository bookRepository; + + @Autowired + private CassandraAdminOperations adminTemplate; + + // + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + LOGGER.info("KeySpace created and activated."); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(javaBook); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + assertEquals(javaBook.getId(), books.iterator().next().getId()); + } + + @Test + public void whenUpdatingBooks_thenAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(javaBook); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + javaBook.setTitle("Head First Java Second Edition"); + bookRepository.save(javaBook); + final Iterable updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); + assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); + } + + @Test(expected = java.util.NoSuchElementException.class) + public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(javaBook); + bookRepository.delete(javaBook); + final Iterable books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); + assertNotEquals(javaBook.getId(), books.iterator().next().getId()); + } + + @Test + public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + bookRepository.save(javaBook); + bookRepository.save(dPatternBook); + final Iterable books = bookRepository.findAll(); + int bookCount = 0; + for (final Book book : books) { + bookCount++; + } + assertEquals(bookCount, 2); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } + +} diff --git a/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CassandraTemplateIntegrationTest.java b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CassandraTemplateIntegrationTest.java new file mode 100644 index 00000000..06fad972 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CassandraTemplateIntegrationTest.java @@ -0,0 +1,154 @@ +package com.epsark.adarsh; + +import static junit.framework.TestCase.assertNull; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.espark.adarsh.configuration.CassandraConfig; +import com.espark.adarsh.entity.Book; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.data.cassandra.core.CassandraOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class CassandraTemplateIntegrationTest { + private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @Autowired + private CassandraOperations cassandraTemplate; + + // + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + LOGGER.info("KeySpace created and activated."); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + final Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(javaBook.getId(), retrievedBook.getId()); + } + + @Test + public void whenSavingBooks_thenAllAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final List bookList = new ArrayList<>(); + bookList.add(javaBook); + bookList.add(dPatternBook); + cassandraTemplate.insert(bookList); + + final Select select = QueryBuilder.select().from("book").limit(10); + final List retrievedBooks = cassandraTemplate.select(select, Book.class); + assertThat(retrievedBooks.size(), is(2)); + assertEquals(javaBook.getId(), retrievedBooks.get(0).getId()); + assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId()); + } + + @Test + public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + retrievedBook.setTags(ImmutableSet.of("Java", "Programming")); + cassandraTemplate.update(retrievedBook); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags()); + } + + @Test + public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + cassandraTemplate.delete(javaBook); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + assertNull(retrievedUpdatedBook); + } + + @Test + public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + cassandraTemplate.insert(dPatternBook); + cassandraTemplate.deleteAll(Book.class); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); + assertNull(retrievedUpdatedBook); + } + + @Test + public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() { + final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); + cassandraTemplate.insert(javaBook); + cassandraTemplate.insert(dPatternBook); + final long bookCount = cassandraTemplate.count(Book.class); + assertEquals(2, bookCount); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CqlQueriesIntegrationTest.java b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CqlQueriesIntegrationTest.java new file mode 100644 index 00000000..d4d17732 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/CqlQueriesIntegrationTest.java @@ -0,0 +1,124 @@ +package com.epsark.adarsh; + +import static junit.framework.TestCase.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import com.espark.adarsh.configuration.CassandraConfig; +import com.espark.adarsh.entity.Book; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.data.cassandra.core.CassandraOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.querybuilder.Insert; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.datastax.driver.core.utils.UUIDs; +import com.google.common.collect.ImmutableSet; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class CqlQueriesIntegrationTest { + private static final Log LOGGER = LogFactory.getLog(CqlQueriesIntegrationTest.class); + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @Autowired + private CassandraOperations cassandraTemplate; + + // + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + LOGGER.info("Server Started at 127.0.0.1:9142... "); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + LOGGER.info("KeySpace created and activated."); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() { + final UUID uuid = UUIDs.timeBased(); + final Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); + cassandraTemplate.execute(insert); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() { + final UUID uuid = UUIDs.timeBased(); + final String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; + cassandraTemplate.execute(insertCql); + final Select select = QueryBuilder.select().from("book").limit(10); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @Test + public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException { + final UUID uuid = UUIDs.timeBased(); + final String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; + final List singleBookArgsList = new ArrayList<>(); + final List> bookList = new ArrayList<>(); + singleBookArgsList.add(uuid); + singleBookArgsList.add("Head First Java"); + singleBookArgsList.add("OReilly Media"); + singleBookArgsList.add(ImmutableSet.of("Software")); + bookList.add(singleBookArgsList); + cassandraTemplate.ingest(insertPreparedCql, bookList); + // This may not be required, just added to avoid any transient issues + Thread.sleep(5000); + final Select select = QueryBuilder.select().from("book"); + final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); + assertEquals(uuid, retrievedBook.getId()); + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/SpringContextIntegrationTest.java b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/SpringContextIntegrationTest.java new file mode 100644 index 00000000..86f03673 --- /dev/null +++ b/APPLICATIONS/springboot-cassandra/src/test/java/com/epsark/adarsh/SpringContextIntegrationTest.java @@ -0,0 +1,67 @@ +package com.epsark.adarsh; + +import java.io.IOException; +import java.util.HashMap; + +import com.espark.adarsh.configuration.CassandraConfig; +import com.espark.adarsh.entity.Book; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextIntegrationTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/.gitignore b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/README.md b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/README.md new file mode 100644 index 00000000..87191649 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/README.md @@ -0,0 +1,10 @@ +# SPRING BOOT CLOUD CONTRACT API CLIENT + +--- + +### To Build the application +* $ mvn clean package + +### To Run the Application +* $ mvn spring-boot:run + diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/pom.xml b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/pom.xml new file mode 100644 index 00000000..dd1bdc06 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.1 + + + com.espark.adarsh + springboot-cloud-contract-api-client + 0.0.1-SNAPSHOT + springboot-cloud-contract-api-client + Demo project for Spring Boot + + 11 + 2021.0.0 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-starter-contract-stub-runner + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java new file mode 100644 index 00000000..496f3417 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(SpringbootApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..d1a11737 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.bean; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Employee { + + Long id; + String name; +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..b7b88caa --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.service.EmployeeApiServiceClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class ApplicationConfig { + + @Bean + RestTemplate restTemplate() { + return new RestTemplate(); + } + + @Bean + EmployeeApiServiceClient employeeApiServiceClient(RestTemplate restTemplate) { + return new EmployeeApiServiceClient(restTemplate); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/service/EmployeeApiServiceClient.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/service/EmployeeApiServiceClient.java new file mode 100644 index 00000000..03f394fa --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/java/com/espark/adarsh/service/EmployeeApiServiceClient.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.util.Collection; + +public class EmployeeApiServiceClient { + + RestTemplate restTemplate; + + public EmployeeApiServiceClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + public Collection getAllEmployees() throws Exception { + ParameterizedTypeReference> parameterizedTypeReference = new ParameterizedTypeReference>() { + }; + ResponseEntity> responseEntity = this.restTemplate.exchange("http://localhost:8081/employees", HttpMethod.GET, null, parameterizedTypeReference); + return responseEntity.getBody(); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/resources/application.properties b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiClientTest.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiClientTest.java new file mode 100644 index 00000000..5be87c3b --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiClientTest.java @@ -0,0 +1,52 @@ +package com.espark.adarsh; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.service.EmployeeApiServiceClient; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpHeaders; +import org.assertj.core.api.BDDAssertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.AutoConfigureJson; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import java.util.Arrays; +import java.util.Collection; + +@Slf4j +@AutoConfigureJson +@AutoConfigureWireMock(port = 8081) +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = SpringbootApplicationMain.class) +public class EmployeeApiClientTest { + + @Autowired + ObjectMapper objectMapper; + + String jsonData; + + @Autowired + EmployeeApiServiceClient employeeApiServiceClient; + + @Test + public void shouldReturnAllEmployee() throws Exception { + jsonData = objectMapper.writeValueAsString(Arrays.asList(new Employee(1L, "Adarsh"), new Employee(2l, "Radha"))); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/employees")) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .withBody(jsonData) + ) + ); + Collection employees = this.employeeApiServiceClient.getAllEmployees(); + BDDAssertions.then(employees).size().isEqualTo(2); + BDDAssertions.then(employees.iterator().next().getId()).isEqualTo(1L); + BDDAssertions.then(employees.iterator().next().getName()).isEqualTo("Adarsh"); + + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiContractClientTest.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiContractClientTest.java new file mode 100644 index 00000000..a323f41b --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/EmployeeApiContractClientTest.java @@ -0,0 +1,39 @@ +package com.espark.adarsh; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.service.EmployeeApiServiceClient; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpHeaders; +import org.assertj.core.api.BDDAssertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.AutoConfigureJson; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.Arrays; +import java.util.Collection; + +@Slf4j +@AutoConfigureStubRunner(ids="com.espark.arash:springboot-cloud-contract-api:+:8081") +@SpringBootTest(classes = SpringbootApplicationMain.class) +public class EmployeeApiContractClientTest { + + @Autowired + EmployeeApiServiceClient employeeApiServiceClient; + + @Test + public void shouldReturnAllEmployee() throws Exception { + + Collection employees = this.employeeApiServiceClient.getAllEmployees(); + BDDAssertions.then(employees).size().isEqualTo(2); + BDDAssertions.then(employees.iterator().next().getId()).isEqualTo(1L); + BDDAssertions.then(employees.iterator().next().getName()).isEqualTo("Adarsh"); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java new file mode 100644 index 00000000..aa634845 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api-client/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/.gitignore b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/README.md b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/README.md new file mode 100644 index 00000000..c333c4d9 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/README.md @@ -0,0 +1,12 @@ +# SPRING BOOT CLOUD CONTRACT + +--- + +### To build the code +* $ mvn clean package + +### To run the application +* $ mvn spring-boot:run + +### Generated Contract Test Class +* $ cat target/generated-test-sources/contracts/com/espark/adarsh/ContractVerifierTest.java \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/pom.xml b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/pom.xml new file mode 100644 index 00000000..3e12ea37 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/pom.xml @@ -0,0 +1,92 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.1 + + + com.espark.adarsh + springboot-cloud-contract-api + 0.0.1-SNAPSHOT + springboot-cloud-contract-api + Demo project for Spring Boot + + 11 + 2021.0.0 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-starter-contract-verifier + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.cloud + spring-cloud-contract-maven-plugin + 3.1.0 + true + + JUNIT5 + + com.espark.adarsh.EmployeeContractBaseTest + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/EmployeeController.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/EmployeeController.java new file mode 100644 index 00000000..57f449e4 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/EmployeeController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collection; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public Collection getAllEmployee() { + return this.employeeService.getAllEmployees(); + } + +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java new file mode 100644 index 00000000..496f3417 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/SpringbootApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(SpringbootApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..2cdbf89e --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Generated; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Employee { + + @Id + Long id; + String name; +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..3a81cf5e --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,7 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface EmployeeRepository extends JpaRepository { +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..0cef5ffc --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +@Slf4j +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public Collection getAllEmployees() { + return this.employeeRepository.findAll(); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/resources/application.properties b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeContractBaseTest.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeContractBaseTest.java new file mode 100644 index 00000000..3391b496 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeContractBaseTest.java @@ -0,0 +1,33 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.Arrays; + +@SpringBootTest(classes = SpringbootApplicationMain.class) +@ExtendWith(SpringExtension.class) +public class EmployeeContractBaseTest { + + @Autowired + EmployeeController employeeController; + + @MockBean + EmployeeRepository employeeRepository; + + @BeforeEach + public void init(){ + Mockito.when(this.employeeRepository.findAll()) + .thenReturn(Arrays.asList(new Employee(1L, "Adarsh") + , new Employee(2L, "Radha"))); + RestAssuredMockMvc.standaloneSetup(this.employeeController); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeControllerTest.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeControllerTest.java new file mode 100644 index 00000000..8bb0663b --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/EmployeeControllerTest.java @@ -0,0 +1,46 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.Arrays; + +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +public class EmployeeControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + EmployeeRepository employeeRepository; + + @Test + public void shouldReturnAllEmployees() throws Exception { + + Mockito.when(this.employeeRepository.findAll()) + .thenReturn(Arrays.asList(new Employee(1L, "Adarsh") + , new Employee(2L, "Radha"))); + + this.mockMvc.perform(MockMvcRequestBuilders.get("/employees")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("@.[0].id").value(1L)) + .andExpect(MockMvcResultMatchers.jsonPath("@.[0].name").value("Adarsh")) + .andExpect(MockMvcResultMatchers.jsonPath("@.[1].id").value(2L)) + .andExpect(MockMvcResultMatchers.jsonPath("@.[1].name").value("Radha")) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + } +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java new file mode 100644 index 00000000..aa634845 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/java/com/espark/adarsh/SpringbootApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/resources/contracts/shouldReturnAllEmployees.groovy b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/resources/contracts/shouldReturnAllEmployees.groovy new file mode 100644 index 00000000..d2dc45c8 --- /dev/null +++ b/APPLICATIONS/springboot-cloud-contract/springboot-cloud-contract-api/src/test/resources/contracts/shouldReturnAllEmployees.groovy @@ -0,0 +1,20 @@ +import org.springframework.cloud.contract.spec.Contract +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType + +Contract.make { + + description(" should return all customers ") + + request { + url "/employees" + method GET() + } + response { + status 200 + headers { + header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + } + body([[id: 1L, name: "Adarsh"], [id: 2L, name: "Radha"]]) + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/.gitignore b/APPLICATIONS/springboot-cloudconfig-example/.gitignore new file mode 100644 index 00000000..059c521b --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/.gitignore @@ -0,0 +1,4 @@ +target/ + +/\.idea/ +*\.iml diff --git a/APPLICATIONS/springboot-cloudconfig-example/README.md b/APPLICATIONS/springboot-cloudconfig-example/README.md new file mode 100644 index 00000000..02cc1ac5 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/README.md @@ -0,0 +1,44 @@ +[![Build Status](https://travis-ci.org/ericdahl/spring-cloud-config-example.svg)](https://travis-ci.org/ericdahl/spring-cloud-config-example) + +# spring-cloud-config-example +basic example of using spring-cloud-config to retrieve configs from a git-backed server + +## Quick Start + +### Build code + +```bash +git clone git@github.com:ericdahl/spring-cloud-config-example.git +cd spring-cloud-config-example +mvn clean package +``` + +### Start Config Server + +```bash +java -jar server/target/*jar +``` + +Load [http://localhost:8888/master/development](http://localhost:8888/master/development). +This displays the config properties which are being retrieved from the git repo defined +in bootstrap.yml. This currently is the [`config` directory in this repository](https://github.com/ericdahl/spring-cloud-config-example/tree/master/config). + +### Start Client App +```bash +java -jar client/target/*jar +``` + +Load [http://localhost:8080](http://localhost:8080) to see the property from the server. +Alternatively, you can inspect the properties and their sources from the spring-boot-actuator +endpoint at [http://localhost:8080/env](http://localhost:8080/env) + +### Reload configuration from server (at runtime) + +Spring Cloud Config has a `@RefreshScope` mechanism to allow beans to be reinitialized +on demand to fetch updated configuration values. The AppController on the client +has this annotation, so it will display the new config value once the refresh +endpoint is called. + +```bash +curl -X POST 'http://localhost:8080/refresh' +``` diff --git a/APPLICATIONS/springboot-cloudconfig-example/espark-server-config/application.yml b/APPLICATIONS/springboot-cloudconfig-example/espark-server-config/application.yml new file mode 100644 index 00000000..19bd615b --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/espark-server-config/application.yml @@ -0,0 +1,9 @@ +# Config data exposed by config server + +info: + foo: bar + someList: [2, 3, 7] + +espark: + adarsh: + names: adarsh,radha,amit,sonu,monu \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/pom.xml b/APPLICATIONS/springboot-cloudconfig-example/pom.xml new file mode 100644 index 00000000..b779adbb --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-cloudconfig-example + pom + 1.0-SNAPSHOT + + + springboot-cloudconfig-server + springboot-cloudconfig-client + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/pom.xml b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/pom.xml new file mode 100644 index 00000000..d6b19c8c --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/pom.xml @@ -0,0 +1,61 @@ + + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.2.6.RELEASE + + + + com.espark.adarsh + springboot-cloudconfig-client + 1.0-SNAPSHOT + + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-config-client + 1.0.1.RELEASE + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/AppController.java b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/AppController.java new file mode 100644 index 00000000..d22eee1b --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/AppController.java @@ -0,0 +1,24 @@ +package example; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +// This will allow us to reinitialize this controller to get any new config +// values when the /refresh endpoint is POSTed to. +@RefreshScope +public class AppController { + + @Value("${info.foo}") + private String fooProperty; + + @Value("${espark.adarsh.name}") + private String[] names; + + @RequestMapping("/") + public String hello() { + return "Using [" + fooProperty + "] from config server"; + } +} diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/Application.java b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/Application.java new file mode 100644 index 00000000..00a8b270 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/java/example/Application.java @@ -0,0 +1,31 @@ +package example; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); + + public static void main(String args[]) { + SpringApplication.run(Application.class, args); + } + + /** + * Output property from cloud-config-server on startup of app, + * + * also can be seen at: + * http://localhost:8080/env/info.foo + */ + @Bean + public CommandLineRunner printProperties(@Value("${info.foo}") final String fooProperty) { + return args -> LOGGER.info("info.foo is: [{}]", fooProperty); + } + +} diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/resources/bootstrap.yml b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..054d526b --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/main/resources/bootstrap.yml @@ -0,0 +1,8 @@ +spring: + application: + name: config-client-test + cloud: + config: + env: default # optional + label: master # optional + uri: http://localhost:8888 # optional \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/test/java/example/ConfigTestManual.java b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/test/java/example/ConfigTestManual.java new file mode 100644 index 00000000..4ba72335 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-client/src/test/java/example/ConfigTestManual.java @@ -0,0 +1,32 @@ +package example; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * This test can be used to ensure that the client is pulling down + * the configuration property from the server. It requires that the + * server be running, so it's not included as part of the normal + * test suite. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebAppConfiguration +public class ConfigTestManual { + + @Value("${info.foo}") + private String fooProperty; + + + @Test + public void shouldLoadConfig() { + assertThat(fooProperty, is("bar")); + } +} diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/pom.xml b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/pom.xml new file mode 100644 index 00000000..2215fbe4 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/pom.xml @@ -0,0 +1,47 @@ + + + + 4.0.0 + + + org.springframework.cloud + spring-cloud-starter-parent + 1.0.2.RELEASE + + + + com.espark.adarsh + springboot-cloudconfig-server + 1.0-SNAPSHOT + + + + 1.8 + + + + + org.springframework.cloud + spring-cloud-config-server + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/java/example/Application.java b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/java/example/Application.java new file mode 100644 index 00000000..223949ab --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/java/example/Application.java @@ -0,0 +1,13 @@ +package example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; + +@SpringBootApplication +@EnableConfigServer +public class Application { + public static void main(String args[]) { + SpringApplication.run(Application.class, args); + } +} diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/application.yml b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/application.yml new file mode 100644 index 00000000..a900e0d2 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/application.yml @@ -0,0 +1,5 @@ +server: + port: 8888 + +# show full health details at /health +endpoints.health.sensitive: false \ No newline at end of file diff --git a/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/bootstrap.yml b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..34aee1d3 --- /dev/null +++ b/APPLICATIONS/springboot-cloudconfig-example/springboot-cloudconfig-server/src/main/resources/bootstrap.yml @@ -0,0 +1,15 @@ +spring: + application: + name: config-server + cloud: + config: + server: + git: +# uri: file://${HOME}/config-repo + uri: https://github.com/adarshkumarsingh83/spring-cloudconfig + + # Search in the 'config' directory of the repo. This generally wouldn't + # be used because the configs would be in the root directory, but because + # this example repo is hosting both the code and the configs, we're + # isolating the configuration files into their own directory. + searchPaths: espark-server-config \ No newline at end of file diff --git a/APPLICATIONS/springboot-conditions/.gitignore b/APPLICATIONS/springboot-conditions/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..9cc84ea9 Binary files /dev/null and b/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..6c8c0e08 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/APPLICATIONS/springboot-conditions/pom.xml b/APPLICATIONS/springboot-conditions/pom.xml new file mode 100644 index 00000000..df37f104 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-conditions + 0.0.1-SNAPSHOT + jar + + springboot-conditions + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/ApplicationMain.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/ApplicationMain.java new file mode 100644 index 00000000..904ced47 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.condition; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnBeanConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnBeanConfig.java new file mode 100644 index 00000000..6ec5da58 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnBeanConfig.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.condition.bean; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; +import com.espark.adarsh.condition.model.PrintService; +import com.espark.adarsh.condition.model.BlackAndWhitePrinterService; +import com.espark.adarsh.condition.model.ColorPrinterService; + + +@org.springframework.context.annotation.Configuration +public class ConditionalOnBeanConfig { + + @org.springframework.context.annotation.Bean + public ServiceOne serviceOne(){ + // will initialize as normal + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnBean(name="serviceOne") + public ServiceTwo serviceTwo(){ + // it will initialize as serviceOne is present in the beanFactory. + return new ServiceTwo(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnBean + public ServiceThree serviceThree(){ + // will not get initialized as there is no bean with return type serviceThree in BeanFactory. + return new ServiceThree(); + } + + @org.springframework.context.annotation.Bean + public PrintService blackAndWhitePrinterService(){ + return new BlackAndWhitePrinterService(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnBean + public PrintService colorPrinterService(){ + return new ColorPrinterService(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnMissingBeanConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnMissingBeanConfig.java new file mode 100644 index 00000000..18a9e030 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/bean/ConditionalOnMissingBeanConfig.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.condition.bean; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; + +@org.springframework.context.annotation.Configuration +public class ConditionalOnMissingBeanConfig { + + @org.springframework.context.annotation.Bean + public ServiceOne serviceOne(){ + return new ServiceOne(); // will initialize as normal + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean(name="serviceOne") + public ServiceTwo serviceTwo(){ + return new ServiceTwo(); // it will not initialize as + // beanA is present in the beanFactory. + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean(name="serviceFour") + public ServiceThree serviceThree(){ + return new ServiceThree(); // will get initialized as there is no + // bean with name beanD in BeanFactory. + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnClassConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnClassConfig.java new file mode 100644 index 00000000..daf0a691 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnClassConfig.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.condition.classs; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; + +@org.springframework.context.annotation.Configuration +public class ConditionOnClassConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnClass(value={java.util.HashMap.class}) + public ServiceOne serviceOne(){ + // will get created as HashMap class is on the classpath + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnClass(name="com.espark.adarsh.condition.model.ServiceFour") + public ServiceTwo serviceTwo(){ + // won't be created as ServiceFour class is not on classpath + return new ServiceTwo(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnClass(value=com.espark.adarsh.condition.model.PrintService.class) + public ServiceThree serviceThree(){ + // PrintService is on the classpath in the project. + //So, ServiceThree's instance will be created. + return new ServiceThree(); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnMissingClassConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnMissingClassConfig.java new file mode 100644 index 00000000..5690414d --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/classs/ConditionOnMissingClassConfig.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.condition.classs; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +@org.springframework.context.annotation.Configuration +public class ConditionOnMissingClassConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass(value={"com.espark.adarsh.condition.model.ServiceFour"}) + public ServiceOne serviceOne(){ + // will get created as ServiceFour class is missing + // from classpath. + return new ServiceOne(); + + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass(value={"com.espark.adarsh.condition.model.ServiceThree"}) + public ServiceTwo serviceTwo(){ + // won't be created as ServiceThree is present in classpath. + return new ServiceTwo(); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/java/ConditionalBeanJavaConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/java/ConditionalBeanJavaConfig.java new file mode 100644 index 00000000..c00344fb --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/java/ConditionalBeanJavaConfig.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.condition.java; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import org.springframework.boot.system.JavaVersion; + +@org.springframework.context.annotation.Configuration +public class ConditionalBeanJavaConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnJava(value=JavaVersion.EIGHT) + public ServiceOne serviceOne(){ + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnJava(value= JavaVersion.NINE + ,range= org.springframework.boot.autoconfigure.condition.ConditionalOnJava.Range.EQUAL_OR_NEWER) + public ServiceTwo serviceTwo(){ + return new ServiceTwo(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/BlackAndWhitePrinterService.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/BlackAndWhitePrinterService.java new file mode 100644 index 00000000..dc21ce65 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/BlackAndWhitePrinterService.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.condition.model; + +public class BlackAndWhitePrinterService implements com.espark.adarsh.condition.model.PrintService { + @Override + public void printData(String data) { + System.out.println("BlackAndWhitePrinterService => "+data); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ColorPrinterService.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ColorPrinterService.java new file mode 100644 index 00000000..9b54e481 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ColorPrinterService.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.condition.model; + +public class ColorPrinterService implements PrintService{ + + @Override + public void printData(String data) { + System.out.println("ColorPrinterService => "+data); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/PrintService.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/PrintService.java new file mode 100644 index 00000000..45898200 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/PrintService.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.condition.model; + +public interface PrintService { + + public void printData(String data); +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceOne.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceOne.java new file mode 100644 index 00000000..2fe64d77 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceOne.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.condition.model; + +public class ServiceOne { + + public void doWork(){ + System.out.println("ServiceOne => working on "); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceThree.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceThree.java new file mode 100644 index 00000000..73d97ddd --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceThree.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.condition.model; + +public class ServiceThree { + + public void doWork(){ + System.out.println("ServiceThree => working on "); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceTwo.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceTwo.java new file mode 100644 index 00000000..12f07d72 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/model/ServiceTwo.java @@ -0,0 +1,8 @@ +package com.espark.adarsh.condition.model; + +public class ServiceTwo { + + public void doWork(){ + System.out.println("ServiceTwo => working on "); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/property/ConditionalBeanPropertyConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/property/ConditionalBeanPropertyConfig.java new file mode 100644 index 00000000..421cde62 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/property/ConditionalBeanPropertyConfig.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.condition.property; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; + +@org.springframework.context.annotation.Configuration +public class ConditionalBeanPropertyConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name="service.property" + , havingValue="ServiceOne") + public ServiceOne serviceOne(){ + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name="service.property" + , havingValue="ServiceTwo") + public ServiceTwo serviceTwo(){ + return new ServiceTwo(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name="service.property" + , havingValue="ServiceThree" + ,matchIfMissing=true) + public ServiceThree serviceThree(){ + return new ServiceThree(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/resource/ConditionalOnResourceConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/resource/ConditionalOnResourceConfig.java new file mode 100644 index 00000000..0a4c723d --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/resource/ConditionalOnResourceConfig.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.condition.resource; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +@org.springframework.context.annotation.Configuration +public class ConditionalOnResourceConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnResource(resources={"classpath:application.properties"}) + public ServiceOne serviceOne(){ + // will initiate as application.properties is in classpath. + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnResource(resources={"file:/usr/data.txt"}) + public ServiceTwo serviceTwo(){ + // will not initialize as the file is not + // present in the given location. + return new ServiceTwo(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanNotWebConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanNotWebConfig.java new file mode 100644 index 00000000..f7e42de9 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanNotWebConfig.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.condition.web; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +@org.springframework.context.annotation.Configuration +public class ConditionalBeanNotWebConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication + public ServiceOne serviceOne(){ + // will initiate if the context is + // WebApplicationContext. + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication + public ServiceTwo serviceTwo(){ + // will initiate if the context is not + // WebApplicationContext. + return new ServiceTwo(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanWebConfig.java b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanWebConfig.java new file mode 100644 index 00000000..91a8821d --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/java/com/espark/adarsh/condition/web/ConditionalBeanWebConfig.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.condition.web; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +@org.springframework.context.annotation.Configuration +public class ConditionalBeanWebConfig { + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication + public ServiceOne serviceOne(){ + return new ServiceOne(); + } + + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication + public ServiceTwo serviceTwo(){ + return new ServiceTwo(); + } +} diff --git a/APPLICATIONS/springboot-conditions/src/main/resources/application.properties b/APPLICATIONS/springboot-conditions/src/main/resources/application.properties new file mode 100644 index 00000000..1fe82217 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/main/resources/application.properties @@ -0,0 +1 @@ +service.property=ServiceOne \ No newline at end of file diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnBeanConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnBeanConfigTest.java new file mode 100644 index 00000000..a1c31c17 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnBeanConfigTest.java @@ -0,0 +1,42 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; +import com.espark.adarsh.condition.model.PrintService; +import com.espark.adarsh.condition.model.BlackAndWhitePrinterService; +import com.espark.adarsh.condition.model.ColorPrinterService; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes= com.espark.adarsh.condition.bean.ConditionalOnBeanConfig.class) +public class ConditionalOnBeanConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testBean() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo",ServiceTwo.class); + + PrintService blackAndWhitePrinterService = applicationContext.getBean("blackAndWhitePrinterService",BlackAndWhitePrinterService.class); + PrintService colorPrinterService = applicationContext.getBean("colorPrinterService",ColorPrinterService.class); + + assertNotNull(serviceOne); + assertNotNull(serviceTwo); + assertNotNull(blackAndWhitePrinterService); + assertNotNull(colorPrinterService); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testBean1(){ + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + ServiceThree serviceThree = applicationContext.getBean("serviceThree",ServiceThree.class); + + assertNotNull(serviceOne); + assertNotNull(serviceThree); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnMissingBeanConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnMissingBeanConfigTest.java new file mode 100644 index 00000000..c687ac70 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/bean/ConditionalOnMissingBeanConfigTest.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes= com.espark.adarsh.condition.bean.ConditionalOnMissingBeanConfig.class) +public class ConditionalOnMissingBeanConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testBeanA() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testBeanB() { + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo",ServiceTwo.class); + assertNull(serviceTwo); + } + + @org.junit.Test + public void testBeanC() { + ServiceThree serviceThree = applicationContext.getBean("serviceThree",ServiceThree.class); + assertNotNull(serviceThree); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnClassConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnClassConfigTest.java new file mode 100644 index 00000000..f00254cb --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnClassConfigTest.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.classs; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes= com.espark.adarsh.condition.classs.ConditionOnClassConfig.class) +public class ConditionOnClassConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testBeanA() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne", ServiceOne.class); + assertNotNull(serviceOne); + + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testBeanB() { + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo", ServiceTwo.class); + assertNotNull(serviceTwo); + } + + + @org.junit.Test + public void testBeanC() { + ServiceThree serviceThree = applicationContext.getBean("serviceThree", ServiceThree.class); + assertNotNull(serviceThree); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnMissingClassConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnMissingClassConfigTest.java new file mode 100644 index 00000000..d35280c6 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/classs/ConditionOnMissingClassConfigTest.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.classs; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes= com.espark.adarsh.condition.classs.ConditionOnMissingClassConfig.class) +public class ConditionOnMissingClassConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testServiceOne() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceTwo() { + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo",ServiceTwo.class); + assertNotNull(serviceTwo); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/java/ConditionalBeanJavaConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/java/ConditionalBeanJavaConfigTest.java new file mode 100644 index 00000000..ffc5c444 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/java/ConditionalBeanJavaConfigTest.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.java; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes= com.espark.adarsh.condition.java.ConditionalBeanJavaConfig.class) +public class ConditionalBeanJavaConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testBeanA() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testBeanB() { + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo",ServiceTwo.class); + assertNotNull(serviceTwo); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/property/ConditionalBeanPropertyConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/property/ConditionalBeanPropertyConfigTest.java new file mode 100644 index 00000000..aa724fcb --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/property/ConditionalBeanPropertyConfigTest.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.property; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import com.espark.adarsh.condition.model.ServiceThree; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes={com.espark.adarsh.condition.property.ConditionalBeanPropertyConfig.class}) +public class ConditionalBeanPropertyConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testServiceOne() { + ServiceOne serviceOne = applicationContext.getBean(ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceTwo() { + ServiceTwo serviceTwo = applicationContext.getBean(ServiceTwo.class); + assertNotNull(serviceTwo); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceThree() { + ServiceThree serviceThree = applicationContext.getBean(ServiceThree.class); + assertNotNull(serviceThree); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/resource/ConditionalOnResourceConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/resource/ConditionalOnResourceConfigTest.java new file mode 100644 index 00000000..08717338 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/resource/ConditionalOnResourceConfigTest.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.resource; + + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest(classes={com.espark.adarsh.condition.resource.ConditionalOnResourceConfig.class}) +public class ConditionalOnResourceConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + + @org.junit.Test + public void testBeanA() { + ServiceOne serviceOne = applicationContext.getBean("serviceOne",ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testBeanB() { + ServiceTwo serviceTwo = applicationContext.getBean("serviceTwo",ServiceTwo.class); + assertNotNull(serviceTwo); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanNotWebConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanNotWebConfigTest.java new file mode 100644 index 00000000..26b62c45 --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanNotWebConfigTest.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.web; + +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest( + classes={com.espark.adarsh.condition.web.ConditionalBeanNotWebConfig.class} + ,webEnvironment= org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK) +public class ConditionalBeanNotWebConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testServiceOneForWeb() { + com.espark.adarsh.condition.model.ServiceOne serviceOne = applicationContext.getBean(com.espark.adarsh.condition.model.ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceTwoForWeb() { + com.espark.adarsh.condition.model.ServiceTwo serviceTwo = applicationContext.getBean(com.espark.adarsh.condition.model.ServiceTwo.class); + assertNotNull(serviceTwo); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceOneForNotWeb() { + com.espark.adarsh.condition.model.ServiceOne serviceOne = applicationContext.getBean(com.espark.adarsh.condition.model.ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test + public void testServiceTwoForNotWeb() { + com.espark.adarsh.condition.model.ServiceTwo serviceTwo = applicationContext.getBean(com.espark.adarsh.condition.model.ServiceTwo.class); + assertNotNull(serviceTwo); + } + +} diff --git a/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanWebConfigTest.java b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanWebConfigTest.java new file mode 100644 index 00000000..f61969fe --- /dev/null +++ b/APPLICATIONS/springboot-conditions/src/test/java/com/espark/adarsh/web/ConditionalBeanWebConfigTest.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.condition.model.ServiceOne; +import com.espark.adarsh.condition.model.ServiceTwo; +import static org.junit.Assert.assertNotNull; + +@org.junit.runner.RunWith(org.springframework.test.context.junit4.SpringRunner.class) +@org.springframework.boot.test.context.SpringBootTest( + classes={com.espark.adarsh.condition.web.ConditionalBeanWebConfig.class} + ,webEnvironment= org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE) +public class ConditionalBeanWebConfigTest { + + @org.springframework.beans.factory.annotation.Autowired + org.springframework.context.ApplicationContext applicationContext; + + @org.junit.Test + public void testServiceOneForWeb() { + ServiceOne serviceOne = applicationContext.getBean(ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceTwoForWeb() { + ServiceTwo serviceTwo = applicationContext.getBean(ServiceTwo.class); + assertNotNull(serviceTwo); + } + + @org.junit.Test(expected= org.springframework.beans.factory.NoSuchBeanDefinitionException.class) + public void testServiceOneForNotWeb() { + ServiceOne serviceOne = applicationContext.getBean(ServiceOne.class); + assertNotNull(serviceOne); + } + + @org.junit.Test + public void testServiceTwoForNotWeb() { + ServiceTwo serviceTwo = applicationContext.getBean(ServiceTwo.class); + assertNotNull(serviceTwo); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/.gitignore b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/pom.xml b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/pom.xml new file mode 100644 index 00000000..2fae6e8c --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-contract-client-validation + 0.0.1-SNAPSHOT + springboot-contract-client-validation + Demo project for Spring Boot + + + 1.8 + Hoxton.SR3 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.cloud + spring-cloud-starter-contract-stub-runner + test + + + junit + junit + 4.13 + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/ApplicationMain.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/ApplicationMain.java new file mode 100644 index 00000000..1f499fc0 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.producer.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/bean/Employee.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/bean/Employee.java new file mode 100644 index 00000000..88757636 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/bean/Employee.java @@ -0,0 +1,131 @@ +package com.espark.adarsh.producer.consumer.bean; + +public class Employee { + + public Integer id; + + public String fname; + + public String lname; + + public Double salary; + + public String gender; + + public Employee() { + } + + public Employee(Integer id, String fname, String lname) { + super(); + this.id = id; + this.fname = fname; + this.lname = lname; + this.salary = salary; + this.gender = gender; + } + + public Employee(Integer id, String fname, String lname, Double salary, String gender) { + super(); + this.id = id; + this.fname = fname; + this.lname = lname; + this.salary = salary; + this.gender = gender; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Double getSalary() { + return salary; + } + + public void setSalary(Double salary) { + this.salary = salary; + } + + public String getFname() { + return fname; + } + + public void setFname(String fname) { + this.fname = fname; + } + + public String getLname() { + return lname; + } + + public void setLname(String lname) { + this.lname = lname; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", fname=" + fname + ", lname=" + lname + ", salary=" + salary + + ", gender=" + gender + "]"; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fname == null) ? 0 : fname.hashCode()); + result = prime * result + ((gender == null) ? 0 : gender.hashCode()); + result = prime * result + id; + result = prime * result + ((lname == null) ? 0 : lname.hashCode()); + result = prime * result + ((salary == null) ? 0 : salary.hashCode()); + return result; + } + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (fname == null) { + if (other.fname != null) + return false; + } else if (!fname.equals(other.fname)) + return false; + if (gender == null) { + if (other.gender != null) + return false; + } else if (!gender.equals(other.gender)) + return false; + if (id != other.id) + return false; + if (lname == null) { + if (other.lname != null) + return false; + } else if (!lname.equals(other.lname)) + return false; + if (salary == null) { + if (other.salary != null) + return false; + } else if (!salary.equals(other.salary)) + return false; + return true; + } + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/config/ApplicationConfig.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/config/ApplicationConfig.java new file mode 100644 index 00000000..8587f1f8 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/config/ApplicationConfig.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.producer.consumer.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class ApplicationConfig { + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/service/IntegrationService.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/service/IntegrationService.java new file mode 100644 index 00000000..6b9a4ae0 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/java/com/espark/adarsh/producer/consumer/service/IntegrationService.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.producer.consumer.service; + +import com.espark.adarsh.producer.consumer.bean.Employee; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class IntegrationService { + + @Autowired + RestTemplate restTemplate; + + public Employee getEmployee(final int id) { + final ResponseEntity result = restTemplate.exchange("http://localhost:9090/employee/" + id, + HttpMethod.GET, null, Employee.class); + return result.getBody(); + } +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/resources/application.yml b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/resources/application.yml new file mode 100644 index 00000000..344707d2 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + application: + name: consumer-app + +server: + port: 8080 \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ApplicationMainTests.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ApplicationMainTests.java new file mode 100644 index 00000000..2fe9aa5c --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ApplicationMainTests.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.consumer; + +import com.espark.adarsh.producer.consumer.ApplicationMain; +import com.espark.adarsh.producer.consumer.service.IntegrationService; +import org.assertj.core.api.BDDAssertions; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.contract.stubrunner.junit.StubRunnerRule; +import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties; +import org.springframework.test.context.junit4.SpringRunner; + +@SpringBootTest(classes = ApplicationMain.class) +@RunWith(SpringRunner.class) +public class ApplicationMainTests { + + @Rule + public StubRunnerRule stubRunnerRule = new StubRunnerRule() + .downloadStub("com.espark.adarsh", "springboot-contract-client-validation", "0.0.1-SNAPSHOT", "stubs") + .withPort(9090) + .stubsMode(StubRunnerProperties.StubsMode.LOCAL); + + @Autowired + IntegrationService consumerClient; + + @Test + public void clientShouldRetrunPersonForGivenID_checkFirsttName() throws Exception { + + BDDAssertions.then(this.consumerClient.getEmployee(1).getFname()).isEqualTo("Adarsh"); + } + + @Test + public void clientShouldRetrunPersonForGivenID_checkLastName() throws Exception { + + BDDAssertions.then(this.consumerClient.getEmployee(1).getLname()).isEqualTo("Kumar"); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ConsumerTestUnit.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ConsumerTestUnit.java new file mode 100644 index 00000000..cd575771 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-client-validation/src/test/java/com/espark/adarsh/consumer/ConsumerTestUnit.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.consumer; + +import com.espark.adarsh.producer.consumer.ApplicationMain; +import com.espark.adarsh.producer.consumer.bean.Employee; +import com.espark.adarsh.producer.consumer.service.IntegrationService; +import org.apache.http.HttpHeaders; +import org.assertj.core.api.BDDAssertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.json.AutoConfigureJson; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; + +@SpringBootTest(classes = ApplicationMain.class) +@RunWith(SpringRunner.class) +@AutoConfigureWireMock(port = 9090) +@AutoConfigureJson +public class ConsumerTestUnit { + + @Autowired + IntegrationService consumerClient; + + @Autowired + ObjectMapper objectMapper; + + @Test + public void clientShouldRetrunPersonForGivenID() throws Exception { + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/employee/1")).willReturn( + WireMock.aResponse() + .withStatus(200) + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE) + .withBody(jsonForPerson(new Employee(1, "Adarsh", "Kumar"))))); + BDDAssertions.then(this.consumerClient.getEmployee(1).getFname()).isEqualTo("Adarsh"); + } + + private String jsonForPerson(final Employee person) throws Exception { + return objectMapper.writeValueAsString(person); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/.gitignore b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/document/help.txt b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/document/help.txt new file mode 100644 index 00000000..43ab4f50 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/document/help.txt @@ -0,0 +1,2 @@ +# To build the app +$ mvn clean install -DskipTests \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/pom.xml b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/pom.xml new file mode 100644 index 00000000..183c59ac --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-contract-producer-validation + 0.0.1-SNAPSHOT + springboot-contract-producer-validation + Demo project for Spring Boot + + + 1.8 + Hoxton.SR3 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + org.springframework.cloud + spring-cloud-starter-contract-verifier + test + + + junit + junit + 4.13 + test + + + + io.rest-assured + rest-assured + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.cloud + spring-cloud-contract-maven-plugin + 2.2.2.RELEASE + true + + JUNIT5 + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/ApplicationMain.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/ApplicationMain.java new file mode 100644 index 00000000..6966ffdb --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.producer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/bean/Employee.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/bean/Employee.java new file mode 100644 index 00000000..8ccfac58 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/bean/Employee.java @@ -0,0 +1,124 @@ +package com.espark.adarsh.producer.bean; + +public class Employee { + + public Integer id; + + public String fname; + + public String lname; + + public Double salary; + + public String gender; + + public Employee() { + } + + + public Employee(Integer id, String fname, String lname, Double salary, String gender) { + super(); + this.id = id; + this.fname = fname; + this.lname = lname; + this.salary = salary; + this.gender = gender; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Double getSalary() { + return salary; + } + + public void setSalary(Double salary) { + this.salary = salary; + } + + public String getFname() { + return fname; + } + + public void setFname(String fname) { + this.fname = fname; + } + + public String getLname() { + return lname; + } + + public void setLname(String lname) { + this.lname = lname; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", fname=" + fname + ", lname=" + lname + ", salary=" + salary + + ", gender=" + gender + "]"; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fname == null) ? 0 : fname.hashCode()); + result = prime * result + ((gender == null) ? 0 : gender.hashCode()); + result = prime * result + id; + result = prime * result + ((lname == null) ? 0 : lname.hashCode()); + result = prime * result + ((salary == null) ? 0 : salary.hashCode()); + return result; + } + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (fname == null) { + if (other.fname != null) + return false; + } else if (!fname.equals(other.fname)) + return false; + if (gender == null) { + if (other.gender != null) + return false; + } else if (!gender.equals(other.gender)) + return false; + if (id != other.id) + return false; + if (lname == null) { + if (other.lname != null) + return false; + } else if (!lname.equals(other.lname)) + return false; + if (salary == null) { + if (other.salary != null) + return false; + } else if (!salary.equals(other.salary)) + return false; + return true; + } + + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/consumer/bean.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/consumer/bean.java new file mode 100644 index 00000000..91e4a83c --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/consumer/bean.java @@ -0,0 +1,4 @@ +package com.espark.adarsh.producer.consumer; + +public class bean { +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/service/EmployeeService.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/service/EmployeeService.java new file mode 100644 index 00000000..e37d9a6a --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/service/EmployeeService.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.producer.service; + +import com.espark.adarsh.producer.bean.Employee; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + + +@Service +public class EmployeeService { + + private static List empList = new ArrayList<>(); + + static { + empList.add(new Employee(1, "Adarsh","kumar", 1000.0,"M")); + empList.add(new Employee(2, "Radha","Singh", 2000.0,"F")); + } + + public Optional findById(Integer id){ + return empList.stream().filter(emp -> emp.id.equals(id)).findFirst(); + } +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/web/EmployeeController.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/web/EmployeeController.java new file mode 100644 index 00000000..c6314957 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/java/com/espark/adarsh/producer/web/EmployeeController.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.producer.web; + +import java.util.Optional; + +import com.espark.adarsh.producer.bean.Employee; +import com.espark.adarsh.producer.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +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.RestController; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping(value = "employee/{id}") + public ResponseEntity getEmployee(@PathVariable("id") int id) { + Optional employee = employeeService.findById(id); + if (employee.isPresent()) { + return ResponseEntity.status(HttpStatus.OK) + .contentType(MediaType.APPLICATION_JSON) + .body(employee.get()); + } else { + return ResponseEntity + .status(HttpStatus.NOT_FOUND) + .build(); + } + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/resources/application.yml b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/resources/application.yml new file mode 100644 index 00000000..aeaa30a0 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + application: + name: producer + + + +server: + port: 9090 + + + diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/ApplicationMainTests.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/ApplicationMainTests.java new file mode 100644 index 00000000..ada99bf5 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/ApplicationMainTests.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.producer; + +import java.util.Optional; + +import com.espark.adarsh.producer.bean.Employee; +import com.espark.adarsh.producer.ApplicationMain; +import com.espark.adarsh.producer.service.EmployeeService; +import com.espark.adarsh.producer.web.EmployeeController; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.springframework.test.context.web.WebAppConfiguration; + +@WebAppConfiguration +@SpringBootTest(classes = ApplicationMain.class) +@RunWith(SpringRunner.class) +class ApplicationMainTests { + + @Autowired + EmployeeController employeeController; + + + @MockBean + private EmployeeService employeeService; + + @Before + public void before() { + final Employee aEmployee = new Employee(1, "Adarsh", "Kumar", 1000.0, "M"); + Mockito.when(this.employeeService.findById(1)).thenReturn(Optional.of(aEmployee)); + RestAssuredMockMvc.standaloneSetup(this.employeeController); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/EmployeeControllerTest.java b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/EmployeeControllerTest.java new file mode 100644 index 00000000..00a9ce01 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/java/com/espark/adarsh/producer/EmployeeControllerTest.java @@ -0,0 +1,45 @@ +package com.espark.adarsh.producer; + +import static io.restassured.RestAssured.get; +import static org.hamcrest.CoreMatchers.equalTo; + +import javax.annotation.PostConstruct; + +import com.espark.adarsh.producer.service.EmployeeService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class EmployeeControllerTest extends ApplicationMainTests { + + @LocalServerPort + private int port; + + private String uri; + + @Autowired + EmployeeService employeeRepository; + + @PostConstruct + public void init() { + uri = "http://localhost:" + port; + } + + + @Test + public void getEmployeeFoundTest() { + get(uri + "/employee/1").then().assertThat().statusCode(200).body("fname", equalTo("Adarsh")); + } + + @Test + public void getEmployeeNotFoundTest() { + get(uri + "/employee/21").then().assertThat().statusCode(404); + } + +} diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdFound.groovy b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdFound.groovy new file mode 100644 index 00000000..5a26bc87 --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdFound.groovy @@ -0,0 +1,24 @@ +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + description("When a GET request with a Employee id=1 is made, the Employee object is returned") + request { + method 'GET' + url '/employee/1' + } + response { + status 200 + body(""" + { + "id": "1", + "fname": "Adarsh", + "lname": "Kumar", + "salary": "1000.0", + "gender": "M" + } + """) + headers { + contentType(applicationJson()) + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdNotFound.groovy b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdNotFound.groovy new file mode 100644 index 00000000..e8a55f4d --- /dev/null +++ b/APPLICATIONS/springboot-contact-validation/springboot-contract-producer-validation/src/test/resources/contracts/shouldReturnEmployeeWhenEmployeeIdNotFound.groovy @@ -0,0 +1,19 @@ +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + description("When a GET request with a Employee id=1 is made, the Employee object is returned") + request { + method 'GET' + url '/employee/21' + } + response { + status 404 + body(""" + { + } + """) + headers { + contentType(applicationJson()) + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-auto-configuration/.gitignore b/APPLICATIONS/springboot-custom-auto-configuration/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-auto-configuration/document/help.txt b/APPLICATIONS/springboot-custom-auto-configuration/document/help.txt new file mode 100644 index 00000000..3b974944 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/document/help.txt @@ -0,0 +1,33 @@ +#To build +$ mvn clean package + +#to execute +$ cd espark-web + +#To execute the application +espark-web $ mvn spring-boot:run + +#To hit the end point +$ curl http://localhsot:8080/message/adarsh + + +---------------- configuration ---------------- +1.To Enable the Services +#espark.service.enable=false +#espark.service.enable=true + +2.to Enable the type of service from module +#espark.service.type=local +#espark.service.type=remote + +3.to provide custom msg to each service +local.espark.msg=hello from local service +remote.espark.msg=hello from remote service. + +4.to provide generic message for both service +espark.application.msg=WELCOME TO THE ESPARK +------------------------------------------------ +NOTE + IF MODULE IS NOT ACTIVE THEN DEFAULT SERVICE WILL BE ACTIVE + IF NON OF THE SERVICE IS ACTIVE THEN DEFAULT SERVICE WILL ACTIVE + OTHER WISE BASED ON TEH CONFIGURATION SERVICE WILL WORK diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/pom.xml b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/pom.xml new file mode 100644 index 00000000..fca5104a --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/pom.xml @@ -0,0 +1,20 @@ + + + + springboot-custom-auto-configuration + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + espark-service + 0.0.1-SNAPSHOT + + 1.8 + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java new file mode 100644 index 00000000..f011b723 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.bean; + +public class ApplicationMessageBean { + + String message; + + public ApplicationMessageBean(){ + + } + + public ApplicationMessageBean(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java new file mode 100644 index 00000000..39878e88 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.configuration; + +import com.espark.adarsh.service.EsparkService; +import com.espark.adarsh.service.EsparkServiceDefaultImpl; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Slf4j +@Configuration +public class ApplicationConfiguration { + + @Bean("esparkServiceDefaultImpl") + @ConditionalOnExpression("'${espark.service.enable}' != 'true'") + public EsparkService instantiateDefaultService() { + log.info("label=configuration EsparkServiceDefaultImpl"); + return new EsparkServiceDefaultImpl(); + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/EsparkServiceAutoConfiguration.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/EsparkServiceAutoConfiguration.java new file mode 100644 index 00000000..b2811b31 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/EsparkServiceAutoConfiguration.java @@ -0,0 +1,88 @@ +package com.espark.adarsh.configuration; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import com.espark.adarsh.configuration.condition.LocalCondition; +import com.espark.adarsh.configuration.condition.RemoteCondition; +import com.espark.adarsh.service.EsparkService; +import com.espark.adarsh.service.EsparkServiceDefaultImpl; +import com.espark.adarsh.service.EsparkServiceLocalImpl; +import com.espark.adarsh.service.EsparkServiceRemoteImpl; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; + +import java.util.Properties; + +@Slf4j +@Configuration +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +@PropertySource("classpath:espark.properties") +@ConditionalOnProperty(name = "espark.service.enable", havingValue = "true") +public class EsparkServiceAutoConfiguration { + + + @Autowired + private Environment environment; + + @Bean + @ConditionalOnResource(resources = "classpath:espark.properties") + @ConditionalOnMissingBean + public ApplicationMessageBean instantiateApplicationMessageBean() { + log.info("label=configuration ApplicationMessageBean"); + return new ApplicationMessageBean(environment.getProperty("espark.application.msg")); + } + + @Bean("esparkServiceDefaultImpl") + @ConditionalOnMissingBean(EsparkService.class) + public EsparkService instantiateDefaultService() { + log.info("label=configuration EsparkServiceDefaultImpl"); + return new EsparkServiceDefaultImpl(); + } + + @Bean("esparkServiceLocalImpl") + @ConditionalOnMissingBean + @ConditionalOnBean(ApplicationMessageBean.class) + @ConditionalOnProperty(name = "espark.service.type", havingValue = "local") + public EsparkService instantiateLocalService() { + log.info("label=configuration EsparkServiceLocalImpl"); + return new EsparkServiceLocalImpl(); + } + + @Bean("esparkServiceRemoteImpl") + @ConditionalOnMissingBean + @ConditionalOnBean(ApplicationMessageBean.class) + @ConditionalOnProperty(name = "espark.service.type", havingValue = "remote") + public EsparkService instantiateRemoteService() { + log.info("label=configuration EsparkServiceRemoteImpl"); + return new EsparkServiceRemoteImpl(); + } + + @Bean + @ConditionalOnResource(resources = "classpath:espark.properties") + @Conditional(LocalCondition.class) + public Properties localProperties() { + Properties localProperties = new Properties(); + localProperties.setProperty("local.espark.msg", environment.getProperty("local.espark.msg")); + return localProperties; + } + + @Bean + @ConditionalOnResource(resources = "classpath:espark.properties") + @Conditional(RemoteCondition.class) + public Properties remoteProperties() { + Properties remoteProperties = new Properties(); + remoteProperties.setProperty("remote.espark.msg", environment.getProperty("remote.espark.msg")); + return remoteProperties; + } + +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/LocalCondition.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/LocalCondition.java new file mode 100644 index 00000000..ded6735a --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/LocalCondition.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.configuration.condition; + +import org.springframework.boot.autoconfigure.condition.ConditionMessage; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.util.ClassUtils; + +import java.util.Arrays; + +public class LocalCondition extends SpringBootCondition { + + private static final String[] CLASS_NAMES = { "com.espark.adarsh.service.EsparkServiceLocalImpl"}; + + @Override + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Local"); + + return Arrays.stream(CLASS_NAMES) + .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) + .map(className -> ConditionOutcome.match(message.found("class").items( + ConditionMessage.Style.NORMAL, className))).findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items( + ConditionMessage.Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/RemoteCondition.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/RemoteCondition.java new file mode 100644 index 00000000..1fc2c6bc --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/configuration/condition/RemoteCondition.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.configuration.condition; + +import org.springframework.boot.autoconfigure.condition.ConditionMessage; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.util.ClassUtils; + +import java.util.Arrays; + +public class RemoteCondition extends SpringBootCondition { + + private static final String[] CLASS_NAMES = { "com.espark.adarsh.service.EsparkServiceRemoteImpl"}; + + @Override + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("Remote"); + + return Arrays.stream(CLASS_NAMES) + .filter(className -> ClassUtils.isPresent(className, context.getClassLoader())) + .map(className -> ConditionOutcome.match(message.found("class").items( + ConditionMessage.Style.NORMAL, className))).findAny() + .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items( + ConditionMessage.Style.NORMAL, Arrays.asList(CLASS_NAMES)))); + } + +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkService.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkService.java new file mode 100644 index 00000000..6ad0ac6f --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkService.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.ApplicationMessageBean; + +public interface EsparkService { + + public String doOperation(String name); + + default void setApplicationMessageBean(ApplicationMessageBean applicationMessageBean){ + + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceDefaultImpl.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceDefaultImpl.java new file mode 100644 index 00000000..f08e9dcd --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceDefaultImpl.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.service; + + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EsparkServiceDefaultImpl implements EsparkService { + + @Override + public String doOperation(String name) { + log.info("label=EsparkService Default name={}", name); + return "Espark Default " + name; + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceLocalImpl.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceLocalImpl.java new file mode 100644 index 00000000..0e4987c3 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceLocalImpl.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Properties; + +@Slf4j +public class EsparkServiceLocalImpl implements EsparkService { + + + @Autowired + private Properties localProperties; + + @Autowired + private ApplicationMessageBean applicationMessageBean; + + @Override + public String doOperation(String name) { + log.info("label=EsparkService Local name={}", name); + return "Espark Local " + + name + " " + + this.applicationMessageBean.getMessage() + + " " + localProperties.getProperty("local.espark.msg"); + } + + @Override + public void setApplicationMessageBean(ApplicationMessageBean applicationMessageBean) { + this.applicationMessageBean = applicationMessageBean; + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceRemoteImpl.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceRemoteImpl.java new file mode 100644 index 00000000..648b4d03 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/java/com/espark/adarsh/service/EsparkServiceRemoteImpl.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Properties; + +@Slf4j +public class EsparkServiceRemoteImpl implements EsparkService { + + @Autowired + private Properties remoteProperties; + + @Autowired + private ApplicationMessageBean applicationBean; + + @Override + public String doOperation(String name) { + log.info("label=EsparkService Remote name={}", name); + return "Espark Remote " + + name + " " + + this.applicationBean.getMessage() + + " " + remoteProperties.getProperty("remote.espark.msg"); + } + + public void setApplicationBean(ApplicationMessageBean applicationBean) { + this.applicationBean = applicationBean; + } + +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/resources/META-INF/spring.factories b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..47cb3601 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-service/src/main/resources/META-INF/spring.factories @@ -0,0 +1,4 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + +########## To Enable Espark Custom Annotation Configuration ########## +com.espark.adarsh.configuration.EsparkServiceAutoConfiguration \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-web/pom.xml b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/pom.xml new file mode 100644 index 00000000..d1f74d4e --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/pom.xml @@ -0,0 +1,36 @@ + + + + springboot-custom-auto-configuration + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + espark-web + + + 1.8 + + + + + com.espark.adarsh + espark-service + 0.0.1-SNAPSHOT + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..197478e0 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,20 @@ +package com.espark.adarsh; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +import java.util.Arrays; + +@Slf4j +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(ApplicationMain.class, args); + Arrays.asList(applicationContext.getBeanDefinitionNames()).stream().forEach(log::info); + + } + +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..00208bea --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.EsparkService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +public class ApplicationController { + + @Autowired + private EsparkService esparkService; + + @GetMapping("/message/{name}") + public String getWish(@PathVariable("name") String name) { + log.info("label=ApplicationController name={}", name); + return this.esparkService.doOperation(name); + } +} diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/application.properties new file mode 100644 index 00000000..fe764c28 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/application.properties @@ -0,0 +1,9 @@ + + +logging.level.root=DEBUG +logging.level.com.espark.adarsh=DEBUG + +############# FOR ENABLING ESPARK SERVICES MODULE ######### +#espark.service.enable=false +#espark.service.enable=true +########################################################### diff --git a/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/espark.properties b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/espark.properties new file mode 100644 index 00000000..c52af3c1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/espark-web/src/main/resources/espark.properties @@ -0,0 +1,21 @@ + + + +############# TO ENABLE THE ESPARK SERVICD TYPE ########### +#espark.service.type=local +#espark.service.type=remote +########################################################### + + + +############# CUSTOM MSG FOR TYPE OF SERVICE ############## +local.espark.msg=hello from local service +remote.espark.msg=hello from remote service. +########################################################### + + + +################ GENERIC MSG FOR ALL TYPE ################# + +espark.application.msg=WELCOME TO THE ESPARK +########################################################### diff --git a/APPLICATIONS/springboot-custom-auto-configuration/pom.xml b/APPLICATIONS/springboot-custom-auto-configuration/pom.xml new file mode 100644 index 00000000..dfce6e97 --- /dev/null +++ b/APPLICATIONS/springboot-custom-auto-configuration/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + pom + + espark-service + espark-web + + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-custom-auto-configuration + 0.0.1-SNAPSHOT + springboot-custom-auto-configuration + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/.gitignore b/APPLICATIONS/springboot-custom-autoconfiguration/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/README.md b/APPLICATIONS/springboot-custom-autoconfiguration/README.md new file mode 100644 index 00000000..e9230070 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/README.md @@ -0,0 +1,5 @@ +# spring boot custom autoconfig + +--- + +* http://localhost:8080/wish/adarsh \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/pom.xml b/APPLICATIONS/springboot-custom-autoconfiguration/pom.xml new file mode 100644 index 00000000..b289e22d --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.espark.adarsh + springboot-custom-autoconfiguration + 0.0.1-SNAPSHOT + springboot-custom-autoconfiguration + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplication.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplication.java new file mode 100644 index 00000000..53ba3150 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootCustomAutoconfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootCustomAutoconfigurationApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigCustomProps.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigCustomProps.java new file mode 100644 index 00000000..c50f80c8 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigCustomProps.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.service.EsparkApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConditionalOnBean(EsparkProcessConfig.class) +public class ApplicationConfigCustomProps { + + @Autowired + EsparkProcessConfig esparkProcessConfig; + + @Bean + @ConditionalOnMissingBean + public EsparkApplicationService esparkApplicationService(){ + return new EsparkApplicationService(this.esparkProcessConfig.getService()); + } +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigDefaultProps.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigDefaultProps.java new file mode 100644 index 00000000..279dc9e0 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/ApplicationConfigDefaultProps.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.service.EsparkApplicationService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConditionalOnMissingBean(EsparkProcessConfig.class) +public class ApplicationConfigDefaultProps { + + @Bean + @ConditionalOnMissingBean + public EsparkApplicationService esparkApplicationService(){ + return new EsparkApplicationService(new EsparkServiceMessage("Without Service Activated")); + } +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkProcessConfig.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkProcessConfig.java new file mode 100644 index 00000000..2ebe16db --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkProcessConfig.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.config; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Slf4j +@Setter +@Getter +@Component +@ConditionalOnProperty(name = "application.espark.process.config.enable",havingValue = "true") +@ConfigurationProperties(prefix = "application.espark.process.config") +public class EsparkProcessConfig { + Boolean enable; + EsparkServiceMessage service; +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkServiceMessage.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkServiceMessage.java new file mode 100644 index 00000000..2af6d58b --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/config/EsparkServiceMessage.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.config; + +import lombok.*; + +@Data +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class EsparkServiceMessage { + + String message; +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/service/EsparkApplicationService.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/service/EsparkApplicationService.java new file mode 100644 index 00000000..3fc680d1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/service/EsparkApplicationService.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.service; + + +import com.espark.adarsh.config.EsparkServiceMessage; + +import java.util.function.Function; + +public class EsparkApplicationService { + + EsparkServiceMessage esparkServiceMessage; + + public EsparkApplicationService(EsparkServiceMessage esparkServiceMessage) { + this.esparkServiceMessage = esparkServiceMessage; + } + + public Function displayGreeting = (name)->{ + return this.esparkServiceMessage.getMessage()+" "+name; + }; +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..da1c3c49 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.EsparkApplicationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @Autowired + EsparkApplicationService applicationService; + + + @GetMapping("/wish/{name}") + public String getGreeting(@PathVariable("name")String name){ + return this.applicationService.displayGreeting.apply(name); + } +} diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/main/resources/application.yml b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/resources/application.yml new file mode 100644 index 00000000..7f0a0176 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/main/resources/application.yml @@ -0,0 +1,12 @@ +spring: + application: + name: springboot-custom-autoconfiguration + + +application: + espark: + process: + config: + enable: true + service: + message: "application service is active " \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-autoconfiguration/src/test/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplicationTests.java b/APPLICATIONS/springboot-custom-autoconfiguration/src/test/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplicationTests.java new file mode 100644 index 00000000..340b9c63 --- /dev/null +++ b/APPLICATIONS/springboot-custom-autoconfiguration/src/test/java/com/espark/adarsh/SpringbootCustomAutoconfigurationApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootCustomAutoconfigurationApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-custom-exception-serializer/.gitignore b/APPLICATIONS/springboot-custom-exception-serializer/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-exception-serializer/README.md b/APPLICATIONS/springboot-custom-exception-serializer/README.md new file mode 100644 index 00000000..9e7d0f7e --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/README.md @@ -0,0 +1,15 @@ +# spring boot-custom exception serializer + +--- +> spring boot-custom exception serializer with jaxson api +> custom json serializer and de-serializer class using +> @JsonComponent annotation with spring unit test case + +### To Build the Code +* mvn clean package + + +### To Run the Code +* mvn spring-boot:run + + diff --git a/APPLICATIONS/springboot-custom-exception-serializer/pom.xml b/APPLICATIONS/springboot-custom-exception-serializer/pom.xml new file mode 100644 index 00000000..cb463ed7 --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.5.2 + + + com.espark.adarsh + springboot-custom-exception-serializer + 0.0.1-SNAPSHOT + springboot-custom-exception-serializer + springboot-custom-exception-serializer + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/ExceptionSerilizerApplication.java b/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/ExceptionSerilizerApplication.java new file mode 100644 index 00000000..d14be2fa --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/ExceptionSerilizerApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.exceptionserilizer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExceptionSerilizerApplication { + + public static void main(String[] args) { + SpringApplication.run(ExceptionSerilizerApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/util/ApplicationExceptionSerializer.java b/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/util/ApplicationExceptionSerializer.java new file mode 100644 index 00000000..d06eb014 --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/src/main/java/com/espark/adarsh/exceptionserilizer/util/ApplicationExceptionSerializer.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.exceptionserilizer.util; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.*; +import org.springframework.boot.jackson.JsonComponent; + +import java.io.IOException; + +@JsonComponent +public class ApplicationExceptionSerializer { + + public static class ExceptionSerializer extends JsonSerializer { + @Override + public void serialize(Exception e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) + throws IOException { + System.out.println("exception serializer executed "); + jsonGenerator.writeStartObject(); + jsonGenerator.writeStringField("class", e.getClass().getName()); + jsonGenerator.writeStringField("message", e.getMessage()); + jsonGenerator.writeStringField("localMessage", e.getLocalizedMessage()); + jsonGenerator.writeEndObject(); + } + } + + + public static class ExceptionDeserializer extends JsonDeserializer { + @Override + public Exception deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) + throws IOException, JsonProcessingException { + System.out.println("exception de-serializer executed "); + JsonNode node = jsonParser.getCodec().readTree(jsonParser); + String message = node.get("message").asText(); + String className = node.get("class").asText(); + return new Exception(message); + } + } + +} diff --git a/APPLICATIONS/springboot-custom-exception-serializer/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-exception-serializer/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-custom-exception-serializer/src/test/java/com/espark/adarsh/exceptionserilizer/ExceptionSerializerApplicationTests.java b/APPLICATIONS/springboot-custom-exception-serializer/src/test/java/com/espark/adarsh/exceptionserilizer/ExceptionSerializerApplicationTests.java new file mode 100644 index 00000000..8ca3e2bb --- /dev/null +++ b/APPLICATIONS/springboot-custom-exception-serializer/src/test/java/com/espark/adarsh/exceptionserilizer/ExceptionSerializerApplicationTests.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.exceptionserilizer; + +import com.espark.adarsh.exceptionserilizer.util.ApplicationExceptionSerializer; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.util.Assert; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +@SpringBootTest +class ExceptionSerializerApplicationTests { + + @Autowired + ObjectMapper objectMapper; + + @Test + void contextLoads() { + } + + @Test + public void testExceptionExceptionSerializer() throws IOException { + String response ="somethings went wrong"; + Exception e = new Exception(){ + @Override + public String getMessage() { + return "somethings went wrong"; + } + }; + Writer jsonWriter = new StringWriter(); + JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonWriter); + SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); + new ApplicationExceptionSerializer.ExceptionSerializer().serialize(e,jsonGenerator,serializerProvider); + jsonGenerator.flush(); + System.out.println(jsonWriter.toString()); + Assert.isTrue(jsonWriter.toString().contains(response),"Response is not Excepted"); + } + + @Test + public void testExceptionExceptionDeSerializer() throws IOException { + String response ="somethings went wrong"; + String exceptionJsonString ="{\"class\":\"java.lang.Exception\",\"message\":\"somethings went wrong\"}"; + Exception e = objectMapper.readValue(exceptionJsonString,Exception.class); + System.out.println(e.toString()); + Assert.isTrue(e.getMessage().contains(response),"Response is not Excepted"); + } + +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/.gitignore b/APPLICATIONS/springboot-custom-healthcheck-actuator/.gitignore new file mode 100644 index 00000000..e33b8fc9 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/.gitignore @@ -0,0 +1,38 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +.DS_Store +*.DS_Store +/*.DS_Store + + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/README.md b/APPLICATIONS/springboot-custom-healthcheck-actuator/README.md new file mode 100644 index 00000000..4b655b0e --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/README.md @@ -0,0 +1,103 @@ +# springboot-custom-healthcheck-actuator + +### To Build +* mvn clean package + + +### To Run +* mvn spring-boot:run + + +### Api Url +* curl -X GET http://localhost:8080/api/wish +``` +{ + "message": "welcome to the espark " +} +``` +* curl -X GET http://localhost:8080/actuator/health +``` +{ + "status": "UP", + "components": { + "db": { + "status": "UP", + "details": { + "database": "H2", + "validationQuery": "isValid()" + } + }, + "diskSpace": { + "status": "UP", + "details": { + "total": 499963174912, + "free": 305292124160, + "threshold": 10485760, + "exists": true + } + }, + "integrationService": { + "status": "UP", + "details": { + "Integration-Service": "Available" + } + }, + "ping": { + "status": "UP" + }, + "wishService": { + "status": "UP", + "details": { + "Wish-Service": "Available" + } + } + } +} +``` +* curl -X GET http://localhost:8080/actuator/rest-api +``` +{ + "request-type": "server api get request", + "server.date": "2022-01-27", + "server-api": "server api is up and running", + "server.time": "13:23:03.151125" +} +``` +* curl -X POST http://localhost:8080/actuator/rest-api -d 'adarsh kumar' +``` +{ + "request-type": "server api post request", + "server.date": "2022-01-27", + "server-api": "server api is up and running", + "server.time": "13:23:24.134326" +} +``` + + +* curl -X GET http://localhost:8080/actuator/server-operation +``` +{ + "operation-type": "server-api-read-operation", + "server.date": "2022-01-27", + "server-operation-api": "server api is up and running", + "server.time": "13:20:40.347791" +} +``` +* curl -X DELETE http://localhost:8080/actuator/server-operation +``` +{ + "operation-type": "server-api-delete-operation", + "server.date": "2022-01-27", + "server-operation-api": "server api is up and running", + "server.time": "13:20:53.931177" +} +``` +* curl -X POST http://localhost:8080/actuator/server-operation +``` +{ + "operation-type": "server-api-write-operation", + "server.date": "2022-01-27", + "server-operation-api": "server api is up and running", + "server.time": "13:21:18.130368" +} +``` diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/pom.xml b/APPLICATIONS/springboot-custom-healthcheck-actuator/pom.xml new file mode 100644 index 00000000..53a86158 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + com.espark.adarsh + springboot-custom-healthcheck-actuator + 0.0.1-SNAPSHOT + springboot-custom-healthcheck-actuator + Demo project for Spring Boot + + 11 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/IntegrationServiceHealthIndicator.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/IntegrationServiceHealthIndicator.java new file mode 100644 index 00000000..f2b481ed --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/IntegrationServiceHealthIndicator.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.actuator; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class IntegrationServiceHealthIndicator implements HealthIndicator { + + private final String message_key = "Integration-Service"; + + @Override + public Health health() { + log.info("IntegrationServiceHealthIndicator::health()"); + if (!isRunningIntegrationService()) { + return Health.down().withDetail(message_key, "Not Available").build(); + } + return Health.up().withDetail(message_key, "Available").build(); + } + + private Boolean isRunningIntegrationService() { + log.info("IntegrationServiceHealthIndicator::isRunningIntegrationService()"); + Boolean isRunning = false; + // temp logic + if (System.nanoTime() % 2 == 0L) { + isRunning = true; + } + return isRunning; + } +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/RestApiActuator.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/RestApiActuator.java new file mode 100644 index 00000000..2bf66d2c --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/RestApiActuator.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.actuator; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +@RestControllerEndpoint(id = "rest-api") +public class RestApiActuator { + + @GetMapping + public Map getRestApiActuatorHealth() { + log.info("RestApiActuator::getRestApiActuatorHealth()"); + return new HashMap<>(){ + { + put("server-api","server api is up and running"); + put("request-type","server api get request"); + put("server.date", LocalDate.now().toString()); + put("server.time", LocalTime.now().toString()); + } + }; + } + + @PostMapping + public Map postRequest(@RequestBody String request) { + log.info("RestApiActuator::postRequest()"); + return new HashMap<>(){ + { + put("server-api","server api is up and running"); + put("request-type","server api post request"); + put("server.date", LocalDate.now().toString()); + put("server.time", LocalTime.now().toString()); + } + }; + } + +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/ServerOperationActuator.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/ServerOperationActuator.java new file mode 100644 index 00000000..b60f6023 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/ServerOperationActuator.java @@ -0,0 +1,58 @@ +package com.espark.adarsh.actuator; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; +import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +@Endpoint(id = "server-operation") +public class ServerOperationActuator { + + @ReadOperation + public Map readOperation() { + log.info("ServerOperationActuator::readOperation()"); + return new HashMap<>() { + { + put("server-operation-api", "server api is up and running"); + put("operation-type", "server-api-read-operation"); + put("server.date", LocalDate.now().toString()); + put("server.time", LocalTime.now().toString()); + } + }; + } + + @WriteOperation + public Map writeOperation() { + log.info("ServerOperationActuator::writeOperation()"); + return new HashMap<>() { + { + put("server-operation-api", "server api is up and running"); + put("operation-type", "server-api-write-operation"); + put("server.date", LocalDate.now().toString()); + put("server.time", LocalTime.now().toString()); + } + }; + } + + @DeleteOperation + public Map deleteOperation() { + log.info("ServerOperationActuator::deleteOperation()"); + return new HashMap<>() { + { + put("server-operation-api", "server api is up and running"); + put("operation-type", "server-api-delete-operation"); + put("server.date", LocalDate.now().toString()); + put("server.time", LocalTime.now().toString()); + } + }; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/WishServiceHealthIndicator.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/WishServiceHealthIndicator.java new file mode 100644 index 00000000..33353540 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/actuator/WishServiceHealthIndicator.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.actuator; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class WishServiceHealthIndicator implements HealthIndicator { + + private final String message_key = "Wish-Service"; + + @Override + public Health health() { + log.info("WishServiceHealthIndicator::health()"); + if (!isRunningWishService()) { + return Health.down().withDetail(message_key, "Not Available").build(); + } + return Health.up().withDetail(message_key, "Available").build(); + } + + private Boolean isRunningWishService() { + log.info("WishServiceHealthIndicator::isRunningWishService()"); + Boolean isRunning = false; + // temp logic + if (System.nanoTime() % 2 == 0L) { + isRunning = true; + } + return isRunning; + } +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..5daa8ac1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.web; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @GetMapping("/wish") + public Map getWish() { + log.info("ApplicationController::getWish()"); + return new HashMap<>() { + { + put("message", "welcome to the espark "); + } + }; + } +} diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.yaml b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.yaml new file mode 100644 index 00000000..210afc33 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/main/resources/application.yaml @@ -0,0 +1,16 @@ + +spring: + application: + name: springboot-custom-healthcheck-actuator + +server: + port: 8080 + +management: + endpoint: + health: + show-details: always + endpoints: + web: + exposure: + include: '*' \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-healthcheck-actuator/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/springboot-custom-healthcheck-actuator/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-custom-module/.gitignore b/APPLICATIONS/springboot-custom-module/.gitignore new file mode 100644 index 00000000..153c9335 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-module/doc/help.txt b/APPLICATIONS/springboot-custom-module/doc/help.txt new file mode 100644 index 00000000..b17a5e8c --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/doc/help.txt @@ -0,0 +1,5 @@ +$ mvn clean package + +GET method +http://localhost:8080/espark/wish + diff --git a/APPLICATIONS/springboot-custom-module/pom.xml b/APPLICATIONS/springboot-custom-module/pom.xml new file mode 100644 index 00000000..f28ab778 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + pom + + org.springframework.boot + spring-boot-starter-parent + 2.1.4.RELEASE + + + com.espark.adarsh + springboot-custom-module + 0.0.1-SNAPSHOT + springboot-custom-module + Demo project for Spring Boot + + + 1.8 + + + + wish-module + web-module + wish-auto-configuration + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + diff --git a/APPLICATIONS/springboot-custom-module/web-module/README.md b/APPLICATIONS/springboot-custom-module/web-module/README.md new file mode 100644 index 00000000..e80c770b --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/README.md @@ -0,0 +1,6 @@ +# web module +--- +> web module will consume the wish autoconfiguration module +> add the maven dependency to the web module pom +> then configured the properties which is required by the wish module in the yaml file +> then we will have the Greeter class available via autoconfiguration \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/web-module/pom.xml b/APPLICATIONS/springboot-custom-module/web-module/pom.xml new file mode 100644 index 00000000..9c8ada9e --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/pom.xml @@ -0,0 +1,32 @@ + + + + springboot-custom-module + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + web-module + + + + com.espark.adarsh + wish-auto-configuration + 0.0.1-SNAPSHOT + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/controller/WishController.java b/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/controller/WishController.java new file mode 100644 index 00000000..10b5d2b5 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/src/main/java/com/espark/adarsh/controller/WishController.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.Greeter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/espark") +public class WishController { + + @Autowired + private Greeter greeter; + + @GetMapping("/wish") + public String getWish() { + String message = greeter.greet(); + return message; + } +} diff --git a/APPLICATIONS/springboot-custom-module/web-module/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-module/web-module/src/main/resources/application.properties new file mode 100644 index 00000000..5a5e1ee1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/src/main/resources/application.properties @@ -0,0 +1,3 @@ + +espark.greeter.afternoonMessage='hi Afternoon' +espark.greeter.userName='adarsh kumar' diff --git a/APPLICATIONS/springboot-custom-module/web-module/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-custom-module/web-module/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/web-module/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/README.md b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/README.md new file mode 100644 index 00000000..99ef7687 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/README.md @@ -0,0 +1,9 @@ +# wish autoconfiguration module +--- +> wish autoconfiguration module will provide a autoconfiguration +> for wish module so that when any code project will import this wish autoconfiguration +> it will create a respective classes from wish module based on the config values +> for the wish module +> +> it read the config values from the yaml|properties and create a WishConfiguration +> and make it available to the spring context for autowire \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/pom.xml b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/pom.xml new file mode 100644 index 00000000..7b2cd383 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/pom.xml @@ -0,0 +1,22 @@ + + + + springboot-custom-module + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + wish-auto-configuration + + + + com.espark.adarsh + wish-module + 0.0.1-SNAPSHOT + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/GreeterProperties.java b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/GreeterProperties.java new file mode 100644 index 00000000..d2408ce8 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/GreeterProperties.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Data +@ConfigurationProperties(prefix = "espark.greeter") +public class GreeterProperties { + + private String userName; + private String morningMessage; + private String afternoonMessage; + private String eveningMessage; + private String nightMessage; + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/autoconfigure/GreeterAutoConfiguration.java b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/autoconfigure/GreeterAutoConfiguration.java new file mode 100644 index 00000000..7bff86fd --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/java/com/espark/adarsh/autoconfigure/GreeterAutoConfiguration.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.autoconfigure; + +import static com.espark.adarsh.GreeterConfigParams.AFTERNOON_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.EVENING_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.MORNING_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.NIGHT_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.USER_NAME; + +import com.espark.adarsh.Greeter; +import com.espark.adarsh.GreeterProperties; +import com.espark.adarsh.GreetingConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConditionalOnClass(Greeter.class) +@EnableConfigurationProperties(GreeterProperties.class) +public class GreeterAutoConfiguration { + + @Autowired + private GreeterProperties greeterProperties; + + @Bean + @ConditionalOnMissingBean + public GreetingConfig greeterConfig() { + + GreetingConfig greetingConfig = new GreetingConfig(); + String userName = greeterProperties.getUserName() == null + ? System.getProperty("user.name") + : greeterProperties.getUserName(); + greetingConfig.put(USER_NAME, userName); + + String morningMsg = greeterProperties.getMorningMessage(); + if (morningMsg != null && !morningMsg.isEmpty()) { + greetingConfig.put(MORNING_MESSAGE, morningMsg); + } + + String afternoonMsg = greeterProperties.getAfternoonMessage(); + if (afternoonMsg != null && !afternoonMsg.isEmpty()) { + greetingConfig.put(AFTERNOON_MESSAGE, afternoonMsg); + } + + String eveningMsg = greeterProperties.getEveningMessage(); + if (eveningMsg != null && !eveningMsg.isEmpty()) { + greetingConfig.put(EVENING_MESSAGE, eveningMsg); + } + String nightMsg = greeterProperties.getNightMessage(); + if (nightMsg != null && !nightMsg.isEmpty()) { + greetingConfig.put(NIGHT_MESSAGE, nightMsg); + } + return greetingConfig; + } + + @Bean + @ConditionalOnMissingBean + public Greeter greeter(GreetingConfig greetingConfig) { + return new Greeter(greetingConfig); + } +} + diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/META-INF/spring.factories b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..621f456f --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.espark.adarsh.autoconfigure.GreeterAutoConfiguration \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/logback.xml b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/logback.xml new file mode 100644 index 00000000..26beb6d5 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-auto-configuration/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-module/README.md b/APPLICATIONS/springboot-custom-module/wish-module/README.md new file mode 100644 index 00000000..1827fb6b --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/README.md @@ -0,0 +1,4 @@ +# wish module +--- +> wish module will provide a service to provide the wish msg. +> it will take values form wish configuration. \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-module/pom.xml b/APPLICATIONS/springboot-custom-module/wish-module/pom.xml new file mode 100644 index 00000000..dce5dde3 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/pom.xml @@ -0,0 +1,23 @@ + + + + + springboot-custom-module + com.espark.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + wish-module + + + org.projectlombok + lombok + 1.18.4 + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/Greeter.java b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/Greeter.java new file mode 100644 index 00000000..a2f7fb19 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/Greeter.java @@ -0,0 +1,38 @@ +package com.espark.adarsh; + +import static com.espark.adarsh.GreeterConfigParams.AFTERNOON_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.EVENING_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.MORNING_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.NIGHT_MESSAGE; +import static com.espark.adarsh.GreeterConfigParams.USER_NAME; + +import java.time.LocalDateTime; + +public class Greeter { + + private GreetingConfig greetingConfig; + + public Greeter(GreetingConfig greetingConfig) { + this.greetingConfig = greetingConfig; + } + + public String greet() { + return greet(LocalDateTime.now()); + } + + public String greet(LocalDateTime localDateTime) { + + String name = greetingConfig.getProperty(USER_NAME); + int hourOfDay = localDateTime.getHour(); + + if (hourOfDay >= 5 && hourOfDay < 12) { + return String.format("Hello %s, %s", name, greetingConfig.get(MORNING_MESSAGE)); + } else if (hourOfDay >= 12 && hourOfDay < 17) { + return String.format("Hello %s, %s", name, greetingConfig.get(AFTERNOON_MESSAGE)); + } else if (hourOfDay >= 17 && hourOfDay < 20) { + return String.format("Hello %s, %s", name, greetingConfig.get(EVENING_MESSAGE)); + } else { + return String.format("Hello %s, %s", name, greetingConfig.get(NIGHT_MESSAGE)); + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreeterConfigParams.java b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreeterConfigParams.java new file mode 100644 index 00000000..18ae088a --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreeterConfigParams.java @@ -0,0 +1,11 @@ +package com.espark.adarsh; + +public class GreeterConfigParams { + + public static final String USER_NAME = "user.name"; + public static final String MORNING_MESSAGE = "morning.message"; + public static final String AFTERNOON_MESSAGE = "afternoon.message"; + public static final String EVENING_MESSAGE = "evening.message"; + public static final String NIGHT_MESSAGE = "night.message"; + +} diff --git a/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreetingConfig.java b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreetingConfig.java new file mode 100644 index 00000000..c6b2ead1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/src/main/java/com/espark/adarsh/GreetingConfig.java @@ -0,0 +1,9 @@ +package com.espark.adarsh; + +import java.util.Properties; + +public class GreetingConfig extends Properties{ + + private static final long serialVersionUID = 5662570853707247891L; + +} diff --git a/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/logback.xml b/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/logback.xml new file mode 100644 index 00000000..26beb6d5 --- /dev/null +++ b/APPLICATIONS/springboot-custom-module/wish-module/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-validator/.gitignore b/APPLICATIONS/springboot-custom-validator/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-custom-validator/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-custom-validator/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/APPLICATIONS/springboot-custom-validator/README.md b/APPLICATIONS/springboot-custom-validator/README.md new file mode 100644 index 00000000..370df254 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/README.md @@ -0,0 +1,20 @@ +# springboot-custom-validation + +---- +``` +curl --location 'http://localhost:8080/user' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "adarsh", + "email": "adarsh@kumar", + "mobile": "+18877665544", + "age": 50, + "working": true, + "aboutMe": "intelligent", + "dateOfBirth": 13091983, + "preference": [ + "java", + "iot" + ] +}' +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-validator/pom.xml b/APPLICATIONS/springboot-custom-validator/pom.xml new file mode 100644 index 00000000..8fbf381f --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.espark.adarsh + springboot-custom-validator + 0.0.1-SNAPSHOT + springboot-custom-validator + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/SpringbootCustomValidatorApplication.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/SpringbootCustomValidatorApplication.java new file mode 100644 index 00000000..835e1d38 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/SpringbootCustomValidatorApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootCustomValidatorApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootCustomValidatorApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/annotation/UserValidation.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/annotation/UserValidation.java new file mode 100644 index 00000000..2e94d609 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/annotation/UserValidation.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.annotation; + + +import com.espark.adarsh.validator.UserValidator; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = UserValidator.class) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface UserValidation { + String message() default "{error.user}"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/bean/User.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/bean/User.java new file mode 100644 index 00000000..2cfd306b --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/bean/User.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.annotation.UserValidation; +import jakarta.validation.constraints.*; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.time.LocalDate; +import java.util.List; + + +@Data +@Setter +@Getter +@ToString +@UserValidation +public class User { + + @NotBlank(message = "Invalid Name: Empty name") + @NotNull(message = "Invalid Name: Name is NULL") + @Size(min = 3, max = 30, message = "Invalid Name: Must be of 3 - 30 characters") + String name; + + @Email(message = "Invalid email") + String email; + + @NotBlank(message = "Invalid Phone number: Empty number") + @NotNull(message = "Invalid Phone number: Number is NULL") + @Pattern(regexp = "^\\d{10}$", message = "Invalid phone number") + String mobile; + + @Min(value = 1, message = "Invalid Age: Equals to zero or Less than zero") + @Max(value = 100, message = "Invalid Age: Exceeds 100 years") + Integer age; + + @AssertTrue(message = "Working must be true") + private boolean working; + + @Size(min = 10, max = 200, message + = "About Me must be between 10 and 200 characters") + private String aboutMe; + + + @Past + private LocalDate dateOfBirth; + + private List<@NotBlank String> preference; + + +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/service/UserService.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/service/UserService.java new file mode 100644 index 00000000..ef15c1ac --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/service/UserService.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class UserService { + + + public String inputUser(User user){ + + return user.toString(); + } +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/validator/UserValidator.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/validator/UserValidator.java new file mode 100644 index 00000000..81816973 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/validator/UserValidator.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.validator; + +import com.espark.adarsh.annotation.UserValidation; +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + + +@Slf4j +@Component +public class UserValidator implements ConstraintValidator { + + + @Override + public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) { + + //todo logic for validating user + log.info("UserValidation isValid {}",user); + return false; + } + + @Override + public void initialize(UserValidation constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/web/UserController.java b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/web/UserController.java new file mode 100644 index 00000000..0ac48398 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/java/com/espark/adarsh/web/UserController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.User; +import com.espark.adarsh.service.UserService; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + + @Autowired + UserService userService; + + @PostMapping("/user") + public String inputUser(@RequestBody @Valid User user){ + return this.userService.inputUser(user); + } +} diff --git a/APPLICATIONS/springboot-custom-validator/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-validator/src/main/resources/application.properties new file mode 100644 index 00000000..b1801997 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=springboot-custom-validator diff --git a/APPLICATIONS/springboot-custom-validator/src/test/java/com/espark/adarsh/SpringbootCustomValidatorApplicationTests.java b/APPLICATIONS/springboot-custom-validator/src/test/java/com/espark/adarsh/SpringbootCustomValidatorApplicationTests.java new file mode 100644 index 00000000..6bca43c1 --- /dev/null +++ b/APPLICATIONS/springboot-custom-validator/src/test/java/com/espark/adarsh/SpringbootCustomValidatorApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootCustomValidatorApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-custom-yml/.gitignore b/APPLICATIONS/springboot-custom-yml/.gitignore new file mode 100644 index 00000000..c456c4a3 --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ diff --git a/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/APPLICATIONS/springboot-custom-yml/doc/help.txt b/APPLICATIONS/springboot-custom-yml/doc/help.txt new file mode 100644 index 00000000..08ee07cd --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/doc/help.txt @@ -0,0 +1,15 @@ + + +change the profile +adarsh or radha + + +#to compile +$ mvn clean package + +#to run +$ mvn spring-boot:run + +#url +http://localhost:8080/values/prop +http://localhost:8080/values/yml \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-yml/pom.xml b/APPLICATIONS/springboot-custom-yml/pom.xml new file mode 100644 index 00000000..2985b2c2 --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.espark.adarsh + springboot-custom-yml + 0.0.1-SNAPSHOT + springboot-custom-yml + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.hibernate + hibernate-validator + 6.0.13.Final + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..b1aed80f --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,14 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} + diff --git a/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/Configurations.java b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/Configurations.java new file mode 100644 index 00000000..d5efa24b --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/Configurations.java @@ -0,0 +1,114 @@ +package com.espark.adarsh.config; +import java.util.ArrayList; +import java.util.List; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotEmpty; + +public interface Configurations { + + String getName(); + + String getCountry(); + + List getWebsite(); + + Address getAddress(); + + List getEducations(); + + public static class Address { + + @NotEmpty + String apt; + @NotEmpty + String city; + + public String getApt() { + return apt; + } + + public void setApt(String apt) { + this.apt = apt; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + } + + public static class Education { + + @NotEmpty + private String course; + + @NotEmpty + private String institution; + + @Max(2018) + @Min(1990) + private Integer year; + + private List subjects = new ArrayList<>(); + + public String getCourse() { + return course; + } + + public void setCourse(String course) { + this.course = course; + } + + public String getInstitution() { + return institution; + } + + public void setInstitution(String institution) { + this.institution = institution; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public List getSubjects() { + return subjects; + } + + public void setSubjects(List subjects) { + this.subjects = subjects; + } + } + + public static class Subject{ + + String name; + String mark; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMark() { + return mark; + } + + public void setMark(String mark) { + this.mark = mark; + } + } + +} diff --git a/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/PropertiesConfiguration.java b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/PropertiesConfiguration.java new file mode 100644 index 00000000..374f95e9 --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/PropertiesConfiguration.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.constraints.NotEmpty; + +@Configuration +@EnableConfigurationProperties +@ConfigurationProperties("prop.personal") +public class PropertiesConfiguration implements Configurations { + + @NotEmpty + private String name; + + @NotEmpty + private String country; + + private List website = new ArrayList<>(); + + private Address address; + + private List educations = new ArrayList<>(); + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public List getWebsite() { + return website; + } + + public void setWebsite(List website) { + this.website = website; + } + + @Override + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + @Override + public List getEducations() { + return educations; + } + + public void setEducations(List educations) { + this.educations = educations; + } + +} diff --git a/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/YamlConfiguration.java b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/YamlConfiguration.java new file mode 100644 index 00000000..bdbc44ef --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/config/YamlConfiguration.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.constraints.NotEmpty; + +@Configuration +@EnableConfigurationProperties +@ConfigurationProperties("yml.personal") +public class YamlConfiguration implements Configurations { + + @NotEmpty + private String name; + + @NotEmpty + private String country; + + private List website = new ArrayList<>(); + + private Address address; + + private List educations = new ArrayList<>(); + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public List getWebsite() { + return website; + } + + public void setWebsite(List website) { + this.website = website; + } + + @Override + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + @Override + public List getEducations() { + return educations; + } + + public void setEducations(List educations) { + this.educations = educations; + } + +} diff --git a/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/controller/ConfigurationController.java b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/controller/ConfigurationController.java new file mode 100644 index 00000000..f4749e8c --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/java/com/espark/adarsh/controller/ConfigurationController.java @@ -0,0 +1,93 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.config.Configurations; +import com.espark.adarsh.config.PropertiesConfiguration; +import com.espark.adarsh.config.YamlConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import java.util.ArrayList; +import java.util.List; + + +@RestController +public class ConfigurationController { + + @Autowired + private YamlConfiguration yamlConfiguration; + + @Autowired + private PropertiesConfiguration propertiesConfiguration; + + @RequestMapping(value = "/values/{type}", method = RequestMethod.GET) + public ConfigurationBean getConfigurations(@PathVariable("type") String type) { + ConfigurationBean configurationBean = null; + if (type.equalsIgnoreCase("prop")) { + configurationBean = new ConfigurationBean(propertiesConfiguration); + } else if (type.equalsIgnoreCase("yml")) { + configurationBean = new ConfigurationBean(yamlConfiguration); + } else { + throw new RuntimeException("Invalid Type "); + } + return configurationBean; + } + + class ConfigurationBean { + + private String name; + private String country; + private List website = new ArrayList<>(); + private Configurations.Address address; + private List educations = new ArrayList<>(); + + public ConfigurationBean(Configurations configurations) { + this.name = configurations.getName(); + this.country = configurations.getCountry(); + this.website = configurations.getWebsite(); + this.address = configurations.getAddress(); + this.educations = configurations.getEducations(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public List getWebsite() { + return website; + } + + public void setWebsite(List website) { + this.website = website; + } + + public Configurations.Address getAddress() { + return address; + } + + public void setAddress(Configurations.Address address) { + this.address = address; + } + + public List getEducations() { + return educations; + } + + public void setEducations(List educations) { + this.educations = educations; + } + } +} diff --git a/APPLICATIONS/springboot-custom-yml/src/main/resources/application-adarsh.properties b/APPLICATIONS/springboot-custom-yml/src/main/resources/application-adarsh.properties new file mode 100644 index 00000000..f74d387a --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/resources/application-adarsh.properties @@ -0,0 +1,20 @@ +prop.personal.name=adarsh kumar +prop.personal.country=india +prop.personal.website[0]=www.adarsh.com +prop.personal.website[1]=www.kumar.com +prop.personal.address.apt=111 +prop.personal.address.city=bang +prop.personal.educations[0].course=10 +prop.personal.educations[0].institution=Cbase +prop.personal.educations[0].subjects[0].name=hindi +prop.personal.educations[0].subjects[0].mark=80 +prop.personal.educations[0].subjects[1].name=english +prop.personal.educations[0].subjects[1].mark=90 +prop.personal.educations[0].year=1999 +prop.personal.educations[1].course=12 +prop.personal.educations[1].institution=Cbase +prop.personal.educations[1].year=2001 +prop.personal.educations[1].subjects[0].name=java +prop.personal.educations[1].subjects[0].mark=80 +prop.personal.educations[1].subjects[1].name=clang +prop.personal.educations[1].subjects[1].mark=90 diff --git a/APPLICATIONS/springboot-custom-yml/src/main/resources/application-radha.properties b/APPLICATIONS/springboot-custom-yml/src/main/resources/application-radha.properties new file mode 100644 index 00000000..845f11a0 --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/resources/application-radha.properties @@ -0,0 +1,20 @@ +prop.personal.name=radha singh +prop.personal.country=india +prop.personal.website[0]=www.radha.com +prop.personal.website[1]=www.singh.com +prop.personal.address.apt=222 +prop.personal.address.city=hyd +prop.personal.educations[0].course=10 +prop.personal.educations[0].institution=Ap Board +prop.personal.educations[0].year=2001 +prop.personal.educations[0].subjects[0].name=hindi +prop.personal.educations[0].subjects[0].mark=80 +prop.personal.educations[0].subjects[1].name=english +prop.personal.educations[0].subjects[1].mark=90 +prop.personal.educations[1].course=12 +prop.personal.educations[1].institution=Ap Board +prop.personal.educations[1].year=2004 +prop.personal.educations[1].subjects[0].name=java +prop.personal.educations[1].subjects[0].mark=80 +prop.personal.educations[1].subjects[1].name=clang +prop.personal.educations[1].subjects[1].mark=90 \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-yml/src/main/resources/application.properties b/APPLICATIONS/springboot-custom-yml/src/main/resources/application.properties new file mode 100644 index 00000000..63ec7cbd --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/resources/application.properties @@ -0,0 +1,8 @@ +#spring.profiles.active=adarsh +spring.profiles.active=radha + + +#Logging +logging.level.org.springframework.web=ERROR +logging.level.com.adarsh=ERROR +logging.level.=error diff --git a/APPLICATIONS/springboot-custom-yml/src/main/resources/application.yml b/APPLICATIONS/springboot-custom-yml/src/main/resources/application.yml new file mode 100644 index 00000000..ed81dcae --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/main/resources/application.yml @@ -0,0 +1,63 @@ +spring: + profiles: adarsh +yml: + personal: + name: adarsh kumar + country: india + website: + - www.adarsh.com + - www.kumar.com + address: + apt: 111 + city: bangalore + educations: + - course: 10 + institution: cbse + year: 1999 + subjects: + - name: english + mark: 100 + - name: hindi + mark: 85 + - course: 12 + institution: cbse + year: 2001 + subjects: + - name: java + mark: 100 + - name: clang + mark: 85 + +--- +spring: + profiles: radha +yml: + personal: + name: radha singh + country: usa + website: + - www.radha.com + - www.singh.com + address: + apt: 222 + city: hyd + educations: + - course: 10 + institution: ap board + year: 2001 + - course: 12 + institution: ap boad + year: 2004 + subjects: + - name: english + mark: 100 + - name: hindi + mark: 85 + - course: 12 + institution: cbse + year: 2001 + subjects: + - name: java + mark: 100 + - name: clang + mark: 85 \ No newline at end of file diff --git a/APPLICATIONS/springboot-custom-yml/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-custom-yml/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..021270d4 --- /dev/null +++ b/APPLICATIONS/springboot-custom-yml/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,17 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} + diff --git a/APPLICATIONS/springboot-custominterceptor/.gitignore b/APPLICATIONS/springboot-custominterceptor/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-custominterceptor/pom.xml b/APPLICATIONS/springboot-custominterceptor/pom.xml new file mode 100644 index 00000000..bf0312d5 --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-custominterceptor + 0.0.1-SNAPSHOT + jar + + springboot-custominterceptor + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/annotation/EsparkInterceptor.java b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/annotation/EsparkInterceptor.java new file mode 100644 index 00000000..3cf801b4 --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/annotation/EsparkInterceptor.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.annotation; + +import org.springframework.stereotype.Component; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +@Documented +@Component +public @interface EsparkInterceptor { + + String[] pathPatterns() default {}; + String[] excludePathPatterns() default {}; + +} diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/controller/EsparkController.java b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/controller/EsparkController.java new file mode 100644 index 00000000..764b5bf9 --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/controller/EsparkController.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +public class EsparkController { + + @GetMapping("/messge") + public Map getMessage(){ + return new HashMap(){ + { + put("adarsh","kumar"); + put("radha","singh"); + } + }; + } + + @GetMapping("/wish") + public Map getWish(){ + return new HashMap(){ + { + put("adarsh","kumar"); + put("radha","singh"); + } + }; + } +} diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/BuildTimestampInterceptor.java b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/BuildTimestampInterceptor.java new file mode 100644 index 00000000..d27336fa --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/BuildTimestampInterceptor.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.interceptor; + +import com.espark.adarsh.annotation.EsparkInterceptor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.lang.Nullable; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@EsparkInterceptor(pathPatterns = {"/messge"},excludePathPatterns = {"/wish"}) +public class BuildTimestampInterceptor extends HandlerInterceptorAdapter { + + @Override + public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception { + req.setAttribute("preHandle ", "PRE-HANDLE"); + return true; + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) + throws Exception { + super.postHandle(request, response, handler, modelAndView); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) + throws Exception { + super.afterCompletion(request, response, handler, ex); + } + + @Override + public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + super.afterConcurrentHandlingStarted(request, response, handler); + } +} diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/processor/InterceptorProcessor.java b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/processor/InterceptorProcessor.java new file mode 100644 index 00000000..14da9497 --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/main/java/com/espark/adarsh/interceptor/processor/InterceptorProcessor.java @@ -0,0 +1,65 @@ +package com.espark.adarsh.interceptor.processor; + +import com.espark.adarsh.annotation.EsparkInterceptor; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.InterceptorRegistration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.lang.annotation.Annotation; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@Component +public class InterceptorProcessor implements BeanPostProcessor, WebMvcConfigurer { + private final Map interceptors = new HashMap<>(); + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + this.scanForInterceptorAnnotation(bean, beanName); + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String string) throws BeansException { + return bean; + } + + protected void scanForInterceptorAnnotation(Object bean, String beanName) { + Optional optionalInterceptor = getInterceptorAnnotation(bean.getClass()); + if (optionalInterceptor.isPresent() && bean instanceof HandlerInterceptor) { + interceptors.put((HandlerInterceptor) bean, optionalInterceptor.get()); + } + } + + private Optional getInterceptorAnnotation(Class cls) { + Annotation[] annotations = cls.getAnnotationsByType(EsparkInterceptor.class); + if (this.hasValue(annotations)) { + return Optional.of((EsparkInterceptor) annotations[0]); + } + return Optional.empty(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + interceptors.forEach((HandlerInterceptor key, EsparkInterceptor val) -> { + InterceptorRegistration registration = registry.addInterceptor(key); + if (this.hasValue(val.pathPatterns())) { + registration.addPathPatterns(val.pathPatterns()); + } + + if (this.hasValue(val.excludePathPatterns())) { + registration.excludePathPatterns(val.excludePathPatterns()); + } + }); + } + + private static boolean hasValue(T[] array) { + return array != null && array.length > 0; + } +} diff --git a/APPLICATIONS/springboot-custominterceptor/src/main/resources/application.properties b/APPLICATIONS/springboot-custominterceptor/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-custominterceptor/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-custominterceptor/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-custominterceptor/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-date-convertor/.gitignore b/APPLICATIONS/springboot-date-convertor/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-date-convertor/README.md b/APPLICATIONS/springboot-date-convertor/README.md new file mode 100644 index 00000000..8af46d6e --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/README.md @@ -0,0 +1,8 @@ +# spring boot date formatter + +--- + + http://localhost:8080/date/2023-08-13/format/yyyy-MM-dd + http://localhost:8080/date/31.07.2016/format/dd.MM.yyyy + http://localhost:8080/date/08-13-23/format/MM-dd-YY + diff --git a/APPLICATIONS/springboot-date-convertor/pom.xml b/APPLICATIONS/springboot-date-convertor/pom.xml new file mode 100644 index 00000000..fc6ead3f --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.2 + + + com.espark.adarsh + springboot-date-convertor + 0.0.1-SNAPSHOT + springboot-date-convertor + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/web/DataFormatterController.java b/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/web/DataFormatterController.java new file mode 100644 index 00000000..1cc57691 --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/src/main/java/com/espark/adarsh/web/DataFormatterController.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + + +@RestController +public class DataFormatterController { + + private final String yyyyMMdd = "yyyy-MM-dd"; + private final String ddMMyyyy = "dd.MM.yyyy"; + private final String MMddYY = "MM-dd-YY"; + + + Predicate notNull = dateString -> dateString != null; + Predicate notEmpty = dateString -> !dateString.isEmpty(); + + Predicate yyyyMMddFormatPredicate = dateFormat -> dateFormat.equals(yyyyMMdd); + Predicate ddMMyyyyFormatPredicate = dateFormat -> dateFormat.equals(ddMMyyyy); + Predicate MMddYYFormatPredicate = dateFormat -> dateFormat.equals(MMddYY); + + BiFunction localDateBiFunction=new BiFunction() { + @Override + public LocalDate apply(String dateString, String dateFormat) { + return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat)); + } + }; + + + final Map, BiFunction> conditions = new HashMap<>() { + { + put(yyyyMMddFormatPredicate, localDateBiFunction); + put(ddMMyyyyFormatPredicate, localDateBiFunction); + put(MMddYYFormatPredicate, localDateBiFunction); + } + }; + + + @GetMapping("/date/{dateString}/format/{dateFormat}") + public String getFormattedDate(@PathVariable("dateString") String dateString, + @PathVariable("dateFormat") String dateFormat) { + + if (!(notNull.and(notEmpty).test(dateString))) { + throw new RuntimeException("DateInputException null or empty date input "); + } + + if (!(notNull.and(notEmpty).test(dateFormat))) { + throw new RuntimeException("DateInputFormatException null or empty date input format"); + } + + LocalDate localDate = conditions.entrySet() + .stream() + .filter(predicateFunctionEntry -> predicateFunctionEntry.getKey().test(dateFormat)) + .map(predicateFunctionEntry -> predicateFunctionEntry.getValue().apply(dateString,dateFormat)) + .findFirst() + .orElseThrow(() -> new RuntimeException("supplied format is not supported ")); + return "CONVERTED DATE AFTER FORMATTING "+localDate.toString(); + } + + @ExceptionHandler(Exception.class) + public String handleException(Exception e) { + return e.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-date-convertor/src/main/resources/application.properties b/APPLICATIONS/springboot-date-convertor/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-date-convertor/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-date-convertor/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/springboot-date-convertor/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/.gitignore b/APPLICATIONS/springboot-diclaratiive-validation/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-diclaratiive-validation/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-diclaratiive-validation/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/APPLICATIONS/springboot-diclaratiive-validation/README.md b/APPLICATIONS/springboot-diclaratiive-validation/README.md new file mode 100644 index 00000000..3380ac66 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/README.md @@ -0,0 +1,37 @@ + + +``` +@AssertTrue validates that the annotated property value is true. +@Size validates that the annotated property value has a size between the attributes min and max. We can apply it to String, Collection, Map, and array properties. +@Min validates that the annotated property has a value no smaller than the value attribute. +@Max validates that the annotated property has a value no larger than the value attribute. +@Email validates that the annotated property is a valid email address. +Some annotations accept additional attributes, but the message attribute is common to all of them. This is the message that will usually be rendered when the value of the respective property fails validation. + +Here are some additional annotations we can find in the JSR: + +@NotEmpty validates that the property isn’t null or empty. We can apply it to String, Collection, Map or Array values. +@NotBlank can be applied only to text values, and validates that the property isn’t null or whitespace. +@Positive and @PositiveOrZero apply to numeric values, and validate that they’re strictly positive, or positive including 0. +@Negative and @NegativeOrZero apply to numeric values, and validate that they’re strictly negative, or negative including 0. +@Past and @PastOrPresent validate that a date value is in the past, or the past including the present. We can apply it to date types, including those added in Java 8. +@Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present. +``` + +``` +curl --location 'http://localhost:8080/user' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "adarsh", + "email": "adarsh@kumar", + "mobile": "+18877665544", + "age": 50, + "working": true, + "aboutMe": "intelligent", + "dateOfBirth": 13091983, + "preference": [ + "java", + "iot" + ] +}' +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-diclaratiive-validation/pom.xml b/APPLICATIONS/springboot-diclaratiive-validation/pom.xml new file mode 100644 index 00000000..7a2d22ae --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.espark.adarsh + springboot-diclaratiive-validation + 0.0.1-SNAPSHOT + springboot-diclaratiive-validation + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java new file mode 100644 index 00000000..1365e5ac --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootValidationBasicApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootValidationBasicApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/bean/User.java b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/bean/User.java new file mode 100644 index 00000000..c9c87d00 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/bean/User.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.bean; + +import jakarta.validation.constraints.*; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.time.LocalDate; +import java.util.List; + + +@Data +@Setter +@Getter +@ToString +public class User { + + @NotBlank(message = "Invalid Name: Empty name") + @NotNull(message = "Invalid Name: Name is NULL") + @Size(min = 3, max = 30, message = "Invalid Name: Must be of 3 - 30 characters") + String name; + + @Email(message = "Invalid email") + String email; + + @NotBlank(message = "Invalid Phone number: Empty number") + @NotNull(message = "Invalid Phone number: Number is NULL") + @Pattern(regexp = "^\\d{10}$", message = "Invalid phone number") + String mobile; + + @Min(value = 1, message = "Invalid Age: Equals to zero or Less than zero") + @Max(value = 100, message = "Invalid Age: Exceeds 100 years") + Integer age; + + @AssertTrue(message = "Working must be true") + private boolean working; + + @Size(min = 10, max = 200, message + = "About Me must be between 10 and 200 characters") + private String aboutMe; + + + @Past + private LocalDate dateOfBirth; + + private List<@NotBlank String> preference; + + +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java new file mode 100644 index 00000000..0a17fc1b --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.validation.FieldError; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class ApplicationExceptionHandler { + + /*@ExceptionHandler(UserNotFoundException.class) + public ResponseEntity>> handleNotFoundException(UserNotFoundException ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.NOT_FOUND); + }*/ + + + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidationErrors(MethodArgumentNotValidException ex) { + List errors = ex.getBindingResult().getFieldErrors() + .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + private Map> getErrorsMap(List errors) { + Map> errorResponse = new HashMap<>(); + errorResponse.put("errors", errors); + return errorResponse; + } + + @ExceptionHandler(Exception.class) + public final ResponseEntity>> handleGeneralExceptions(Exception ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(RuntimeException.class) + public final ResponseEntity>> handleRuntimeExceptions(RuntimeException ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/service/UserService.java b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/service/UserService.java new file mode 100644 index 00000000..741ef79e --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/service/UserService.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class UserService { + + public String inputUser(User user){ + return user.toString(); + } +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/web/UserController.java b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/web/UserController.java new file mode 100644 index 00000000..0ac48398 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/java/com/espark/adarsh/web/UserController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.User; +import com.espark.adarsh.service.UserService; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + + @Autowired + UserService userService; + + @PostMapping("/user") + public String inputUser(@RequestBody @Valid User user){ + return this.userService.inputUser(user); + } +} diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/main/resources/application.properties b/APPLICATIONS/springboot-diclaratiive-validation/src/main/resources/application.properties new file mode 100644 index 00000000..d53156d5 --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=springboot-validation-basic diff --git a/APPLICATIONS/springboot-diclaratiive-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java b/APPLICATIONS/springboot-diclaratiive-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java new file mode 100644 index 00000000..4df451bb --- /dev/null +++ b/APPLICATIONS/springboot-diclaratiive-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java @@ -0,0 +1,52 @@ +package com.espark.adarsh; + +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Slf4j +@SpringBootTest +class SpringbootValidationBasicApplicationTests { + + + private Validator validator; + + @BeforeEach + void setUp() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + void contextLoads() { + } + + @Test + void test1(){ + User user = new User(); + user.setName("test-name"); + user.setWorking(true); + user.setAboutMe("test-about-me"); + user.setAge(24); + user.setEmail("adarsh@kumar.ut"); + + Set> violations = validator.validate(user); + display(violations); + assertTrue(violations.isEmpty()); + } + + + void display(Set> violations){ + for (ConstraintViolation violation : violations) { + log.error(violation.getMessage()); + } + } +} diff --git a/APPLICATIONS/springboot-docker-maven/.gitignore b/APPLICATIONS/springboot-docker-maven/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/MavenWrapperDownloader.java b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..72308aa4 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/APPLICATIONS/springboot-docker-maven/Dockerfile b/APPLICATIONS/springboot-docker-maven/Dockerfile new file mode 100644 index 00000000..02b0d26a --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/Dockerfile @@ -0,0 +1,22 @@ +# Start with a base image containing Java runtime +FROM openjdk:8-jdk-alpine + +# Add Maintainer Info +LABEL maintainer="adarshkumarsingh83@gmail.com" + +# Add a volume pointing to /tmp +VOLUME /tmp + +# Make port 8080 available to the world outside this container +EXPOSE 8080 + +# The application's jar file +ARG JAR_FILE=target/springboot-docker-maven-0.0.1-SNAPSHOT.jar + +# Add the application's jar to the container +ADD ${JAR_FILE} espark-rest.jar + +# Run the jar file +ENTRYPOINT ["/usr/bin/java","-jar","/espark-rest.jar"] + +CMD ["/usr/bin/java","-jar","/espark-rest.jar"] diff --git a/APPLICATIONS/springboot-docker-maven/document/help.txt b/APPLICATIONS/springboot-docker-maven/document/help.txt new file mode 100644 index 00000000..3bfcceeb --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/document/help.txt @@ -0,0 +1,171 @@ +#To build the application +$ mvn clean package + +#To create a docker tags +$ docker build -t +Example +$ docker build -t espark-springboot-sample . + +#To list the docker tags +$ docker image ls + +#To Run the Docker image +$ docker run -p 5000:8080 +Example +$ docker run -p 5000:8080 espark-springboot-sample + +#To hit the endpoint and get the response +$ curl http://localhost:5000/wish + +#To Run the Docker image in background +$ docker run -d -p 5000:8080 espark-springboot-sample + +#To list the docker containers +$ docker container ls +Example +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +1c3fea2d6064 espark-springboot-sample "java -Djava.securit…" About a minute ago Up About a minute 0.0.0.0:5000->8080/tcp reverent_stallman + +#To kill the container +$ docker stop +Example +$ docker stop 1c3fea2d6064 + + +#To Login in Docker +$ docker login + +Example +Username: adarshkumarsingh83 +Password: ***************** +Login Succeeded + + +#To Tag the Docker image +$ docker tag image username/repository:tag +Example +$ docker tag espark-springboot-sample:latest adarshkumarsingh83/espark:espark-springboot-sample.0.0.1-SNAPSHOT + + +#To Push the Docker image to the docker +$ docker push : +Example +$ docker push adarshkumarsingh83/espark:espark-springboot-sample.0.0.1-SNAPSHOT + + +#To pull the image from docker +$ docker pull adarshkumarsingh83/espark:espark-springboot-sample.0.0.1-SNAPSHOT + +#To Pull the images from the Docker and running +$ docker run -p 5000:8080 / +Example +$ docker run -p 5000:8080 adarshkumarsingh83/espark:espark-springboot-sample.0.0.1-SNAPSHOT + +#To hit the endpoint and get the response +$ curl http://localhost:5000/wish + +#To List the docker locally repository +$ docker images + +#To Delete the docker image form docker locally +$ docker image rm -f + + +##STEP BY STEP DOCKER IMAGE TO PFC +------------------------------------------ +#Sign in to PWS: +$ cf login -a https://api.run.pivotal.io + +#Create a space +cf create-space [-o ORG] [-q SPACE_QUOTA] +$ cf create-space espark-space -o espark-adarsh + +#Target the space of the pcf +$ cf target [-o ORG] -s +$ cf target -o espark-adarsh -s espark-space + +#To push the docker image to the pivitol cloud foundry +$ cf push APP-NAME --docker-image REPO/IMAGE:TAG +$ cf push --docker-image : +Example +$ cf push espark-springboot-docker --docker-image adarshkumarsingh83/espark:espark-springboot-sample.0.0.1-SNAPSHOT –random-route -i 1 -m 512M -t 180 + +#To View the logs +$ cf logs espark-springboot-docker --recent + +#To list the apps in PCF +$ cf apps +----------------------------------------------------------------------------------------------------------------------- +Example +Getting apps in org espark-adarsh / space espark-space as adarshkumarsingh83@gmail.com... +OK +name requested state instances memory disk urls +espark-springboot-docker started 1/1 512M 1G espark-springboot-docker.cfapps.io +----------------------------------------------------------------------------------------------------------------------- + +#To hit the application + $ curl espark-springboot-docker.cfapps.io/wish + welcome to the espark + + +#To start the stop application +$ cf start espark-springboot-docker + +#To stop the running application +$ cf stop espark-springboot-docker + +#To remove the application from pcf +$ cf delete [-r routs] +$ cf delete -r espark-springboot-docker +-------------------------------------------------------- +Example +cf delete -r espark-springboot-docker +Really delete the app espark-springboot-docker?> yes +-------------------------------------------------------- + + +#To delete the space +cf delete-space [-o ORG] +$ cf delete-space espark-space -o espark-adarsh +--------------------------------------------------------- +Example +$ cf delete-space espark-space -o espark-adarsh +Really delete the space espark-space? [yN]: y +Deleting space espark-space in org espark-adarsh as adarshkumarsingh83@gmail.com... +--------------------------------------------------------- + +#logout from PWS +$ cf logout + +************************************************************************************************************************ +============================================================================================ + + com.spotify + dockerfile-maven-plugin + 1.4.0 + + adarshkumarsingh83/espark/espark-springboot-sample + ${project.version} + + target/${project.build.finalName}.jar + + + + + default + install + + build + push + + + + +============================================================================================ +#To build the image +$ mvn package dockerfile:build + +#To push the docker image +$ mvn dockerfile:push + +************************************************************************************************************************ diff --git a/APPLICATIONS/springboot-docker-maven/manifest.yml b/APPLICATIONS/springboot-docker-maven/manifest.yml new file mode 100644 index 00000000..c0598fa4 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/manifest.yml @@ -0,0 +1,7 @@ +applications: +- name: espark-springboot-sample + instances: 1 + disk_quota: 1G + memory: 128M + docker: + image: adarshkumarsingh83/espark \ No newline at end of file diff --git a/APPLICATIONS/springboot-docker-maven/pom.xml b/APPLICATIONS/springboot-docker-maven/pom.xml new file mode 100644 index 00000000..c8ce9663 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + + com.espark.adarsh + springboot-docker-maven + 0.0.1-SNAPSHOT + + springboot-docker-maven + Demo project for Spring Boot + + + 1.8 + espark + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + com.spotify + dockerfile-maven-plugin + 1.4.0 + + adarshkumarsingh83/espark + ${project.version} + + target/${project.build.finalName}.jar + + + + + default + install + + build + push + + + + + + + + diff --git a/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/web/EsparkController.java b/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/web/EsparkController.java new file mode 100644 index 00000000..98124d63 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/src/main/java/com/espark/adarsh/web/EsparkController.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class EsparkController { + + @GetMapping("/wish") + public String getWish() { + return "welcome to the espark"; + } +} diff --git a/APPLICATIONS/springboot-docker-maven/src/main/resources/application.properties b/APPLICATIONS/springboot-docker-maven/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-docker-maven/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-docker-maven/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-docker-maven/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-dropwizard-example/.gitignore b/APPLICATIONS/springboot-dropwizard-example/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-dropwizard-example/README.md b/APPLICATIONS/springboot-dropwizard-example/README.md new file mode 100644 index 00000000..bb9ffa0c --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/README.md @@ -0,0 +1,14 @@ +## springboot dropwizard example + +--- +### To build +* mvn clean package + +### To Test +* mvn spring-boot:run +* seq 1 10 | xargs -n1 -P1 curl -X GET "http://localhost:8080/api/wish/adarsh" + +--- + +### drop wizard end point +* $ curl localhost:8080/metrics \ No newline at end of file diff --git a/APPLICATIONS/springboot-dropwizard-example/pom.xml b/APPLICATIONS/springboot-dropwizard-example/pom.xml new file mode 100644 index 00000000..a62119ca --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.0.0 + + + com.espark.adarsh + springboot-dropwizard-example + 0.0.1-SNAPSHOT + springboot-dropwizard-example + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.ryantenney.metrics + metrics-spring + 3.1.3 + + + com.codahale.metrics + metrics-core + + + org.springframework + spring-core + + + + + + io.dropwizard.metrics + metrics-core + 3.1.2 + + + + io.dropwizard.metrics + metrics-annotation + 3.1.2 + + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java new file mode 100644 index 00000000..ec5b5025 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/Springboot3ExampleApplication.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import com.ryantenney.metrics.spring.config.annotation.EnableMetrics; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableMetrics(proxyTargetClass = true) +public class Springboot3ExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(Springboot3ExampleApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java new file mode 100644 index 00000000..860152cd --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.config; + +import com.codahale.metrics.ConsoleReporter; +import com.codahale.metrics.MetricRegistry; +import com.ryantenney.metrics.spring.config.annotation.EnableMetrics; +import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.TimeUnit; + + +@Configuration +@EnableMetrics +public class ApplicationConfiguration extends MetricsConfigurerAdapter { + + @Override + public void configureReporters(MetricRegistry metricRegistry) { + // registerReporter allows the MetricsConfigurerAdapter to + // shut down the reporter when the Spring context is closed + registerReporter(ConsoleReporter + .forRegistry(metricRegistry) + .build()) + .start(1, TimeUnit.MINUTES); + } + +} diff --git a/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/service/WishService.java new file mode 100644 index 00000000..c5fe53ca --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/service/WishService.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.service; + +import com.codahale.metrics.Meter; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.Timer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@Service +public class WishService { + + private Meter wishMeter; + private Timer wishTimer; + + + @Autowired + public WishService(MetricRegistry metricRegistry) { + this.wishMeter = metricRegistry.meter("wishMeter"); + this.wishTimer = metricRegistry.timer("wishTimer"); + } + + public Map wish(String name) { + wishMeter.mark(); + Timer.Context timer = wishTimer.time(); + HashMap response; + + int hour = LocalDateTime.now().getHour(); + if (hour > 0 && hour < 11) { + response = new HashMap() { + { + { + put("message", " Good morning " + name); + } + } + }; + } else if (hour > 11 && hour < 16) { + response = new HashMap() { + { + { + put("message", " Good After noon " + name); + } + } + }; + } else { + response = new HashMap() { + { + { + put("message", " Good Evening " + name); + } + } + }; + + } + timer.stop(); + return response; + } +} diff --git a/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..e1ed71a7 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.web; + +import com.codahale.metrics.annotation.Timed; +import com.espark.adarsh.service.WishService; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + WishService wishService; + + @Timed + @GetMapping("/wish/{name}") + public ResponseEntity> wish(@PathVariable("name") String name) { + return ResponseEntity.ok(wishService.wish(name)); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-dropwizard-example/src/main/resources/application.properties b/APPLICATIONS/springboot-dropwizard-example/src/main/resources/application.properties new file mode 100644 index 00000000..84febfa8 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/main/resources/application.properties @@ -0,0 +1,4 @@ + +management.endpoints.enabled-by-default=false +management.endpoint.info.enabled=true +spring.metrics.dropwizard.enabled=true \ No newline at end of file diff --git a/APPLICATIONS/springboot-dropwizard-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java b/APPLICATIONS/springboot-dropwizard-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java new file mode 100644 index 00000000..e18b0619 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard-example/src/test/java/com/espark/adarsh/Springboot3ExampleApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Springboot3ExampleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-dropwizard/.gitignore b/APPLICATIONS/springboot-dropwizard/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-dropwizard/README. md b/APPLICATIONS/springboot-dropwizard/README. md new file mode 100644 index 00000000..8747d745 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/README. md @@ -0,0 +1,15 @@ +## springboot dropwizard example + +--- + +### To build +* $ mvn clean package + +### To run +* $ mvn spring-boot:run + +### api end point +* $ curl localhost:8080/message + +### drop wizard end point +* $ curl localhost:8080/metrics diff --git a/APPLICATIONS/springboot-dropwizard/pom.xml b/APPLICATIONS/springboot-dropwizard/pom.xml new file mode 100644 index 00000000..008652b9 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-dropwizard + 0.0.1-SNAPSHOT + springboot-dropwizard + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + + + com.ryantenney.metrics + metrics-spring + 3.1.3 + + + com.codahale.metrics + metrics-core + + + org.springframework + spring-core + + + + + + io.dropwizard.metrics + metrics-core + 3.1.2 + + + + io.dropwizard.metrics + metrics-annotation + 3.1.2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..62ceb11b --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import com.ryantenney.metrics.spring.config.annotation.EnableMetrics; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableMetrics(proxyTargetClass = true) +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java new file mode 100644 index 00000000..83dc62d4 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.config; + +import java.util.concurrent.TimeUnit; + +import org.springframework.context.annotation.Configuration; +import com.codahale.metrics.ConsoleReporter; +import com.codahale.metrics.MetricRegistry; +import com.ryantenney.metrics.spring.config.annotation.EnableMetrics; +import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter; + + +@Configuration +@EnableMetrics +public class ApplicationConfiguration extends MetricsConfigurerAdapter { + + @Override + public void configureReporters(MetricRegistry metricRegistry) { + // registerReporter allows the MetricsConfigurerAdapter to + // shut down the reporter when the Spring context is closed + registerReporter(ConsoleReporter + .forRegistry(metricRegistry) + .build()) + .start(1, TimeUnit.MINUTES); + } + +} diff --git a/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..76c0648c --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.web; + +import com.codahale.metrics.annotation.Timed; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @Timed + @GetMapping("/message") + public String getMessage() { + return "welcome from espark"; + } +} diff --git a/APPLICATIONS/springboot-dropwizard/src/main/resources/application.properties b/APPLICATIONS/springboot-dropwizard/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-dropwizard/src/test/java/com/espark/adarsh/SpringbootDropwizardApplicationTests.java b/APPLICATIONS/springboot-dropwizard/src/test/java/com/espark/adarsh/SpringbootDropwizardApplicationTests.java new file mode 100644 index 00000000..1a0ba1ab --- /dev/null +++ b/APPLICATIONS/springboot-dropwizard/src/test/java/com/espark/adarsh/SpringbootDropwizardApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootDropwizardApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/.gitignore b/APPLICATIONS/springboot-dynamic-payload-response/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-dynamic-payload-response/README.md b/APPLICATIONS/springboot-dynamic-payload-response/README.md new file mode 100644 index 00000000..8af5cd52 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/README.md @@ -0,0 +1,47 @@ +# springboot-dynamic-payload-response + +--- + +## to build +* mvn clean packgqe + +## to run +* mvn spring-boot:run + + +## To access the api url +* api without dynamic payload + * http://localhost:8080/api/response +``` + { + "employeeBean": { + "empId": "01", + "firstName": "firstName", + "lastName": "lastName" + }, + "deptBean": { + "deptId": null, + "deptName": null + }, + "addressBean": { + "addressId": null, + "street": null, + "city": null + } + } +``` +* api with dynamic payload + * http://localhost:8080/api/custom/response +``` +{ +"employeeBean": { + "empId": "01", + "firstName": "firstName", + "lastName": "lastName" +}, +"deptBean": {}, +"addressBean": {} +} +``` + + diff --git a/APPLICATIONS/springboot-dynamic-payload-response/pom.xml b/APPLICATIONS/springboot-dynamic-payload-response/pom.xml new file mode 100644 index 00000000..d130c7ef --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.0 + + + com.espark.adarsh + springboot-dynamic-payload-response + 0.0.1-SNAPSHOT + springboot-dynamic-payload-response + Demo project for Spring Boot + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/SpringbootCustomResponseApplication.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/SpringbootCustomResponseApplication.java new file mode 100644 index 00000000..e4e99373 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/SpringbootCustomResponseApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootCustomResponseApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootCustomResponseApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/AddressBean.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/AddressBean.java new file mode 100644 index 00000000..99101ab3 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/AddressBean.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.bean; + +public class AddressBean { + + private String addressId; + + private String street; + + private String city; + + + public String getAddressId() { + return addressId; + } + + public void setAddressId(String addressId) { + this.addressId = addressId; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/CustomResponseBean.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/CustomResponseBean.java new file mode 100644 index 00000000..1fccae3f --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/CustomResponseBean.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.bean; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CustomResponseBean{ + + @JsonInclude(JsonInclude.Include.NON_NULL) + EmployeeBean employeeBean; + + @JsonInclude(JsonInclude.Include.NON_NULL) + DeptBean deptBean; + + @JsonInclude(JsonInclude.Include.NON_NULL) + AddressBean addressBean; + +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/DeptBean.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/DeptBean.java new file mode 100644 index 00000000..12daa92e --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/DeptBean.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.bean; + +import lombok.Data; + +@Data +public class DeptBean { + + private String deptId; + + private String deptName; + + public String getDeptId() { + return deptId; + } + + public void setDeptId(String deptId) { + this.deptId = deptId; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..12ff6c87 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.bean; + +import lombok.Data; + +public class EmployeeBean { + + protected String empId; + protected String firstName; + protected String lastName; + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/ResponseBean.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/ResponseBean.java new file mode 100644 index 00000000..23daab84 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/bean/ResponseBean.java @@ -0,0 +1,38 @@ +package com.espark.adarsh.bean; + +import lombok.Data; + +@Data +public class ResponseBean { + + EmployeeBean employeeBean; + + DeptBean deptBean; + + + AddressBean addressBean; + + public EmployeeBean getEmployeeBean() { + return employeeBean; + } + + public void setEmployeeBean(EmployeeBean employeeBean) { + this.employeeBean = employeeBean; + } + + public DeptBean getDeptBean() { + return deptBean; + } + + public void setDeptBean(DeptBean deptBean) { + this.deptBean = deptBean; + } + + public AddressBean getAddressBean() { + return addressBean; + } + + public void setAddressBean(AddressBean addressBean) { + this.addressBean = addressBean; + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/service/ApiResponseService.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/service/ApiResponseService.java new file mode 100644 index 00000000..5acf0f28 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/service/ApiResponseService.java @@ -0,0 +1,78 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.*; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.springframework.stereotype.Service; + +import java.util.Random; + +@Service +public class ApiResponseService { + + + ObjectMapper objectMapper = new ObjectMapper(); + + { + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + } + + public ResponseBean getApiResponse() { + int number = new Random().nextInt(4 - 1) + 1; + return getApiResponse(number); + } + + public JsonNode getApiCustomResponse() throws JsonProcessingException { + int number = new Random().nextInt(4 - 1) + 1; + ResponseBean responseBean = getApiResponse(number); + String input = objectMapper.writeValueAsString(responseBean); + System.out.println(input); + JsonNode jsonNode = objectMapper.readTree(input); + return jsonNode; + } + + public ResponseBean getApiResponse(int number) { + ResponseBean responseBean = new ResponseBean(); + if (number > 2) { + EmployeeBean employeeBean = new EmployeeBean(); + employeeBean.setEmpId("01"); + employeeBean.setFirstName("firstName"); + employeeBean.setLastName("lastName"); + responseBean.setEmployeeBean(employeeBean); + DeptBean deptBean = new DeptBean(); + deptBean.setDeptId("it"); + deptBean.setDeptName("it dept"); + responseBean.setDeptBean(deptBean); + AddressBean addressBean = new AddressBean(); + addressBean.setAddressId("00"); + addressBean.setStreet("my street"); + addressBean.setCity("myciti"); + responseBean.setAddressBean(addressBean); + } else if (number > 1) { + EmployeeBean employeeBean = new EmployeeBean(); + employeeBean.setEmpId("01"); + employeeBean.setFirstName("firstName"); + employeeBean.setLastName("lastName"); + responseBean.setEmployeeBean(employeeBean); + DeptBean deptBean = new DeptBean(); + deptBean.setDeptId("it"); + deptBean.setDeptName("it dept"); + responseBean.setDeptBean(deptBean); + responseBean.setAddressBean(new AddressBean()); + } else { + EmployeeBean employeeBean = new EmployeeBean(); + employeeBean.setEmpId("01"); + employeeBean.setFirstName("firstName"); + employeeBean.setLastName("lastName"); + responseBean.setEmployeeBean(employeeBean); + responseBean.setDeptBean(new DeptBean()); + responseBean.setAddressBean(new AddressBean()); + } + return responseBean; + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..40702b5b --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.CustomResponseBean; +import com.espark.adarsh.bean.ResponseBean; +import com.espark.adarsh.service.ApiResponseService; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @Autowired + ApiResponseService apiResponseService; + + @GetMapping("/api/response") + ResponseBean getApiResponse(){ + return this.apiResponseService.getApiResponse(); + } + + @GetMapping("/api/custom/response") + JsonNode getApiCustomResponse() throws JsonProcessingException { + return this.apiResponseService.getApiCustomResponse(); + } +} diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/main/resources/application.properties b/APPLICATIONS/springboot-dynamic-payload-response/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-dynamic-payload-response/src/test/java/com/espark/adarsh/SpringbootCustomResponseApplicationTests.java b/APPLICATIONS/springboot-dynamic-payload-response/src/test/java/com/espark/adarsh/SpringbootCustomResponseApplicationTests.java new file mode 100644 index 00000000..5e334379 --- /dev/null +++ b/APPLICATIONS/springboot-dynamic-payload-response/src/test/java/com/espark/adarsh/SpringbootCustomResponseApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootCustomResponseApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-elasticsearch/.gitignore b/APPLICATIONS/springboot-elasticsearch/.gitignore new file mode 100644 index 00000000..e4e0bd7f --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/.gitignore @@ -0,0 +1,33 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-elasticsearch/Dockerfile b/APPLICATIONS/springboot-elasticsearch/Dockerfile new file mode 100644 index 00000000..83bd1d5f --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8 +MAINTAINER adarsh.kumar@gmail.com +COPY target/springboot-elasticsearch.jar springboot-elasticsearch.jar +ENTRYPOINT ["java","-jar","springboot-elasticsearch.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-elasticsearch/README.md b/APPLICATIONS/springboot-elasticsearch/README.md new file mode 100644 index 00000000..1425f7fc --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/README.md @@ -0,0 +1,28 @@ +# SPRING BOOT ELASTIC SEARCH +> Description: +> spring boot elastic search example +> where data indexed to the elastic search using +> spring data repository and then kibina is used to view the indexed data +> + +### To start the elastic docker +* docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" --name elasticsearch docker.elastic.co/elasticsearch/elasticsearch:7.8.0 + +### To start the kibana for the elastic search +* docker run --link elasticsearch -p 5601:5601 docker.elastic.co/kibana/kibana:7.8.0 + +### To compile the application +* mvn clean package -DskipTests + +### To execute the application +* $ mvn spring-boot:run +* $ java -jar target/springboot-elasticsearch.jar + +### To execute application via docker image +* $ docker build -f Dockerfile -t springboot-elasticsearch . +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 8080:8080 springboot-elasticsearch + +### To test the services +* curl http://localhost:8080/api/employee +* curl http://localhost:8080/api/employee/100 + diff --git a/APPLICATIONS/springboot-elasticsearch/kubernates/app.yml b/APPLICATIONS/springboot-elasticsearch/kubernates/app.yml new file mode 100644 index 00000000..837e74b5 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/kubernates/app.yml @@ -0,0 +1,49 @@ +kind: Service +apiVersion: v1 +metadata: + name: springboot-elasticsearch +spec: + selector: + app: springboot-elasticsearch + ports: + - name: 8080-8080 + port: 8080 + protocol: TCP + targetPort: 8080 + type: LoadBalancer +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: springboot-elasticsearch +spec: + selector: + matchLabels: + app: springboot-elasticsearch + replicas: 1 + template: + metadata: + labels: + app: springboot-elasticsearch + spec: + containers: + - name: springboot-elasticsearch + image: "adarshkumarsingh83/springboot-elasticsearch" + imagePullPolicy: Always + ports: + - containerPort: 8080 + env: # Setting environmental Variables + - name: SPRING_PROFILES_ACTIVE + value: kubernetes + - name: ELASTIC_NODES + value: elasticsearch:9300 + - name: ELASTIC_NAME + value: elasticsearch + - name: ELASTIC_INDEX + value: epsark-index + volumeMounts: + - name: springboot-elasticsearch + mountPath: /var/logs + volumes: + - name: springboot-elasticsearch + emptyDir: {} \ No newline at end of file diff --git a/APPLICATIONS/springboot-elasticsearch/kubernates/elasticsearch.yml b/APPLICATIONS/springboot-elasticsearch/kubernates/elasticsearch.yml new file mode 100644 index 00000000..a891fd7d --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/kubernates/elasticsearch.yml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: elasticsearch + namespace: default + labels: + k8s-app: elasticsearch +spec: + ports: + - port: 9200 + protocol: TCP + targetPort: db + selector: + k8s-app: elasticsearch + type: LoadBalancer + +--- + +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: elasticsearch + labels: + k8s-app: elasticsearch +spec: + serviceName: elasticsearch + replicas: 1 + updateStrategy: + type: RollingUpdate + selector: + matchLabels: + k8s-app: elasticsearch + template: + metadata: + labels: + k8s-app: elasticsearch + spec: + serviceAccountName: elasticsearch + containers: + - image: elasticsearch:6.8.4 + name: elasticsearch + ports: + - containerPort: 9200 + name: db + protocol: TCP + - containerPort: 9300 + name: transport + protocol: TCP + volumeMounts: + - name: elasticsearch + mountPath: /data + volumes: + - name: elasticsearch + emptyDir: {} \ No newline at end of file diff --git a/APPLICATIONS/springboot-elasticsearch/kubernates/kibana.yml b/APPLICATIONS/springboot-elasticsearch/kubernates/kibana.yml new file mode 100644 index 00000000..5ec62874 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/kubernates/kibana.yml @@ -0,0 +1,47 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: kibana + namespace: default + labels: + k8s-app: kibana +spec: + replicas: 1 + selector: + matchLabels: + k8s-app: kibana + template: + metadata: + labels: + k8s-app: kibana + spec: + containers: + - name: kibana + image: docker.elastic.co/kibana/kibana-oss:6.8.4 + env: + - name: ELASTICSEARCH_URL + value: http://elasticsearch:9200 + ports: + - containerPort: 5601 + name: ui + protocol: TCP + type: LoadBalancer +--- + +apiVersion: v1 +kind: Service +metadata: + name: kibana + namespace: default + labels: + k8s-app: kibana + kubernetes.io/name: "Kibana" +spec: + type: NodePort + ports: + - port: 5601 + protocol: TCP + targetPort: ui + nodePort: 32010 + selector: + k8s-app: kibana \ No newline at end of file diff --git a/APPLICATIONS/springboot-elasticsearch/pom.xml b/APPLICATIONS/springboot-elasticsearch/pom.xml new file mode 100644 index 00000000..be2f38cb --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.espark.adarsh + springboot-elasticsearch + 0.0.1-SNAPSHOT + springboot-elasticsearch + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-elasticsearch + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/ElasticsearchApplication.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/ElasticsearchApplication.java new file mode 100644 index 00000000..bfa9bebe --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/ElasticsearchApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElasticsearchApplication { + + public static void main(String[] args) { + SpringApplication.run(ElasticsearchApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..528163df --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.entity; + +import lombok.Data; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; + +@Data +@Document(indexName = "epsark-index", createIndex = true) +public class Employee { + + @Id + private Integer id; + private String name; +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..6d75250a --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.repository; + + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends ElasticsearchRepository { +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..ff303dc0 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,56 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import lombok.extern.slf4j.Slf4j; +import org.elasticsearch.ResourceNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +@Slf4j +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + + public Employee saveEmployees(Employee employee) { + log.info("label=EmployeeService saveEmployees()"); + Employee employees = this.employeeRepository.save(employee); + return employees; + } + + public List getEmployees() { + log.info("label=EmployeeService getEmployees()"); + List employees = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employees.add(employee)); + return employees; + } + + public Employee getEmployee(Integer id) { + log.info("label=EmployeeService getEmployee()"); + Optional employeeOptional = this.employeeRepository.findById(id); + if (employeeOptional.isPresent()) { + return employeeOptional.get(); + } else { + return null; + } + } + + public Employee deleteEmployee(Integer id) { + log.info("label=EmployeeService deleteEmployee()"); + Optional employeeOptional = this.employeeRepository.findById(id); + if (employeeOptional.isPresent()) { + Employee employee = employeeOptional.get(); + this.employeeRepository.delete(employee); + return employee; + } else { + throw new ResourceNotFoundException("Employee not found with id " + id); + } + } +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/util/DataLoader.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/util/DataLoader.java new file mode 100644 index 00000000..ab31902f --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/util/DataLoader.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component +public class DataLoader { + + @Autowired + EmployeeRepository employeeRepository; + + @PostConstruct + public void init() { + Employee adarsh = new Employee(); + adarsh.setId(100); + adarsh.setName("adarsh kumar"); + employeeRepository.save(adarsh); + + + Employee radha = new Employee(); + radha.setId(200); + radha.setName("radha singh"); + employeeRepository.save(radha); + } +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..a837cdc5 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +@Slf4j +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping(value = "/employee") + public List getEmployees() { + log.info("label=EmployeeController getEmployees()"); + return this.employeeService.getEmployees(); + } + + @PostMapping(value = "/employee") + public Employee saveEmployees(@RequestBody Employee employee) { + log.info("label=EmployeeController saveEmployees()"); + return this.employeeService.saveEmployees(employee); + } + + @GetMapping(value = "/employee/{id}") + public Employee getEmployee(@PathVariable("id") Integer id) { + log.info("label=EmployeeController getEmployee()"); + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employee/{id}") + public Employee deleteEmployee(@PathVariable("id") Integer id) { + log.info("label=EmployeeController deleteEmployee()"); + return this.employeeService.deleteEmployee(id); + } + +} diff --git a/APPLICATIONS/springboot-elasticsearch/src/main/resources/application.yaml b/APPLICATIONS/springboot-elasticsearch/src/main/resources/application.yaml new file mode 100644 index 00000000..abba5db8 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/main/resources/application.yaml @@ -0,0 +1,54 @@ +server: + port: 8080 + +logging: + level: + root: DEBUG + +spring: + application: + name: springboot-elasticsearch + profiles: + - defualt + data: + elasticsearch: + repositories: + enabled: true + cluster-nodes: 'localhost:9300' + cluster-name: 'elasticsearch' + + +elasticsearch: + index: + name: epsark-index + user: + type: user + +--- + +server: + port: 8080 + +logging: + level: + root: DEBUG + +spring: + application: + name: springboot-elasticsearch + profiles: + - docker + - kubernetes + data: + elasticsearch: + repositories: + enabled: true + cluster-nodes: ${ELASTIC_NODES:'localhost:9300'} + cluster-name: ${ELASTIC_NAME:'elasticsearch'} + + +elasticsearch: + index: + name: ${ELASTIC_INDEX:'epsark-index'} + user: + type: user \ No newline at end of file diff --git a/APPLICATIONS/springboot-elasticsearch/src/test/java/com/espark/adarsh/ElasticsearchApplicationTests.java b/APPLICATIONS/springboot-elasticsearch/src/test/java/com/espark/adarsh/ElasticsearchApplicationTests.java new file mode 100644 index 00000000..c837a0e0 --- /dev/null +++ b/APPLICATIONS/springboot-elasticsearch/src/test/java/com/espark/adarsh/ElasticsearchApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ElasticsearchApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/.gitignore b/APPLICATIONS/springboot-embedded-hazelcast-cache/.gitignore new file mode 100644 index 00000000..e4e0bd7f --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/.gitignore @@ -0,0 +1,33 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/README.md b/APPLICATIONS/springboot-embedded-hazelcast-cache/README.md new file mode 100644 index 00000000..1d52f1e5 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/README.md @@ -0,0 +1,42 @@ +# SPRING BOOT EMBEDDED HAZELCAST CACHE +> Description: \ +> springboot rest api interannly using hazelcast as the cache \ +> spring cache manager is use for performing the curd operation on the cache + + +---- + +### To build the code +* $ mvn clean package + +### To execute application +* $ java -jar -Dserver.port=9090 target/springboot-embedded-hazelcast-cache.jar +* $ java -jar -Dserver.port=9091 target/springboot-embedded-hazelcast-cache.jar +* $ java -jar -Dserver.port=9092 target/springboot-embedded-hazelcast-cache.jar + +### To Test the api on rep cache +* $ curl -d '{"id":"100","name":"adarsh kumar","email":"adarsh@kumar"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-rep-cache +* $ curl -d '{"id":"101","name":"amit kumar","email":"amit@kumar"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-rep-cache +* $ curl -d '{"id":"200","name":"radha singh","email":"radha@singh"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-rep-cache +* $ curl -X GET http://localhost:9090/v1/api/person/espark-rep-cache/100 +* $ curl -X GET http://localhost:9090/v1/api/person/espark-rep-cache/200 + +### To Test the api on normal cache +* $ curl -d '{"id":"100","name":"adarsh kumar","email":"adarsh@kumar"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-cache +* $ curl -d '{"id":"101","name":"amit kumar","email":"amit@kumar"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-cache +* $ curl -d '{"id":"200","name":"radha singh","email":"radha@singh"}' -H 'Content-Type: application/json' -X POST http://localhost:9090/v1/api/person/espark-cache +* $ curl -X GET http://localhost:9090/v1/api/person/espark-cache/100 +* $ curl -X GET http://localhost:9090/v1/api/person/espark-cache/101 +* $ curl -X GET http://localhost:9090/v1/api/person/espark-cache/200 + + + +### Download management-center:3.12.8 from the official site and execute it +* hazelcast-management-center-3.12.8$ sh start.sh + +### TO DELETE ALL THE CONTAINERS WITH VOLUMES +* $ docker rm -vf $(docker ps -a -q) +### TO DELETE ALL THE IMAGES +* $ docker rmi -f $(docker images -a -q) + + diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/pom.xml b/APPLICATIONS/springboot-embedded-hazelcast-cache/pom.xml new file mode 100644 index 00000000..0ab93b66 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.2.RELEASE + + + com.espark.adarsh + springboot-embedded-hazelcast-cache + 0.0.1-SNAPSHOT + springboot-embedded-hazelcast-cache + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-cache + + + + com.hazelcast + hazelcast + + + com.hazelcast + hazelcast-spring + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/EmbeddedHazelcastCacheApplication.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/EmbeddedHazelcastCacheApplication.java new file mode 100644 index 00000000..9be835d9 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/EmbeddedHazelcastCacheApplication.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@SpringBootApplication +public class EmbeddedHazelcastCacheApplication { + + public static void main(String[] args) { + SpringApplication.run(EmbeddedHazelcastCacheApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Person.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Person.java new file mode 100644 index 00000000..00637929 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Person.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.bean; + +import com.hazelcast.nio.ObjectDataInput; +import com.hazelcast.nio.ObjectDataOutput; +import com.hazelcast.nio.serialization.DataSerializable; +import lombok.Data; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +@Data +public class Person implements DataSerializable { + + Long id; + String name; + String email; + + @Override + public void readData(ObjectDataInput in) + throws IOException { + this.id = in.readLong(); + this.email = in.readUTF(); + this.name = in.readUTF(); + } + + @Override + public void writeData(ObjectDataOutput out) + throws IOException { + out.writeLong(id); + out.writeUTF(email); + out.writeUTF(name); + } +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/AppConfigProp.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/AppConfigProp.java new file mode 100644 index 00000000..a94f51a0 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/AppConfigProp.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties("spring.hazelcast") +public class AppConfigProp { + + String cacheName; + + String repCacheName; + + String instanceName; + + String managementUrl; + + String userName; + + String userPwd; + + String publicAddress; + +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/HazelcastConfiguration.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/HazelcastConfiguration.java new file mode 100644 index 00000000..0d901a5c --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/config/HazelcastConfiguration.java @@ -0,0 +1,69 @@ +package com.espark.adarsh.config; + +import com.hazelcast.config.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class HazelcastConfiguration { + + @Autowired + AppConfigProp appConfigProp; + + @Bean + public Config hazelCastConfig() { + Config config = new Config() + .setInstanceName(appConfigProp.getInstanceName()) + .addMapConfig( + new MapConfig() + .setName(appConfigProp.getCacheName()) + .setMaxSizeConfig(new MaxSizeConfig(200, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE)) + .setEvictionPolicy(EvictionPolicy.LRU) + .setTimeToLiveSeconds(20)); + + config.getGroupConfig().setName(appConfigProp.getUserName()); + config.getGroupConfig().setPassword(appConfigProp.getUserPwd()); + config.getManagementCenterConfig().setEnabled(true); + config.getManagementCenterConfig().setUrl(appConfigProp.getManagementUrl()); + + ReplicatedMapConfig replicatedMapConfig = new ReplicatedMapConfig(); + replicatedMapConfig.setName(appConfigProp.getRepCacheName()); + replicatedMapConfig.setAsyncFillup(true); + config.addReplicatedMapConfig(replicatedMapConfig); + + config.setProperty("hazelcast.local.publicAddress", appConfigProp.getPublicAddress()); + return config; + } + + /* + @Bean + // hazelcast 4.x configuration + public Config hazelCastConfig() { + MapConfig mapConfig = new MapConfig(); + mapConfig.setName(appConfigProp.getCacheName()); + + Config config = new Config() + .setInstanceName(appConfigProp.getInstanceName()) + .addMapConfig( + new MapConfig() + .setName(appConfigProp.getCacheName()) + .setTimeToLiveSeconds(20)); + + + ManagementCenterConfig managementCenterConfig = config.getManagementCenterConfig(); + Set set = new HashSet<>(); + set.add(appConfigProp.getManagementUrl()); + managementCenterConfig.setTrustedInterfaces(set); + config.setManagementCenterConfig(managementCenterConfig); + + ReplicatedMapConfig replicatedMapConfig = new ReplicatedMapConfig(); + replicatedMapConfig.setName(appConfigProp.getRepCacheName()); + replicatedMapConfig.setAsyncFillup(true); + config.addReplicatedMapConfig(replicatedMapConfig); + //config.setProperty("hazelcast.local.publicAddress", appConfigProp.getPublicAddress()); + return config; + }*/ + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java new file mode 100644 index 00000000..300a3b42 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java @@ -0,0 +1,62 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Person; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Slf4j +@Service +public class CacheService { + + @Autowired + private CacheManager cacheManager; + + public boolean save(String cacheName, Person person) { + Cache ch = this.cacheManager.getCache(cacheName); + if (ch != null) { + ch.put(person.getId(), person); + return true; + } + return false; + } + + public boolean update(String cacheName, Person person) { + Cache ch = this.cacheManager.getCache(cacheName); + if (ch != null) { + ch.putIfAbsent(person.getId(), person); + return true; + } + return false; + } + + public Object get(String cacheName, Long personId) { + Cache ch = this.cacheManager.getCache(cacheName); + if (ch != null) { + return ch.get(personId).get(); + } + return null; + } + + public boolean delete(String cacheName, Long personId) { + Cache ch = this.cacheManager.getCache(cacheName); + if (ch != null) { + return ch.evictIfPresent(personId); + } + return false; + } + + public boolean clearCache(String cacheName) { + Cache ch = this.cacheManager.getCache(cacheName); + if (ch != null) { + ch.clear(); + return true; + } + return false; + } +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/web/PersonController.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/web/PersonController.java new file mode 100644 index 00000000..d0358714 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/java/com/espark/adarsh/web/PersonController.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.Person; +import com.espark.adarsh.service.CacheService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@Slf4j +@RestController +@RequestMapping("/v1/api") +public class PersonController { + + @Autowired + CacheService cacheService; + + @PostMapping("/person/{cacheName}") + public boolean save(@PathVariable("cacheName") String cacheName, @RequestBody Person person) { + return this.cacheService.save(cacheName, person); + } + + @PutMapping("/person/{cacheName}") + public boolean update(@PathVariable("cacheName") String cacheName, @RequestBody Person person) { + return this.cacheService.update(cacheName, person); + } + + @GetMapping("/person/{cacheName}/{personId}") + public Object get(@PathVariable("cacheName") String cacheName, @PathVariable("personId") Long personId) { + return this.cacheService.get(cacheName, personId); + } + + @DeleteMapping("/person/{cacheName}/{personId}/{personId}") + public boolean delete(@PathVariable("cacheName") String cacheName, @PathVariable("personId") Long personId) { + return this.cacheService.delete(cacheName, personId); + } + + @DeleteMapping("/person/{cacheName}") + public boolean clearCache(@PathVariable("cacheName") String cacheName) { + return this.cacheService.clearCache(cacheName); + } +} diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/resources/application.yaml b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/resources/application.yaml new file mode 100644 index 00000000..93184b4f --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/main/resources/application.yaml @@ -0,0 +1,15 @@ + +spring: + application: + name: springboot-embedded-hazelcast-cache + hazelcast: + instanceName: hazelcast-instance + cacheName: espark-cache + repCacheName: espark-rep-cache + managementUrl: http://localhost:8080/hazelcast-mancenter + userName: espark-dev + userPwd: dev-pass + publicAddress: 10.67.6.67:5701 + +server: + port: 0 diff --git a/APPLICATIONS/springboot-embedded-hazelcast-cache/src/test/java/com/espark/adarsh/SpringbootEmbidedHazelcastCacheApplicationTests.java b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/test/java/com/espark/adarsh/SpringbootEmbidedHazelcastCacheApplicationTests.java new file mode 100644 index 00000000..803ec136 --- /dev/null +++ b/APPLICATIONS/springboot-embedded-hazelcast-cache/src/test/java/com/espark/adarsh/SpringbootEmbidedHazelcastCacheApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootEmbidedHazelcastCacheApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-espark-json/.gitignore b/APPLICATIONS/springboot-espark-json/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-espark-json/doc/help.txt b/APPLICATIONS/springboot-espark-json/doc/help.txt new file mode 100644 index 00000000..c1037af0 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/doc/help.txt @@ -0,0 +1,9 @@ + +http://localhost:8080/save + +{ + "data":{ + "id":100, + "type":"user" + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-espark-json/pom.xml b/APPLICATIONS/springboot-espark-json/pom.xml new file mode 100644 index 00000000..eceaba37 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + springboot-espark-json + springboot-espark-jsoh + 0.0.1-SNAPSHOT + jar + + springboot-espark-json + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..203b430a --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/AbstractBean.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/AbstractBean.java new file mode 100644 index 00000000..17e4a940 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/AbstractBean.java @@ -0,0 +1,92 @@ +package com.espark.adarsh.bean; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.Date; + +public abstract class AbstractBean { + + protected Type type; + + private Date createdOn = new Date(); + private String createdBy = "user"; + private Date updatedOn = new Date(); + private String updatedBy = "user"; + + public enum Type { + user(User.class), address(Address.class); + + Class classType; + + Type(Class classType) { + if (!AbstractBean.class.isAssignableFrom(classType)) + throw new RuntimeException("class should extend from AbstractNode"); + this.classType = classType; + } + + public static Type lookupByClassType(Class classType) { + Type type = Arrays.stream(values()).filter(type1 -> type1.classType == classType).findFirst().orElse(null); + log.warn("label=typeNotFound classType='{}'", classType); + return type; + } + + static Logger log = LoggerFactory.getLogger(Type.class); + } + + @JsonCreator + public static AbstractBean create(@JsonProperty("type") Type type) { + try { + Constructor constructor = null; + try { + constructor = type.classType.getConstructor(Type.class); + } catch (Exception e) { + constructor = null; + } + if (constructor != null) { + return constructor.newInstance(); + } else { + return (AbstractBean) type.classType.newInstance(); + } + } catch (IllegalAccessException | InstantiationException | InvocationTargetException rethrow) { + throw new RuntimeException(rethrow); + } + } + + public Date getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Date getUpdatedOn() { + return updatedOn; + } + + public void setUpdatedOn(Date updatedOn) { + this.updatedOn = updatedOn; + } + + public String getUpdatedBy() { + return updatedBy; + } + + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/Address.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/Address.java new file mode 100644 index 00000000..40069d62 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/Address.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.bean; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonPropertyOrder({"id","city","country"}) +public class Address extends AbstractBean { + + private Integer id; + private String city; + private String country; + + + public Address() { + this.type= Type.address; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} + diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkRequestBean.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkRequestBean.java new file mode 100644 index 00000000..4040ba89 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkRequestBean.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public class EsparkRequestBean implements Serializable{ + + private AbstractBean data; + + public AbstractBean getData() { + return data; + } + + public void setData(AbstractBean data) { + this.data = data; + } +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java new file mode 100644 index 00000000..5af6a4c6 --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/EsparkResponseBean.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public class EsparkResponseBean implements Serializable{ + + private AbstractBean data; + private String message; + + public AbstractBean getData() { + return data; + } + + public void setData(AbstractBean data) { + this.data = data; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/User.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/User.java new file mode 100644 index 00000000..7ebe198b --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/bean/User.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.bean; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonPropertyOrder({"id","name","email"}) +public class User extends AbstractBean { + + private Integer id; + private String name; + private String email; + + public User() { + this.type= Type.user; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/controller/UserController.java b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/controller/UserController.java new file mode 100644 index 00000000..c9136bac --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/main/java/com/espark/adarsh/controller/UserController.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.AbstractBean; +import com.espark.adarsh.bean.EsparkRequestBean; +import com.espark.adarsh.bean.EsparkResponseBean; +import org.springframework.web.bind.annotation.*; + +@RestController +public class UserController { + + @RequestMapping(method = RequestMethod.POST,value = "/save") + public @ResponseBody EsparkResponseBean save(@RequestBody EsparkRequestBean esparkRequestBean){ + AbstractBean data=esparkRequestBean.getData(); + EsparkResponseBean esparkResponseBean= new EsparkResponseBean(); + esparkResponseBean.setData(data); + esparkResponseBean.setMessage("Data Saved"); + return esparkResponseBean; + } + +} diff --git a/APPLICATIONS/springboot-espark-json/src/main/resources/application.properties b/APPLICATIONS/springboot-espark-json/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-espark-json/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-espark-json/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-espark-json/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/README.md b/APPLICATIONS/springboot-functional-flux-cloud-stream/README.md new file mode 100644 index 00000000..05180b1e --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/README.md @@ -0,0 +1,40 @@ +# springboot kafka stream producer processor consumer +--- + + +### To Run kafka locally + +* [download kafka](https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz) + +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic + + +## To use default producer for testing +./bin/kafka-console-produer.sh --bootstrap-server localhost:9092 --topic espark-topic + +## To use default consumer for testing +./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic + +``` + + +### To Build Code +* mvn clean package -DskipTests + +### To Run the Code +* mvn spring-boot:run + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/.gitignore b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/README.md b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/README.md new file mode 100644 index 00000000..049fb42c --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/README.md @@ -0,0 +1,40 @@ +# springboot kafka stream consumer +--- + + +### To Run kafka locally + +* [download kafka](https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz) + +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic + + +## To use default producer for testing +./bin/kafka-console-produer.sh --bootstrap-server localhost:9092 --topic espark-topic + +## To use default consumer for testing +./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic + +``` + + +### To Build Code +* mvn clean package -DskipTests + +### To Run the Code +* mvn spring-boot:run + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/pom.xml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/pom.xml new file mode 100644 index 00000000..32d9de75 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + com.espark.adarsh + springboot-streams-consumer-kafka + 0.0.1-SNAPSHOT + springboot-streams-consumer-kafka + Demo project for Spring Boot + + 1.8 + 2021.0.4 + + + + org.springframework.cloud + spring-cloud-stream + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-stream + test + test-binder + test-jar + + + org.springframework.kafka + spring-kafka-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/config/ApplicationConsumer.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/config/ApplicationConsumer.java new file mode 100644 index 00000000..8be47937 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/java/com/espark/adarsh/config/ApplicationConsumer.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.config; + +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import java.util.function.Consumer; + +@Slf4j +@Configuration +public class ApplicationConsumer { + + @Bean + public Consumer> consumer() { + return stringFlux -> stringFlux.subscribe(data -> log.info("Consumer {}", data)); + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/resources/application.yml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/resources/application.yml new file mode 100644 index 00000000..761c158b --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/main/resources/application.yml @@ -0,0 +1,17 @@ +logging: + level: + root: INFO + +spring: + application: + name: spring-streams-consumer-kafka + cloud: + stream: + function: + definition: consumer + bindings: + consumer-in-0: + destination: dataChannelTopicProcessor + kafka: + binder: + brokers: localhost:9092 \ No newline at end of file diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java new file mode 100644 index 00000000..5e3b30fd --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-consumer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootStreamsKafkaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/.gitignore b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/README.md b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/README.md new file mode 100644 index 00000000..b27ad42f --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/README.md @@ -0,0 +1,31 @@ +# springboot kafka stream processor +--- + +### To Run kafka locally + +* [download kafka](https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz) + +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic +``` + + +### To Build Code +* mvn clean package -DskipTests + +### To Run the Code +* mvn spring-boot:run + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/pom.xml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/pom.xml new file mode 100644 index 00000000..da2160cf --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + com.espark.adarsh + springboot-streams-processor-kafka + 0.0.1-SNAPSHOT + springboot-streams-processor-kafka + Demo project for Spring Boot + + 1.8 + 2021.0.4 + + + + org.springframework.cloud + spring-cloud-stream + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-stream + test + test-binder + test-jar + + + org.springframework.kafka + spring-kafka-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/config/ApplicationProcessor.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/config/ApplicationProcessor.java new file mode 100644 index 00000000..5d728e95 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/java/com/espark/adarsh/config/ApplicationProcessor.java @@ -0,0 +1,29 @@ +package com.espark.adarsh.config; + +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.function.Function; + +@Slf4j +@Configuration +public class ApplicationProcessor { + + + @Bean + public Function, Flux> processor() { + return longFlux -> longFlux.map(data -> eval(data)) + .doOnEach((data) -> log.info("Processor {}", data)); + } + + private String eval(Integer value) { + if (value % 2 == 0) { + return "EVEN " + value; + } else { + return "ODD " + value; + } + } +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/resources/application.yml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/resources/application.yml new file mode 100644 index 00000000..b1bb5695 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/main/resources/application.yml @@ -0,0 +1,19 @@ +logging: + level: + root: INFO + +spring: + application: + name: spring-streams-processor-kafka + cloud: + stream: + function: + definition: processor + bindings: + processor-in-0: + destination: dataChannelTopic + processor-out-0: + destination: dataChannelTopicProcessor + kafka: + binder: + brokers: localhost:9092 \ No newline at end of file diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java new file mode 100644 index 00000000..5e3b30fd --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-processor-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootStreamsKafkaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/.gitignore b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/README.md b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/README.md new file mode 100644 index 00000000..3b7e2544 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/README.md @@ -0,0 +1,32 @@ +# springboot kafka stream produer +--- + + +### To Run kafka locally + +* [download kafka](https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz) + +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic +``` + + +### To Build Code +* mvn clean package -DskipTests + +### To Run the Code +* mvn spring-boot:run + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/pom.xml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/pom.xml new file mode 100644 index 00000000..c2662b72 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + com.espark.adarsh + springboot-streams-producer-kafka + 0.0.1-SNAPSHOT + springboot-streams-producer-kafka + Demo project for Spring Boot + + 1.8 + 2021.0.4 + + + + org.springframework.cloud + spring-cloud-stream + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + org.springframework.kafka + spring-kafka + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.cloud + spring-cloud-stream + test + test-binder + test-jar + + + org.springframework.kafka + spring-kafka-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/config/ApplicationProducer.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/config/ApplicationProducer.java new file mode 100644 index 00000000..a9848391 --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/java/com/espark/adarsh/config/ApplicationProducer.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.config; + +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.Duration; +import java.util.Random; +import java.util.function.Supplier; + +@Slf4j +@Configuration +public class ApplicationProducer { + + Random random = new Random(); + + @Bean + public Supplier> producer() { + return () -> Flux.interval(Duration.ofSeconds(1)) + .map(value -> random.nextInt(1000 - 1) + 1) + .doOnEach((number) -> log.info("Producer {}", number)); + } +} diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/resources/application.yml b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/resources/application.yml new file mode 100644 index 00000000..81a0d5ed --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/main/resources/application.yml @@ -0,0 +1,18 @@ +logging: + level: + root: INFO + +spring: + application: + name: spring-streams-producer-kafka + cloud: + stream: + function: + definition: producer + bindings: + producer-out-0: + destination: dataChannelTopic + kafka: + binder: + brokers: localhost:9092 + auto-create-topics: true \ No newline at end of file diff --git a/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java new file mode 100644 index 00000000..5e3b30fd --- /dev/null +++ b/APPLICATIONS/springboot-functional-flux-cloud-stream/springboot-streams-producer-kafka/src/test/java/com/espark/adarsh/SpringbootStreamsKafkaApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootStreamsKafkaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-gradle-standalone/build.gradle b/APPLICATIONS/springboot-gradle-standalone/build.gradle new file mode 100644 index 00000000..8ac09b5f --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/build.gradle @@ -0,0 +1,37 @@ +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.7.RELEASE") + } +} + + +plugins { + id 'org.springframework.boot' version '1.5.7.RELEASE' +} + +jar { + baseName = 'springboot-gradle-standalone' + version = '0.1.0' +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'org.springframework.boot' + +repositories { + mavenCentral() +} + +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" + +dependencies { + compile("org.springframework.boot:spring-boot-starter") { + exclude module: "spring-boot-starter-tomcat" + } + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/APPLICATIONS/springboot-gradle-standalone/gradle.properties b/APPLICATIONS/springboot-gradle-standalone/gradle.properties new file mode 100644 index 00000000..1816e1f9 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/gradle.properties @@ -0,0 +1,2 @@ +javaVersion=1.8 +springBootVersion=1.5.7.RELEASE diff --git a/APPLICATIONS/springboot-gradle-standalone/gradle/wrapper/gradle-wrapper.properties b/APPLICATIONS/springboot-gradle-standalone/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ed889284 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Oct 12 16:14:03 CDT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-rc-2-all.zip diff --git a/APPLICATIONS/springboot-gradle-standalone/gradlew b/APPLICATIONS/springboot-gradle-standalone/gradlew new file mode 100644 index 00000000..4453ccea --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/APPLICATIONS/springboot-gradle-standalone/gradlew.bat b/APPLICATIONS/springboot-gradle-standalone/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/APPLICATIONS/springboot-gradle-standalone/settings.gradle b/APPLICATIONS/springboot-gradle-standalone/settings.gradle new file mode 100644 index 00000000..805a9aa5 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'springboot-gradle-standalone' + diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..efd26683 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,33 @@ +package com.espark.adarsh; + +import java.util.Arrays; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner commandLineRunner(ApplicationContext ctx) { + return args -> { + + System.out.println("Let's inspect the beans provided by Spring Boot:"); + + String[] beanNames = ctx.getBeanDefinitionNames(); + Arrays.sort(beanNames); + for (String beanName : beanNames) { + System.out.println(beanName); + } + + }; + } + +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..9e410e66 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.bean; + + +import java.io.Serializable; + +public class Employee implements Serializable{ + + private String empId; + private String empName; + private String empEmail; + + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public String getEmpEmail() { + return empEmail; + } + + public void setEmpEmail(String empEmail) { + this.empEmail = empEmail; + } +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java new file mode 100644 index 00000000..cb267688 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.repsotiory; + +import com.espark.adarsh.bean.Employee; + +import java.util.List; + +public interface EmployeeRepository { + + public Employee saveEmployee(Employee employee); + + public Employee updateEmployee(Employee employee); + + public Employee deleteEmployee(String employeeId); + + public Employee getEmployee(String employeeId); + + public List getEmployees(); +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java new file mode 100644 index 00000000..599417ec --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.repsotiory; + +import com.espark.adarsh.bean.Employee; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.*; + +@Repository +public class EmployeeRepositoryImpl implements EmployeeRepository { + + private Map employeeStore = new HashMap<>(); + + @Override + public Employee saveEmployee(Employee employee) { + this.employeeStore.put(employee.getEmpId(), employee); + return employee; + } + + @Override + public Employee updateEmployee(Employee employee) { + this.employeeStore.put(employee.getEmpId(), employee); + return employee; + } + + @Override + public Employee deleteEmployee(String employeeId) { + return this.employeeStore.remove(employeeId); + } + + @Override + public Employee getEmployee(String employeeId) { + return this.employeeStore.get(employeeId); + } + + @Override + public List getEmployees() { + return new ArrayList<>(employeeStore.values()); + } +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..306f7e50 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; + +import java.util.List; + +public interface EmployeeService { + + public Employee saveEmployee(Employee employee); + + public Employee updateEmployee(Employee employee); + + public Employee deleteEmployee(String employeeId); + + public Employee getEmployee(String employeeId); + + public List getEmployees(); + +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java new file mode 100644 index 00000000..186f0558 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.repsotiory.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + private EmployeeRepository employeeRepository; + + @Override + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.saveEmployee(employee); + } + + @Override + public Employee updateEmployee(Employee employee) { + return this.employeeRepository.updateEmployee(employee); + } + + @Override + public Employee deleteEmployee(String employeeId) { + return this.employeeRepository.deleteEmployee(employeeId); + } + + @Override + public Employee getEmployee(String employeeId) { + return this.employeeRepository.getEmployee(employeeId); + } + + @Override + public List getEmployees() { + return this.employeeRepository.getEmployees(); + } +} diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/resources/application.properties b/APPLICATIONS/springboot-gradle-standalone/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/resources/banner.txt b/APPLICATIONS/springboot-gradle-standalone/src/main/resources/banner.txt new file mode 100644 index 00000000..94b0aa55 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/resources/banner.txt @@ -0,0 +1,5 @@ + _____ ____ ____ _ ____ _ __ ____ ____ _ ____ _ _____ + | ____| / ___| | _ \ / \ | _ \ | |/ / / ___| | _ \ / \ | _ \ | | | ____| + | _| \___ \ | |_) | / _ \ | |_) | | ' / | | _ | |_) | / _ \ | | | | | | | _| + | |___ ___) | | __/ / ___ \ | _ < | . \ | |_| | | _ < / ___ \ | |_| | | |___ | |___ + |_____| |____/ |_| /_/ \_\ |_| \_\ |_|\_\ \____| |_| \_\ /_/ \_\ |____/ |_____| |_____| diff --git a/APPLICATIONS/springboot-gradle-standalone/src/main/resources/logback.xml b/APPLICATIONS/springboot-gradle-standalone/src/main/resources/logback.xml new file mode 100644 index 00000000..c8a4f9e6 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-standalone/src/main/resources/logback.xml @@ -0,0 +1,36 @@ + + + + + + + ${DEV_HOME}/application.log + + + %d{yyyy-MM-dd HH:mm:ss} - %msg%n + + + + + + ${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log + + + 10MB + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-gradle-web/build.gradle b/APPLICATIONS/springboot-gradle-web/build.gradle new file mode 100644 index 00000000..67ecbdee --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/build.gradle @@ -0,0 +1,41 @@ +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.7.RELEASE") + } +} + + +plugins { + id 'org.springframework.boot' version '1.5.7.RELEASE' +} + +jar { + baseName = 'springboot-gradle-web' + version = '0.1.0' +} + +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'org.springframework.boot' + +repositories { + mavenCentral() +} + +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web") { + //exclude module: "spring-boot-starter-tomcat" + } + testCompile group: 'junit', name: 'junit', version: '4.12' + // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test + testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.7.RELEASE' + compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.4.0' + compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.4.0' +} diff --git a/APPLICATIONS/springboot-gradle-web/gradle.properties b/APPLICATIONS/springboot-gradle-web/gradle.properties new file mode 100644 index 00000000..1816e1f9 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/gradle.properties @@ -0,0 +1,2 @@ +javaVersion=1.8 +springBootVersion=1.5.7.RELEASE diff --git a/APPLICATIONS/springboot-gradle-web/gradle/wrapper/gradle-wrapper.properties b/APPLICATIONS/springboot-gradle-web/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..f437ad80 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 13 14:20:40 CDT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-rc-2-all.zip diff --git a/APPLICATIONS/springboot-gradle-web/gradlew b/APPLICATIONS/springboot-gradle-web/gradlew new file mode 100644 index 00000000..4453ccea --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save ( ) { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/APPLICATIONS/springboot-gradle-web/gradlew.bat b/APPLICATIONS/springboot-gradle-web/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/APPLICATIONS/springboot-gradle-web/settings.gradle b/APPLICATIONS/springboot-gradle-web/settings.gradle new file mode 100644 index 00000000..dc5f56a8 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'springboot-gradle-web' + diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..efd26683 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,33 @@ +package com.espark.adarsh; + +import java.util.Arrays; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public CommandLineRunner commandLineRunner(ApplicationContext ctx) { + return args -> { + + System.out.println("Let's inspect the beans provided by Spring Boot:"); + + String[] beanNames = ctx.getBeanDefinitionNames(); + Arrays.sort(beanNames); + for (String beanName : beanNames) { + System.out.println(beanName); + } + + }; + } + +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..4802002f --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.bean; + + +import java.io.Serializable; + +public class Employee implements Serializable{ + + private String empId; + private String empName; + private String empEmail; + + + public Employee() { + } + + public Employee(String empId, String empName) { + this.empId = empId; + this.empName = empName; + } + + public String getEmpId() { + return empId; + } + + public void setEmpId(String empId) { + this.empId = empId; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public String getEmpEmail() { + return empEmail; + } + + public void setEmpEmail(String empEmail) { + this.empEmail = empEmail; + } +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java new file mode 100644 index 00000000..a361e068 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +@Configuration +public class ApplicationConfiguration { + + @Value("${base.url}") + private String baseUrl; + + @Bean + public RestTemplate getRestTemplate(){ + return new RestTemplate(); + } + + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).pathMapping(baseUrl) + .select() + .apis(RequestHandlerSelectors.basePackage("com.espark.adarsh")) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + ApiInfo apiInfo = new ApiInfo( + "IRIS DATA INTI Rest Api", + "IRIS Rest Swagger Apis UI.", + "IRIS 1.0", + "http://jcpenney.com", + "admin.jcpenney.com", + "JCPENNEY", + "http://jcpenney/icense"); + return apiInfo; + } +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java new file mode 100644 index 00000000..cb267688 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepository.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.repsotiory; + +import com.espark.adarsh.bean.Employee; + +import java.util.List; + +public interface EmployeeRepository { + + public Employee saveEmployee(Employee employee); + + public Employee updateEmployee(Employee employee); + + public Employee deleteEmployee(String employeeId); + + public Employee getEmployee(String employeeId); + + public List getEmployees(); +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java new file mode 100644 index 00000000..689ed162 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/repsotiory/EmployeeRepositoryImpl.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.repsotiory; + +import com.espark.adarsh.bean.Employee; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.*; + +@Repository +public class EmployeeRepositoryImpl implements EmployeeRepository { + + private Map employeeStore = new HashMap(){ + { + put("100",new Employee("100","adarsh kumar")); + } + }; + + @Override + public Employee saveEmployee(Employee employee) { + this.employeeStore.put(employee.getEmpId(), employee); + return employee; + } + + @Override + public Employee updateEmployee(Employee employee) { + this.employeeStore.put(employee.getEmpId(), employee); + return employee; + } + + @Override + public Employee deleteEmployee(String employeeId) { + return this.employeeStore.remove(employeeId); + } + + @Override + public Employee getEmployee(String employeeId) { + return this.employeeStore.get(employeeId); + } + + @Override + public List getEmployees() { + return new ArrayList<>(employeeStore.values()); + } +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..306f7e50 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; + +import java.util.List; + +public interface EmployeeService { + + public Employee saveEmployee(Employee employee); + + public Employee updateEmployee(Employee employee); + + public Employee deleteEmployee(String employeeId); + + public Employee getEmployee(String employeeId); + + public List getEmployees(); + +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java new file mode 100644 index 00000000..186f0558 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/service/EmployeeServiceImpl.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.repsotiory.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + private EmployeeRepository employeeRepository; + + @Override + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.saveEmployee(employee); + } + + @Override + public Employee updateEmployee(Employee employee) { + return this.employeeRepository.updateEmployee(employee); + } + + @Override + public Employee deleteEmployee(String employeeId) { + return this.employeeRepository.deleteEmployee(employeeId); + } + + @Override + public Employee getEmployee(String employeeId) { + return this.employeeRepository.getEmployee(employeeId); + } + + @Override + public List getEmployees() { + return this.employeeRepository.getEmployees(); + } +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..e36aa202 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RequestMapping("/emp") +@RestController +public class EmployeeController { + + @Autowired + private EmployeeService employeeService; + + @RequestMapping(value = "/save",method = RequestMethod.POST) + public @ResponseBody + Employee saveEmployee(@RequestBody Employee employee){ + return this.employeeService.saveEmployee(employee); + } + + @RequestMapping(value = "/fetch/{id}",method = RequestMethod.GET) + public @ResponseBody Employee getEmployee(@PathVariable("id")String employeeId){ + return this.employeeService.getEmployee(employeeId); + } +} diff --git a/APPLICATIONS/springboot-gradle-web/src/main/resources/application.properties b/APPLICATIONS/springboot-gradle-web/src/main/resources/application.properties new file mode 100644 index 00000000..360f23b9 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/resources/application.properties @@ -0,0 +1 @@ +base.url= \ No newline at end of file diff --git a/APPLICATIONS/springboot-gradle-web/src/main/resources/banner.txt b/APPLICATIONS/springboot-gradle-web/src/main/resources/banner.txt new file mode 100644 index 00000000..94b0aa55 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/resources/banner.txt @@ -0,0 +1,5 @@ + _____ ____ ____ _ ____ _ __ ____ ____ _ ____ _ _____ + | ____| / ___| | _ \ / \ | _ \ | |/ / / ___| | _ \ / \ | _ \ | | | ____| + | _| \___ \ | |_) | / _ \ | |_) | | ' / | | _ | |_) | / _ \ | | | | | | | _| + | |___ ___) | | __/ / ___ \ | _ < | . \ | |_| | | _ < / ___ \ | |_| | | |___ | |___ + |_____| |____/ |_| /_/ \_\ |_| \_\ |_|\_\ \____| |_| \_\ /_/ \_\ |____/ |_____| |_____| diff --git a/APPLICATIONS/springboot-gradle-web/src/main/resources/logback.xml b/APPLICATIONS/springboot-gradle-web/src/main/resources/logback.xml new file mode 100644 index 00000000..c8a4f9e6 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/main/resources/logback.xml @@ -0,0 +1,36 @@ + + + + + + + ${DEV_HOME}/application.log + + + %d{yyyy-MM-dd HH:mm:ss} - %msg%n + + + + + + ${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log + + + 10MB + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-gradle-web/src/test/java/com/espark/adarsh/test/EmployeeTest.java b/APPLICATIONS/springboot-gradle-web/src/test/java/com/espark/adarsh/test/EmployeeTest.java new file mode 100644 index 00000000..a1ea5946 --- /dev/null +++ b/APPLICATIONS/springboot-gradle-web/src/test/java/com/espark/adarsh/test/EmployeeTest.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.test; + + +import com.espark.adarsh.bean.Employee; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; +import java.net.URL; +import org.junit.Before; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.web.client.TestRestTemplate; + + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class EmployeeTest { + + @LocalServerPort + private int port; + + private URL base; + + @Autowired + private TestRestTemplate template; + + @Before + public void setUp() throws Exception { + this.base = new URL("http://localhost:" + port + "/"); + } + + + @Test + public void saveEmployee() throws Exception { + ResponseEntity response = template.postForEntity(base.toString()+"/emp/save", + new Employee("200","radha singh"),Employee.class); + Employee employee = response.getBody(); + assertThat(employee.getEmpId(), equalTo("200")); + } + + @Test + public void getEmployee() throws Exception { + ResponseEntity response = template.getForEntity(base.toString()+"/emp/fetch/100", + Employee.class); + Employee employee = response.getBody(); + assertThat(employee.getEmpId(), equalTo("100")); + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/.gitignore b/APPLICATIONS/springboot-graphql-crud-example/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-graphql-crud-example/README.md b/APPLICATIONS/springboot-graphql-crud-example/README.md new file mode 100644 index 00000000..7fa4642b --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/README.md @@ -0,0 +1,195 @@ +# SPRING BOOT-BASIC-CRUD-EXAMPLE + +--- + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +## graphql scale lib +``` + + + com.graphql-java + graphql-java-extended-scalars + 20.2 + +``` + +## Graphql console +* http://localhost:8080/espark/graphiql?path=/api/espark/graphql + +### single selection query +```` +query{ + getEmployee(id:1){ + id + firstName + lastName + salary + doj + gender + attributes + phone + } +} +```` + +### multi selection query +``` +query{ + getAllEmployee{ + id + firstName + lastName + salary + doj + gender + attributes + phone + } +} +``` + +### saving data +``` +mutation{ + saveEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"singh",career:"it", salary: 3, doj:"1010-01-01", gender:MALE, attributes:"{\"key\":\"value\"}", phone:["1234567890","12345678999"]}) { + id firstName lastName career salary doj gender phone + } +} +``` + + +### updating data +``` +mutation{ + updateEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"kumar singh",career:"it", salary: 3}) { + id firstName lastName career salary + } +} +``` + +### Filter Query +``` +query { + employeesFilter(filter: { salary: { operator: "gt" value: "5" } }) { id firstName lastName salary } +} +``` + +### removing data +``` +mutation{ + removeEmployee(id: 10){ + id + firstName + lastName + career + } +} + +``` + + +--- +# Curl Cmd Operation + +--- + +### AllEmployee +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query{getAllEmployee{ id firstName lastName salary}\n}"}' +``` + +### Get Employee By Id +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{ + "query": "query{getEmployee(id:1){ id firstName lastName salary}\n}" +}' +``` + +### Saving Employee +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\"sonu\",lastName:\"singh\",career:\"it\", salary: 3}) { id firstName lastName career salary}\n}"}' +``` + + +### Updating Employee +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{updateEmployee(employeeBean:{ id:10,firstName:\"sonu\",lastName:\"kumar singh\",career:\"it\", salary: 3}) { id firstName lastName career salary}\n}"}' + +``` + + +### Filter Query +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query {\n employeesFilter(filter: { salary: { operator: \"gt\" value: \"5\" } }) { id firstName lastName salary } \n}"}' +``` + +### Deleting Employee +``` +curl --location 'http://localhost:8080/api/espark/graphql' \ +--header 'Content-Type: application/json' \ +--data '{ + "query": "mutation{removeEmployee(id: 10){ id firstName lastName career}\n}" +}' +``` + + +## SONAR +$ Downloads/sonarqube-10.1.0.73491 2/bin/macosx-universal-64 + +$ sh sonar.sh start +``` +$ sh sonar.sh start +/usr/bin/java +Starting SonarQube... +Started SonarQube. +``` +``` +$ sh sonar.sh stop +/usr/bin/javamvn c +Gracefully stopping SonarQube... +Stopped SonarQube. + +``` +url +http://localhost:9000/ +admin/admin + +create project manually +analyze your project locally -> provide a token -> generate +it will generate a token +run your project from maven -> it will provide a maven cmd like below to run +and build a code for sonar analysis + +$ mvn clean verify sonar:sonar \ +-Dsonar.projectKey=graphql \ +-Dsonar.projectName='graphql' \ +-Dsonar.host.url=http://localhost:9000 \ +-Dsonar.token=sqp_d2802588ba05e9255839f21e5ce9bf8d5c84dc8f + + diff --git a/APPLICATIONS/springboot-graphql-crud-example/pom.xml b/APPLICATIONS/springboot-graphql-crud-example/pom.xml new file mode 100644 index 00000000..ab50c380 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/pom.xml @@ -0,0 +1,146 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.9 + + + com.espark.adarsh + springboot-graphql-crud-example + 0.0.1-SNAPSHOT + springboot-graphql-crud-example + Demo project for Spring Boot + + 1.8 + 11.1.0 + 0.8.3 + jacoco + reuseReports + ${project.basedir}/../target/jacoco.exec + java + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-graphql + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + 1.18.26 + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.graphql + spring-graphql-test + test + + + + com.graphql-java + graphql-java-servlet + 4.7.0 + + + + + + + org.springframework + spring-webflux + 5.3.23 + + + + javax.validation + validation-api + 2.0.1.Final + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 15 + 15 + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + ${maven.test.skip} + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/jacoco-unit.exec + file + true + + *MethodAccess + + + + + jacoco-initialize + + prepare-agent + + test-compile + + + jacoco-site + verify + + report + + + + + + + + diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..cc540d91 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.GraphqlScalarConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import({GraphqlScalarConfiguration.class}) +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..6f92864d --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,125 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.entity.Gender; +import lombok.extern.slf4j.Slf4j; + +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotEmpty; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +@Slf4j +public class EmployeeBean { + + @Digits(fraction = 0, integer = 100, message = "id for employee") + private Long id; + @NotEmpty + private String firstName; + @NotEmpty + private String lastName; + private String career; + + private Long salary; + + private LocalDate doj; + + private Gender gender; + + private List phone; + + private Map attributes; + + public EmployeeBean() { + } + + public EmployeeBean(Long id, String firstName, String lastName, String career, Long salary, LocalDate doj, Gender gender, Map attributes) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + this.doj = doj; + this.gender = gender; + this.attributes = attributes; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + + public LocalDate getDoj() { + return doj; + } + + public void setDoj(LocalDate doj) { + this.doj = doj; + } + + public Gender getGender() { + return gender; + } + + public void setGender(Gender gender) { + this.gender = gender; + } + + + public Map getAttributes() { + return attributes; + } + + public void setAttributes( Map attributes) { + this.attributes = attributes; + } + + public List getPhone() { + return phone; + } + + public void setPhone(List phone) { + this.phone = phone; + } + + public Employee getEmployee() { + return new Employee(this.id, this.firstName, this.lastName, this.career,this.salary,this.doj,this.gender,this.attributes,this.phone); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/config/GraphqlScalarConfiguration.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/config/GraphqlScalarConfiguration.java new file mode 100644 index 00000000..5fe05002 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/config/GraphqlScalarConfiguration.java @@ -0,0 +1,136 @@ +package com.espark.adarsh.config; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import graphql.language.StringValue; +//import graphql.scalars.ExtendedScalars; +import graphql.schema.Coercing; +import graphql.schema.CoercingParseLiteralException; +import graphql.schema.CoercingParseValueException; +import graphql.schema.CoercingSerializeException; +import graphql.schema.GraphQLScalarType; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.execution.RuntimeWiringConfigurer; + +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.Map; + +@Configuration +public class GraphqlScalarConfiguration { + + @Bean + public RuntimeWiringConfigurer runtimeWiringConfigurer() { + return wiringBuilder -> wiringBuilder + .scalar(dateScalar()) + .scalar(jsonScalar()); + //.scalar(ExtendedScalars.Json) + //.scalar(ExtendedScalars.Date); + } + + + public GraphQLScalarType dateScalar() { + return GraphQLScalarType.newScalar() + .name("Date") //graphql type define in the schema file + .description("Java 8 LocalDate as scalar.") + .coercing(new Coercing() { + @Override + public String serialize(final Object dataFetcherResult) { + if (dataFetcherResult instanceof LocalDate) { + return dataFetcherResult.toString(); + } else { + throw new CoercingSerializeException("Expected a LocalDate object."); + } + } + + @Override + public LocalDate parseValue(final Object input) { + try { + if (input instanceof String) { + return LocalDate.parse((String) input); + } else { + throw new CoercingParseValueException("Expected a String"); + } + } catch (DateTimeParseException e) { + throw new CoercingParseValueException(String.format("Not a valid date: '%s'.", input), e + ); + } + } + + @Override + public LocalDate parseLiteral(final Object input) { + if (input instanceof StringValue) { + try { + return LocalDate.parse(((StringValue) input).getValue()); + } catch (DateTimeParseException e) { + throw new CoercingParseLiteralException(e); + } + } else { + throw new CoercingParseLiteralException("Expected a StringValue."); + } + } + }) + .build(); + } + + + public GraphQLScalarType jsonScalar() { + ObjectMapper objectMapper = new ObjectMapper(); + return GraphQLScalarType.newScalar() + .name("JSON") //graphql type define in the schema file + .description("Java MAP as scalar.") + .coercing(new Coercing, String>() { + @Override + public String serialize(final Object dataFetcherResult) { + if (dataFetcherResult instanceof Map) { + try { + return objectMapper.writeValueAsString(dataFetcherResult); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } else { + throw new CoercingSerializeException("Expected a Map object."); + } + } + + @Override + public Map parseValue(final Object input) { + + if (input instanceof StringValue) { + try { + return objectMapper.readValue(input.toString() + , new TypeReference>() { + }); + + + } catch (JsonProcessingException e) { + throw new CoercingParseLiteralException(e); + } + } else { + throw new CoercingParseValueException("Expected a String"); + } + } + + + @Override + public Map parseLiteral(final Object input) { + if (input instanceof StringValue) { + try { + return objectMapper.readValue(((StringValue) input).getValue() + , new TypeReference>() { + }); + } catch (JsonProcessingException e) { + throw new CoercingParseLiteralException(e); + } + } else { + throw new CoercingParseLiteralException("Expected a StringValue."); + } + } + }).build(); + + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..e756e56f --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,140 @@ +package com.espark.adarsh.entity; + +import com.espark.adarsh.entity.convertors.AttributeMapConverter; +import com.espark.adarsh.entity.convertors.PhoneListConverter; + +import javax.persistence.*; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + private Long id; + private String firstName; + private String lastName; + private String career; + + private Long salary; + + @Column(name = "doj", columnDefinition = "DATE") + private LocalDate doj; + + @Enumerated(EnumType.STRING) + private Gender gender; + + @Convert(converter = AttributeMapConverter.class) + private Map attributes; + + + @Convert(converter = PhoneListConverter.class) + private List phone; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career, Long salary) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public Employee(Long id, String firstName, String lastName, String career, Long salary) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public Employee(Long id, String firstName, String lastName, String career, Long salary, LocalDate doj, Gender gender) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + this.doj = doj; + this.gender = gender; + } + + public Employee(Long id, String firstName, String lastName, String career, Long salary, LocalDate doj, Gender gender, Map attributes, List phone) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + this.doj = doj; + this.gender = gender; + this.attributes = attributes; + this.phone = phone; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public LocalDate getDoj() { + return doj; + } + + public void setDoj(LocalDate doj) { + this.doj = doj; + } + + public Gender getGender() { + return gender; + } + + public void setGender(Gender gender) { + this.gender = gender; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } +} + diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Gender.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Gender.java new file mode 100644 index 00000000..ad87f934 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/Gender.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.entity; + +public enum Gender { + MALE, + FEMALE +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/AttributeMapConverter.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/AttributeMapConverter.java new file mode 100644 index 00000000..b2d783f3 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/AttributeMapConverter.java @@ -0,0 +1,42 @@ +package com.espark.adarsh.entity.convertors; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.util.Map; + +@Slf4j +@Converter +public class AttributeMapConverter implements AttributeConverter { + + ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map attribute) { + try { + return objectMapper.writeValueAsString(attribute); + } catch (JsonProcessingException e) { + log.error(e.getMessage()); + } + return null; + } + + @Override + public Map convertToEntityAttribute(String dbData) { + try { + return objectMapper.readValue(dbData.toString() + , new TypeReference>() { + }); + + } catch (JsonProcessingException e) { + log.error(e.getMessage()); + } + return null; + } +} + + diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/PhoneListConverter.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/PhoneListConverter.java new file mode 100644 index 00000000..c848db5d --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/entity/convertors/PhoneListConverter.java @@ -0,0 +1,42 @@ +package com.espark.adarsh.entity.convertors; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; + +import java.util.List; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + + +@Slf4j +@Converter +public class PhoneListConverter implements AttributeConverter, String> { + ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(List phone) { + try { + return objectMapper.writeValueAsString(phone + ); + } catch (JsonProcessingException e) { + log.error(e.getMessage()); + } + return null; + } + + @Override + public List convertToEntityAttribute(String dbData) { + try { + return objectMapper.readValue(dbData + , new TypeReference>() { + }); + + } catch (JsonProcessingException e) { + log.error(e.getMessage()); + } + return null; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java new file mode 100644 index 00000000..44006a1d --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; +import graphql.schema.DataFetchingEnvironment; +import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.List; + +@Component +public class AppDataFetcherExceptionResolverAdapter extends DataFetcherExceptionResolverAdapter { + + @Override + protected List resolveToMultipleErrors(Throwable ex, DataFetchingEnvironment env) { + if(ex!=null){ + if(ex instanceof EmployeeNotFoundException){ + return Arrays.asList((EmployeeNotFoundException)ex); + } + } + return Arrays.asList(GraphqlErrorBuilder.newError().message(ex.getMessage()).errorType(ErrorType.DataFetchingException).build()); + } + + @Override + protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { + if(ex!=null){ + if(ex instanceof EmployeeNotFoundException){ + return (EmployeeNotFoundException)ex; + } + } + return GraphqlErrorBuilder.newError().message(ex.getMessage()).errorType(ErrorType.DataFetchingException).build(); + } +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..c8325d19 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.exception; + + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EmployeeNotFoundException extends RuntimeException implements GraphQLError { + + private Map extensions = new HashMap<>(); + + public EmployeeNotFoundException(String message, Long id) { + super(message); + extensions.put("EmployeeNotFoundException ", id); + } + + @Override + public List getLocations() { + return null; + } + + @Override + public Map getExtensions() { + return extensions; + } + + @Override + public ErrorType getErrorType() { + return ErrorType.DataFetchingException; + } + + @Override + public String toString() { + return "EmployeeNotFoundException "+this.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/GraphQlExceptionsHandler.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/GraphQlExceptionsHandler.java new file mode 100644 index 00000000..1429a43f --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/exception/GraphQlExceptionsHandler.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.exception; + +import graphql.GraphQLError; +import org.springframework.boot.context.properties.bind.BindException; +import org.springframework.graphql.execution.ErrorType; +import org.springframework.web.bind.annotation.ControllerAdvice; + +@ControllerAdvice +public class GraphQlExceptionsHandler { + +/* @GraphQlExceptionHandler + public GraphQLError handle(BindException ex) { + return GraphQLError.newError().errorType(ErrorType.BAD_REQUEST).message("...").build(); + }*/ +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java new file mode 100644 index 00000000..0594c550 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.filter; + +import lombok.Data; + +@Data +public class EmployeeFilter { + + private FilterField id; + private FilterField salary; + private FilterField carrier; +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/FilterField.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/FilterField.java new file mode 100644 index 00000000..36892416 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/filter/FilterField.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.filter; +import lombok.Data; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; + +@Data +public class FilterField { + private String operator; + private String value; + + public Predicate generateCriteria(CriteriaBuilder builder, Path field) { + try { + int v = Integer.parseInt(value); + switch (operator) { + case "lt": return builder.lt(field, v); + case "le": return builder.le(field, v); + case "gt": return builder.gt(field, v); + case "ge": return builder.ge(field, v); + case "eq": return builder.equal(field, v); + } + } catch (NumberFormatException e) { + switch (operator) { + case "endsWith": return builder.like(field, "%" + value); + case "startsWith": return builder.like(field, value + "%"); + case "contains": return builder.like(field, "%" + value + "%"); + case "eq": return builder.equal(field, value); + } + } + + return null; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java new file mode 100644 index 00000000..be382ec9 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.interceptor; + +import org.springframework.graphql.server.WebGraphQlInterceptor; +import org.springframework.graphql.server.WebGraphQlRequest; +import org.springframework.graphql.server.WebGraphQlResponse; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +import java.util.Collections; + +@Component +public class RequestHeaderInterceptor implements WebGraphQlInterceptor { + + @Override + public Mono intercept(WebGraphQlRequest request, Chain chain) { + String value = request.getHeaders().getFirst("espark"); + if (value != null) { + request.configureExecutionInput((executionInput, builder) -> + builder.graphQLContext(Collections.singletonMap("espark", value)).build()); + } + return chain.next(request); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java new file mode 100644 index 00000000..5526a6ae --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.interceptor; + +import org.springframework.graphql.server.WebGraphQlInterceptor; +import org.springframework.graphql.server.WebGraphQlRequest; +import org.springframework.graphql.server.WebGraphQlResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +@Component +public class ResponseHeaderInterceptor implements WebGraphQlInterceptor { + + @Override + public Mono intercept(WebGraphQlRequest request, Chain chain) { + return chain.next(request).doOnNext(response -> { + String value = response.getExecutionInput().getGraphQLContext().get("cookieName"); + ResponseCookie cookie = ResponseCookie.from("cookieName", value).build(); + response.getResponseHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString()); + }); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..ef6764da --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository, + JpaSpecificationExecutor { +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..4e7dce70 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,97 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.filter.FilterField; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.stereotype.Service; +import org.springframework.util.ReflectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.lang.reflect.Field; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + this.employeeRepository.deleteById(id); + return employee; + } + + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } + + + public Employee updatePartialEmployee(@PathVariable("id") Long id, Map employee) { + final Optional employeeOptional = this.employeeRepository.findById(id); + if (employeeOptional.isPresent()) { + employee.forEach((key, value) -> { + Field field = ReflectionUtils.findField(Employee.class, key); + field.setAccessible(true); + ReflectionUtils.setField(field, employeeOptional.get(), value); + }); + return this.employeeRepository.save(employeeOptional.get()); + } + return employeeOptional.orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + } + + + + + public Iterable employeesFilter(EmployeeFilter filter) { + Specification spec = null; + if (filter.getSalary() != null) + spec = bySalary(filter.getSalary()); + if (filter.getId() != null) + spec = (spec == null ? byId(filter.getId()) : spec.and(byId(filter.getId()))); + if (filter.getCarrier() != null) + spec = (spec == null ? byCarrier(filter.getCarrier()) : + spec.and(byCarrier(filter.getCarrier()))); + if (spec != null) + return employeeRepository.findAll(spec); + else + return employeeRepository.findAll(); + } + + private Specification bySalary(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("salary")); + } + + private Specification byId(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("id")); + } + + private Specification byCarrier(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("carrier")); + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeGraphQlController.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeGraphQlController.java new file mode 100644 index 00000000..0636e8ab --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeGraphQlController.java @@ -0,0 +1,63 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.service.EmployeeService; +import graphql.schema.DataFetchingEnvironment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.MutationMapping; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.stereotype.Controller; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + + +import javax.validation.Valid; +import java.util.List; + +@Controller +public class EmployeeGraphQlController { + + @Autowired + EmployeeService employeeService; + + + @QueryMapping + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @QueryMapping + public Employee getEmployee(@Argument Long id, DataFetchingEnvironment env) { + ServletRequestAttributes attributes = + (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + String val = attributes.getRequest().getHeader("name"); + return this.employeeService.getEmployee(id); + } + + @MutationMapping + public Employee removeEmployee(@Argument("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @MutationMapping + public Employee saveEmployee(@Argument @Valid EmployeeBean employeeBean) { + return this.employeeService.saveEmployee(employeeBean.getEmployee()); + } + + @MutationMapping + public Employee updateEmployee(@Argument @Valid EmployeeBean employeeBean) { + return this.employeeService.updateEmployee(employeeBean.getId(), employeeBean.getEmployee()); + } + + + @QueryMapping + public Iterable employeesFilter(@Argument EmployeeFilter filter) { + return this.employeeService.employeesFilter(filter); + } + + + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeRestController.java b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeRestController.java new file mode 100644 index 00000000..47bd6e79 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/java/com/espark/adarsh/web/EmployeeRestController.java @@ -0,0 +1,61 @@ +/* +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.service.EmployeeService; +import graphql.schema.DataFetchingEnvironment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.validation.Valid; +import java.util.List; + +@RestController +public class EmployeeRestController { + + @Autowired + EmployeeService employeeService; + + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id, DataFetchingEnvironment env) { + ServletRequestAttributes attributes = + (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + String val = attributes.getRequest().getHeader("name"); + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employee/{id") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody @Valid EmployeeBean employeeBean) { + return this.employeeService.saveEmployee(employeeBean.getEmployee()); + } + + @PutMapping("/employee") + public Employee updateEmployee(@RequestBody @Valid EmployeeBean employeeBean) { + return this.employeeService.updateEmployee(employeeBean.getId(), employeeBean.getEmployee()); + } + + + @PostMapping + public Iterable employeesFilter(@RequestBody EmployeeFilter filter) { + return this.employeeService.employeesFilter(filter); + } + + + +} +*/ diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/application.properties b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/application.properties new file mode 100644 index 00000000..9bac64c7 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/application.properties @@ -0,0 +1,20 @@ + + +spring.graphql.graphiql.enabled=true +#graphql ui base path +spring.graphql.graphiql.path=/espark/graphiql +#api base path +spring.graphql.path=/api/espark/graphql + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true + + diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/data.sql b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/data.sql new file mode 100644 index 00000000..25c032e0 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/data.sql @@ -0,0 +1,19 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL, + gender VARCHAR(8), + salary INT NOT NULL, + doj DATE, + attributes VARCHAR(250) DEFAULT NULL, + phone VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career, salary, gender, doj, attributes, phone) VALUES + ('adarsh', 'kumar', 'It', 10, 'MALE', '2020-01-1', '{"key1":"value"}', '["1234567890","1234567890"]'), + ('radha', 'singh', 'IT', 10, 'FEMALE', '2020-01-1', '{"key2":"value"}','["1234567890","1234567890"]'), + ('sonu', 'singh', 'IT', 5, 'MALE', '2020-01-1', '{"key3":"value"}','["1234567890","1234567890"]'), + ('amit', 'kumar', 'Finance',8, 'MALE', '2020-01-1', '{"key4":"value"}','["1234567890","1234567890"]'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/graphql/schema.graphqls b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/graphql/schema.graphqls new file mode 100644 index 00000000..6c9a0012 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/main/resources/graphql/schema.graphqls @@ -0,0 +1,55 @@ +scalar Date +scalar JSON + + + +enum Gender{ + MALE, + FEMALE +} +type Employee { + id: ID! + firstName: String + lastName: String + career: String + salary: Int + doj: Date + gender: Gender + attributes: JSON + phone: [String] +} + +input EmployeeBean { + id: ID! + firstName: String! + lastName: String! + career: String + salary: Int + doj: Date + gender: Gender + attributes: JSON + phone: [String] +} + +input FilterField { + operator: String! + value: String! +} + +input EmployeeFilter { + salary: FilterField + id: FilterField + career: FilterField +} + +type Query { + getAllEmployee: [Employee]! + getEmployee(id: ID): Employee + employeesFilter(filter: EmployeeFilter): [Employee] +} + +type Mutation { + saveEmployee(employeeBean:EmployeeBean!): Employee + updateEmployee(employeeBean:EmployeeBean!): Employee + removeEmployee(id: ID): Employee +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerTest.java b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerTest.java new file mode 100644 index 00000000..c4c5f63e --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerTest.java @@ -0,0 +1,180 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.GraphqlScalarConfiguration; +import com.espark.adarsh.entity.Employee; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureGraphQlTester; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.graphql.test.tester.GraphQlTester; +import org.springframework.test.context.TestPropertySource; + + +import javax.annotation.PostConstruct; +import java.util.List; + +@AutoConfigureGraphQlTester +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@Import({GraphqlScalarConfiguration.class}) +public class EmployeeGraphqQlControllerTest { + + + @Autowired + GraphQlTester graphQlTester; + + @PostConstruct + void init() { + + } + + @Test + void testGetEmployeeById() { + String document = """ + query{ + getEmployee(id:1){ + id + firstName + lastName + salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + @Test + void testSavingEmployee() { + String document = """ + mutation{ + saveEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"singh",career:"it", salary: 3}) { + id firstName lastName career salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.saveEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test + void testFilterEmployee() { + String document = """ + query { + employeesFilter(filter: { salary: { operator: "gt" value: "5" } }) { id firstName lastName salary }\s + } + """; + List employees = graphQlTester.document(document) + .execute() + .path("data.employeesFilter[*]") + .entityList(Employee.class) + .get(); + Assertions.assertTrue(employees.size() > 0); + Assertions.assertNotNull(employees.get(0).getId()); + Assertions.assertNotNull(employees.get(0).getFirstName()); + } + + @Test + void testUpdatingEmployee() { + String document = """ + mutation{ + updateEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"kumar singh",career:"it", salary: 3}) { + id firstName lastName career salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.updateEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test + void testGetAllEmployee() { + String document = """ + query{ + getAllEmployee{ + id + firstName + lastName + salary + } + } + """; + List employees = graphQlTester.document(document) + .execute() + .path("data.getAllEmployee[*]") + .entityList(Employee.class) + .get(); + Assertions.assertTrue(employees.size() > 0); + Assertions.assertNotNull(employees.get(0).getId()); + Assertions.assertNotNull(employees.get(0).getFirstName()); + } + + @Test + void testDeleteEmployee() { + String document = """ + mutation{ + removeEmployee(id: 3){ + id + firstName + lastName + career + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.removeEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test() + void testGetEmployeeNotFoundException() { + String document = """ + query{ + getEmployee(id:10){ + id + firstName + lastName + salary + } + } + """; + + java.lang.AssertionError exception = Assertions.assertThrows(java.lang.AssertionError.class, () -> { + graphQlTester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + }); + Assertions.assertTrue(exception.getMessage().toString().contains("employee not found")); + } + + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerWebTests.java b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerWebTests.java new file mode 100644 index 00000000..c4873c88 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployeeGraphqQlControllerWebTests.java @@ -0,0 +1,65 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.GraphqlScalarConfiguration; +import com.espark.adarsh.entity.Employee; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureGraphQlTester; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Import; +import org.springframework.graphql.test.tester.HttpGraphQlTester; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.servlet.client.MockMvcWebTestClient; +import org.springframework.web.context.WebApplicationContext; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@AutoConfigureGraphQlTester +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@Import({GraphqlScalarConfiguration.class}) +class EmployeeGraphqQlControllerWebTests { + + private final static String url ="/api/espark/graphql"; + + HttpGraphQlTester tester; + + public EmployeeGraphqQlControllerWebTests(WebApplicationContext context) { + WebTestClient client = + MockMvcWebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl(url) + .defaultHeader("name","my-header") + .build(); + tester = HttpGraphQlTester.create(client); + } + + + + + @Test + void testWebControllerGetEmployeeById(ApplicationContext context) { + String document = """ + query{ + getEmployee(id:1){ + id + firstName + lastName + salary + } + } + """; + Employee employee = this.tester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployyControllerMockTests.java b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployyControllerMockTests.java new file mode 100644 index 00000000..b838b5ba --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/EmployyControllerMockTests.java @@ -0,0 +1,189 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.GraphqlScalarConfiguration; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.Arrays; + +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) +@Sql({"/data.sql"}) +@Slf4j +@Import({GraphqlScalarConfiguration.class}) +class EmployyControllerMockTests { + + + private final static String url ="/api/espark/graphql"; + @Autowired + private MockMvc mockMvc; + + @MockBean + EmployeeService employeeService; + + + @Test + void contextLoads() { + } + + @Test + void testGraphQLGetEmployeeById() throws Exception { + when(employeeService.getEmployee(anyLong())).thenReturn(new Employee(1L,"adarsh","kumar","it",220L)); + String document = """ + { + "query": "query{getEmployee(id:1){ id firstName lastName salary}}" + } + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLGetAllEmployee() throws Exception { + + when(employeeService.getAllEmployee()).thenReturn(Arrays.asList( + new Employee(1L,"adarsh","kumar","it",220L), + new Employee(2L,"radha","singh","it",300L)) + ); + String document = """ + {"query":"query{getAllEmployee{ id firstName lastName salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLSavingEmployee() throws Exception { + Employee savedEmployee = new Employee(10L,"sonu","singh","it",3L); + when(employeeService.saveEmployee(ArgumentMatchers.any())).thenReturn(savedEmployee); + String document = """ + {"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\\"sonu\\",lastName:\\"singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLUpdatingEmployee() throws Exception { + Employee updateEmployee = new Employee(1L,"adarsh","kumar singh","it",3L); + when(employeeService.updateEmployee(anyLong(),ArgumentMatchers.any())).thenReturn(updateEmployee); + String document = """ + {"query":"mutation{updateEmployee(employeeBean:{ id:1,firstName:\\"adarsh\\",lastName:\\"kumar singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}\\n}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLDeleteEmployee() throws Exception { + Employee deleteEmployee = new Employee(1L,"adarsh","kumar singh","it",3L); + when(employeeService.removeEmployee(anyLong())).thenReturn(deleteEmployee); + String document = """ + { + "query": "mutation{removeEmployee(id: 1){ id firstName lastName career}\\n}" + } + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLFilterEmployee() throws Exception { + + when(employeeService.employeesFilter(ArgumentMatchers.any())).thenReturn(Arrays.asList( + new Employee(1L,"adarsh","kumar","it",10L), + new Employee(2L,"radha","singh","it",10L), + new Employee(4L,"amit","kumar","it",8L)) + ); + String document = """ + {"query":"query { employeesFilter(filter: { salary: { operator: \\"gt\\" value: \\"5\\" } }) { id firstName lastName salary } }"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + +} diff --git a/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java new file mode 100644 index 00000000..1aab2857 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-crud-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java @@ -0,0 +1,158 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.GraphqlScalarConfiguration; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) +@Sql({"/data.sql"}) +@Slf4j +@Import({GraphqlScalarConfiguration.class}) +class SpringbootBasicExampleApplicationTests { + + + private final static String url ="/api/espark/graphql"; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void contextLoads() { + } + + @Test + void testGraphQLGetEmployeeById() throws Exception { + String document = """ + { + "query": "query{getEmployee(id:1){ id firstName lastName salary}}" + } + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLGetAllEmployee() throws Exception { + String document = """ + {"query":"query{getAllEmployee{ id firstName lastName salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLSavingEmployee() throws Exception { + String document = """ + {"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\\"sonu\\",lastName:\\"singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLUpdatingEmployee() throws Exception { + String document = """ + {"query":"mutation{updateEmployee(employeeBean:{ id:1,firstName:\\"adarsh\\",lastName:\\"kumar singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}\\n}"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLDeleteEmployee() throws Exception { + String document = """ + { + "query": "mutation{removeEmployee(id: 1){ id firstName lastName career}\\n}" + } + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLFilterEmployee() throws Exception { + String document = """ + {"query":"query { employeesFilter(filter: { salary: { operator: \\"gt\\" value: \\"5\\" } }) { id firstName lastName salary } }"} + """; + MvcResult mvcResult = mockMvc.perform(post(url) + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/.gitignore b/APPLICATIONS/springboot-graphql-one-to-one-example/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/README.md b/APPLICATIONS/springboot-graphql-one-to-one-example/README.md new file mode 100644 index 00000000..cd521a96 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/README.md @@ -0,0 +1,248 @@ +# SPRING BOOT-BASIC-CRUD-EXAMPLE + +--- + +### to build the application +* $ mvn clean package +* $ mvn clean install -DskipTests + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +## Graphql console +* http://localhost:8080/graphiql?path=/graphql + +### single selection query without dependent data +```` +query{ + getEmployee(id:1){ + id + firstName + lastName + salary + } +} +```` + +### single selection query with dependent data +``` +query{ + getEmployee(id:10){ + id + firstName + lastName + salary + address { + id + street + state + country + } + } +} +``` + +### multi selection query without dependent data +``` +query{ + getAllEmployee{ + id + firstName + lastName + salary + } +} +``` + +### multi selection query with dependent data +``` +query{ + getAllEmployee{ + id + firstName + lastName + salary + address { + id + street + state + country + } + } +} +``` + +### saving data without dependent data +``` +mutation{ + saveEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"singh",career:"it", salary: 3}) { + id firstName lastName career salary + } +} +``` + +### saving data with dependent data +``` +mutation{ + saveEmployee(employeeBean:{ id:50,firstName:"sonu",lastName:"singh",career:"it", salary: 3 , addressBean:{ id:5, street:"blvd street",state:"texas",country:"usa"}}) { + id firstName lastName career salary address{ id street state country} + } +} +``` + +### updating data without dependent data +``` +mutation{ + updateEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"kumar singh",career:"it", salary: 3}) { + id firstName lastName career salary + } +} +``` + +### updating data with dependent data +``` +mutation{ + updateEmployee(employeeBean:{ id:50,firstName:"sonu",lastName:"kumar singh",career:"it", salary: 3 , addressBean:{ id:1, street:"town and country blvd street",state:"texas",country:"usa"}}) { + id firstName lastName career salary address{ id street state country} + } +} +``` + +### Filter Query without dependent +``` +query { + employeesFilter(filter: { salary: { operator: "gt" value: "5" } }) { id firstName lastName salary } +} +``` + +### Filter Query with dependent +``` +query { + employeesFilter(filter: { salary: { operator: "gt" value: "5" } }) { id firstName lastName salary address {id street state country}} +} +``` + +### removing data +``` +mutation{ + removeEmployee(id: 1){ + id + firstName + lastName + career + } +} + +``` + + +--- +# Curl Cmd Operation + +--- + +### AllEmployee without Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query{getAllEmployee{ id firstName lastName salary}\n}"}' + +``` + +### AllEmployee with Dependent +``` + +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query{getAllEmployee{ id firstName lastName salary address {id street state country }}\n}"}' +``` + +### Get Employee By Id without Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{ + "query": "query{getEmployee(id:1){ id firstName lastName salary}\n}" +}' +``` + +### Get Employee By Id with Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{ + "query": "query{getEmployee(id:10){ id firstName lastName salary address {id street state country }}\n}" +}' +``` + + +### Saving Employee without Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\"sonu\",lastName:\"singh\",career:\"it\", salary: 3}) { id firstName lastName career salary}\n}"}' +``` + +### Saving Employee with Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{saveEmployee(employeeBean:{ id:50,firstName:\"sonu\",lastName:\"singh\",career:\"it\", salary: 3 addressBean:{ id:5, street:\"blvd street\",state:\"texas\",country:\"usa\"}}) { id firstName lastName career salary address {id street state country }}\n}"}' + +``` + +### Updating Employee without Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{updateEmployee(employeeBean:{ id:50,firstName:\"sonu\",lastName:\"kumar singh\",career:\"it\", salary: 3 }) { id firstName lastName career salary }\n}"}' + +``` + + +### Updating Employee with Dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"mutation{updateEmployee(employeeBean:{ id:50,firstName:\"sonu\",lastName:\"kumar singh\",career:\"it\", salary: 3 , addressBean:{ id:1, street:\"town and country blvd street\",state:\"texas\",country:\"usa\"}}) { id firstName lastName career salary address {id street state country }}\n}"}' +``` + + +### Filter Query without dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query {\n employeesFilter(filter: { salary: { operator: \"gt\" value: \"5\" } }) { id firstName lastName salary } \n}"}' +``` + +### Filter Query without dependent +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--header 'Cookie: cookieName=' \ +--data '{"query":"query {\n employeesFilter(filter: { salary: { operator: \"gt\" value: \"5\" } }) { id firstName lastName salary address {id street state country} } \n}"}' +``` + +### Deleting Employee +``` +curl --location 'http://localhost:8080/graphql' \ +--header 'Content-Type: application/json' \ +--data '{ + "query": "mutation{removeEmployee(id: 10){ id firstName lastName career}\n}" +}' +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/pom.xml b/APPLICATIONS/springboot-graphql-one-to-one-example/pom.xml new file mode 100644 index 00000000..256a88a6 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.5 + + + com.espark.adarsh + springboot-graphql-one-to-one-example + 0.0.1-SNAPSHOT + springboot-graphql-one-to-one-example + Demo project for Spring Boot + + 1.8 + 11.1.0 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-graphql + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + 1.18.26 + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.graphql + spring-graphql-test + test + + + + com.graphql-java + graphql-java-servlet + 4.7.0 + + + + org.springframework + spring-webflux + 5.3.23 + + + + + javax.validation + validation-api + 2.0.1.Final + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 15 + 15 + + + + + + diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/AddressBean.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/AddressBean.java new file mode 100644 index 00000000..de1a74af --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/AddressBean.java @@ -0,0 +1,66 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entity.Address; + +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotEmpty; + +public class AddressBean { + + @Digits(fraction = 0, integer = 100, message = "id for address") + private Long id; + + @NotEmpty + private String street; + @NotEmpty + private String state; + + @NotEmpty + private String country; + + public AddressBean() { + } + + public AddressBean(Long id, String street, String state, String country) { + this.id = id; + this.street = street; + this.state = state; + this.country = country; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Address getAddress(){ + return new Address(this.id,this.street,this.state,this.country); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java new file mode 100644 index 00000000..0033a1bc --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/bean/EmployeeBean.java @@ -0,0 +1,92 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entity.Address; +import com.espark.adarsh.entity.Employee; + +import javax.validation.constraints.Digits; +import javax.validation.constraints.NotEmpty; + +public class EmployeeBean { + + @Digits(fraction = 0, integer = 100, message = "id for employee") + private Long id; + @NotEmpty + private String firstName; + @NotEmpty + private String lastName; + private String career; + + private Long salary; + + private AddressBean addressBean; + + public EmployeeBean() { + } + + public EmployeeBean(String firstName, String lastName, String career, Long salary) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public EmployeeBean(Long id, String firstName, String lastName, String career,Long salary) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public Employee getEmployee() { + return new Employee(this.id, this.firstName, this.lastName, this.career,this.salary,this.getAddressBean().getAddress()); + } + + public AddressBean getAddressBean() { + return addressBean; + } + + public void setAddressBean(AddressBean addressBean) { + this.addressBean = addressBean; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Address.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Address.java new file mode 100644 index 00000000..3b41ca1c --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Address.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + private String street; + private String state; + private String country; + + public Address() { + } + + public Address( String street, String state, String country) { + this.street = street; + this.state = state; + this.country = country; + } + + public Address(Long id, String street, String state, String country) { + this.id = id; + this.street = street; + this.state = state; + this.country = country; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..e50888be --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,95 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + private Long id; + private String firstName; + private String lastName; + private String career; + private Long salary; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id", foreignKey = @ForeignKey(name = "FK_ADDRESS_ID")) + private Address address; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career, Long salary) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public Employee(Long id, String firstName, String lastName, String career, Long salary) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + } + + public Employee(Long id, String firstName, String lastName, String career, Long salary, Address address) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + this.salary = salary; + this.address = address; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} + diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AddressNotFoundException.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AddressNotFoundException.java new file mode 100644 index 00000000..ef615615 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AddressNotFoundException.java @@ -0,0 +1,39 @@ +package com.espark.adarsh.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AddressNotFoundException extends RuntimeException implements GraphQLError { + + private Map extensions = new HashMap<>(); + + public AddressNotFoundException(String message, Long id) { + super(message); + extensions.put("AddressNotFoundException ", id); + } + + @Override + public List getLocations() { + return null; + } + + @Override + public Map getExtensions() { + return extensions; + } + + @Override + public ErrorType getErrorType() { + return ErrorType.DataFetchingException; + } + + @Override + public String toString() { + return "AddressNotFoundException "+this.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java new file mode 100644 index 00000000..9dccbb6e --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/AppDataFetcherExceptionResolverAdapter.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; +import graphql.schema.DataFetchingEnvironment; +import lombok.extern.slf4j.Slf4j; +import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.List; + + +@Slf4j +@Component +public class AppDataFetcherExceptionResolverAdapter extends DataFetcherExceptionResolverAdapter { + + @Override + protected List resolveToMultipleErrors(Throwable ex, DataFetchingEnvironment env) { + log.error("exception {}",ex.getMessage()); + if(ex!=null){ + if(ex instanceof EmployeeNotFoundException){ + return Arrays.asList((EmployeeNotFoundException)ex); + } + } + return Arrays.asList(GraphqlErrorBuilder.newError().message(ex.getMessage()).errorType(ErrorType.DataFetchingException).build()); + } + + @Override + protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { + log.error("exception {}",ex.getMessage()); + if(ex!=null){ + if(ex instanceof EmployeeNotFoundException){ + return (EmployeeNotFoundException)ex; + } + } + return GraphqlErrorBuilder.newError().message(ex.getMessage()).errorType(ErrorType.DataFetchingException).build(); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..c8325d19 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.exception; + + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.language.SourceLocation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EmployeeNotFoundException extends RuntimeException implements GraphQLError { + + private Map extensions = new HashMap<>(); + + public EmployeeNotFoundException(String message, Long id) { + super(message); + extensions.put("EmployeeNotFoundException ", id); + } + + @Override + public List getLocations() { + return null; + } + + @Override + public Map getExtensions() { + return extensions; + } + + @Override + public ErrorType getErrorType() { + return ErrorType.DataFetchingException; + } + + @Override + public String toString() { + return "EmployeeNotFoundException "+this.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/AddressFilter.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/AddressFilter.java new file mode 100644 index 00000000..e18b3f10 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/AddressFilter.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.filter; + +import lombok.Data; + + +@Data +public class AddressFilter { + + private FilterField id; + private FilterField street; + private FilterField state; + private FilterField country; + +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java new file mode 100644 index 00000000..8ba760c5 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/EmployeeFilter.java @@ -0,0 +1,14 @@ +package com.espark.adarsh.filter; + +import lombok.Data; + +@Data +public class EmployeeFilter { + + private FilterField id; + private FilterField salary; + private FilterField carrier; + + private AddressFilter addressFilter; + +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/FilterField.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/FilterField.java new file mode 100644 index 00000000..36892416 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/filter/FilterField.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.filter; +import lombok.Data; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; + +@Data +public class FilterField { + private String operator; + private String value; + + public Predicate generateCriteria(CriteriaBuilder builder, Path field) { + try { + int v = Integer.parseInt(value); + switch (operator) { + case "lt": return builder.lt(field, v); + case "le": return builder.le(field, v); + case "gt": return builder.gt(field, v); + case "ge": return builder.ge(field, v); + case "eq": return builder.equal(field, v); + } + } catch (NumberFormatException e) { + switch (operator) { + case "endsWith": return builder.like(field, "%" + value); + case "startsWith": return builder.like(field, value + "%"); + case "contains": return builder.like(field, "%" + value + "%"); + case "eq": return builder.equal(field, value); + } + } + + return null; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java new file mode 100644 index 00000000..be382ec9 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/RequestHeaderInterceptor.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.interceptor; + +import org.springframework.graphql.server.WebGraphQlInterceptor; +import org.springframework.graphql.server.WebGraphQlRequest; +import org.springframework.graphql.server.WebGraphQlResponse; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +import java.util.Collections; + +@Component +public class RequestHeaderInterceptor implements WebGraphQlInterceptor { + + @Override + public Mono intercept(WebGraphQlRequest request, Chain chain) { + String value = request.getHeaders().getFirst("espark"); + if (value != null) { + request.configureExecutionInput((executionInput, builder) -> + builder.graphQLContext(Collections.singletonMap("espark", value)).build()); + } + return chain.next(request); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java new file mode 100644 index 00000000..5526a6ae --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/interceptor/ResponseHeaderInterceptor.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.interceptor; + +import org.springframework.graphql.server.WebGraphQlInterceptor; +import org.springframework.graphql.server.WebGraphQlRequest; +import org.springframework.graphql.server.WebGraphQlResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; + +@Component +public class ResponseHeaderInterceptor implements WebGraphQlInterceptor { + + @Override + public Mono intercept(WebGraphQlRequest request, Chain chain) { + return chain.next(request).doOnNext(response -> { + String value = response.getExecutionInput().getGraphQLContext().get("cookieName"); + ResponseCookie cookie = ResponseCookie.from("cookieName", value).build(); + response.getResponseHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString()); + }); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/AddressRepository.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/AddressRepository.java new file mode 100644 index 00000000..85960545 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/AddressRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Address; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AddressRepository extends CrudRepository, + JpaSpecificationExecutor
{ +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..ef6764da --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository, + JpaSpecificationExecutor { +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/AddressService.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/AddressService.java new file mode 100644 index 00000000..cb6db84d --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/AddressService.java @@ -0,0 +1,116 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Address; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.AddressNotFoundException; +import com.espark.adarsh.filter.AddressFilter; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.filter.FilterField; +import com.espark.adarsh.respository.AddressRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.util.ReflectionUtils; +import org.springframework.web.bind.annotation.PathVariable; +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.Predicate; +import java.lang.reflect.Field; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +public class AddressService { + + + + @Autowired + AddressRepository addressRepository; + + public List
getAllAddress() { + List
addresses = new LinkedList<>(); + this.addressRepository.findAll().forEach(employee -> addresses.add(employee)); + return addresses; + } + + public Address getAddress(Long id) { + return this.addressRepository.findById(id) + .orElseThrow(() -> new AddressNotFoundException("employee not found", id)); + } + + public Address removeAddress(Long id) { + Address address = this.addressRepository.findById(id) + .orElseThrow(() -> new AddressNotFoundException("Address not found", id)); + this.addressRepository.deleteById(id); + return address; + } + + public Address saveAddress(Address employee) { + return this.addressRepository.save(employee); + } + + public Address updateAddress(Long id, Address employee) { + this.addressRepository.findById(id) + .orElseThrow(() -> new AddressNotFoundException("Address not found", id)); + return this.addressRepository.save(employee); + } + + + public Address updatePartialAddress(@PathVariable("id") Long id, Map address) { + final Optional
addressOptional = this.addressRepository.findById(id); + if (addressOptional.isPresent()) { + address.forEach((key, value) -> { + Field field = ReflectionUtils.findField(Employee.class, key); + field.setAccessible(true); + ReflectionUtils.setField(field, addressOptional.get(), value); + }); + return this.addressRepository.save(addressOptional.get()); + } + return addressOptional.orElseThrow(() -> new AddressNotFoundException("Address not found", id)); + } + + + + + public Iterable
addressFilter(AddressFilter filter) { + Specification
spec = null; + + if (filter.getId() != null) + spec = (spec == null ? byAddressId(filter.getId()) : spec.and(byAddressId(filter.getId()))); + + if (filter.getStreet() != null) + spec = (spec == null ? byStreet(filter.getStreet()) : + spec.and(byStreet(filter.getStreet()))); + + if (filter.getState() != null) + spec = (spec == null ? byStreet(filter.getState()) : + spec.and(byState(filter.getState()))); + + if (filter.getCountry() != null) + spec = (spec == null ? byCountry(filter.getCountry()) : + spec.and(byCountry(filter.getCountry()))); + + if (spec != null) + return addressRepository.findAll(spec); + else + return addressRepository.findAll(); + } + + + private Specification
byAddressId(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("id")); + } + + private Specification
byStreet(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("street")); + } + + private Specification
byState(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("state")); + } + + private Specification
byCountry(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("country")); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..2d1965be --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,108 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Address; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.filter.FilterField; +import com.espark.adarsh.respository.AddressRepository; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.util.ReflectionUtils; +import org.springframework.web.bind.annotation.*; + +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.Predicate; +import java.lang.reflect.Field; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + + @Autowired + AddressRepository addressRepository; + + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + this.employeeRepository.deleteById(id); + return employee; + } + + public Employee saveEmployee(Employee employee) { + //Address savedAddress =this.addressRepository.save(employee.getAddress()); + //employee.setAddress(savedAddress); + return this.employeeRepository.save(employee); + } + + public Employee updateEmployee(Long id, Employee employee) { + this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + return this.employeeRepository.save(employee); + } + + + public Employee updatePartialEmployee(@PathVariable("id") Long id, Map employee) { + final Optional employeeOptional = this.employeeRepository.findById(id); + if (employeeOptional.isPresent()) { + employee.forEach((key, value) -> { + Field field = ReflectionUtils.findField(Employee.class, key); + field.setAccessible(true); + ReflectionUtils.setField(field, employeeOptional.get(), value); + }); + return this.employeeRepository.save(employeeOptional.get()); + } + return employeeOptional.orElseThrow(() -> new EmployeeNotFoundException("employee not found", id)); + } + + + + + public Iterable employeesFilter(EmployeeFilter filter) { + Specification spec = null; + if (filter.getSalary() != null) + spec = bySalary(filter.getSalary()); + if (filter.getId() != null) + spec = (spec == null ? byEmployeeId(filter.getId()) : spec.and(byEmployeeId(filter.getId()))); + if (filter.getCarrier() != null) + spec = (spec == null ? byCarrier(filter.getCarrier()) : + spec.and(byCarrier(filter.getCarrier()))); + + if (spec != null) + return employeeRepository.findAll(spec); + else + return employeeRepository.findAll(); + } + + private Specification bySalary(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("salary")); + } + + private Specification byEmployeeId(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("id")); + } + + private Specification byCarrier(FilterField filterField) { + return (root, query, builder) -> filterField.generateCriteria(builder, root.get("carrier")); + } +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..9ea21db8 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.EmployeeBean; +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.filter.EmployeeFilter; +import com.espark.adarsh.service.EmployeeService; +import graphql.GraphQLContext; +import graphql.schema.DataFetchingEnvironment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.MutationMapping; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.stereotype.Controller; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@Controller +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @QueryMapping + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @QueryMapping + public Employee getEmployee(@Argument Long id, DataFetchingEnvironment env) { + ServletRequestAttributes attributes = + (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + String val = attributes.getRequest().getHeader("name"); + return this.employeeService.getEmployee(id); + } + + @MutationMapping + public Employee removeEmployee(@Argument("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @MutationMapping + public Employee saveEmployee(@Argument @Valid EmployeeBean employeeBean) { + return this.employeeService.saveEmployee(employeeBean.getEmployee()); + } + + @MutationMapping + public Employee updateEmployee(@Argument @Valid EmployeeBean employeeBean) { + return this.employeeService.updateEmployee(employeeBean.getId(), employeeBean.getEmployee()); + } + + + @QueryMapping + public Iterable employeesFilter(@Argument EmployeeFilter filter) { + return this.employeeService.employeesFilter(filter); + } + + + +} diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/application.properties b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/application.properties new file mode 100644 index 00000000..06fb6310 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/application.properties @@ -0,0 +1,20 @@ + +spring.graphql.graphiql.enabled=true +spring.graphql.graphiql.path=/graphiql + +spring.datasource.url=jdbc:h2:mem:test; +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.datasource.platform=h2 +spring.jpa.hibernate.ddl-auto=create-drop + + +spring.jpa.show-sql=true +#spring.datasource.url=jdbc:h2:file:/espark/db +spring.h2.console.enabled=true + + + + diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/data.sql b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/data.sql new file mode 100644 index 00000000..25118ace --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/data.sql @@ -0,0 +1,18 @@ + + +INSERT INTO address (id, street, state, country) VALUES + (100,'bang street', 'mp', 'in'), + (102,'hyd street', 'ap', 'in'), + (103,'ald street', 'up', 'in'), + (104,'delhi street', 'delhi', 'in'), + (105,'us street', 'delhi', 'us'); + +INSERT INTO employee (id,first_name, last_name, career, salary, address_id) VALUES + (10,'adarsh', 'kumar', 'It', 10, 100), + (20,'radha', 'singh', 'IT', 10, 102), + (30,'sonu', 'singh', 'IT', 5, 103), + (40,'amit', 'kumar', 'Finance', 8, 104), + (50,'monu', 'singh', 'IT', 5, 105); + + + diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/graphql/schema.graphqls b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/graphql/schema.graphqls new file mode 100644 index 00000000..ad19aed1 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/graphql/schema.graphqls @@ -0,0 +1,63 @@ +type Employee { + id: ID! + firstName: String + lastName: String + career: String + salary: Int + address: Address +} + + +type Address { + id: ID! + street: String + state: String + country: String +} + +input AddressBean { + id: ID! + street: String + state: String + country: String +} + +input EmployeeBean { + id: ID! + firstName: String! + lastName: String! + career: String + salary: Int + addressBean: AddressBean +} + +input FilterField { + operator: String! + value: String! +} + +input AddressBeanFilter { + id: FilterField + street: FilterField + state: FilterField + country: FilterField +} + +input EmployeeFilter { + salary: FilterField + id: FilterField + career: FilterField + addressBean: AddressBeanFilter +} + +type Query { + getAllEmployee: [Employee]! + getEmployee(id: ID): Employee + employeesFilter(filter: EmployeeFilter): [Employee] +} + +type Mutation { + saveEmployee(employeeBean:EmployeeBean!): Employee + updateEmployee(employeeBean:EmployeeBean!): Employee + removeEmployee(id: ID): Employee +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/schema.sql b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/schema.sql new file mode 100644 index 00000000..adc2b2c8 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/main/resources/schema.sql @@ -0,0 +1,24 @@ + + +--DROP TABLE IF EXISTS address; + +CREATE TABLE IF NOT EXISTS address ( + id INT AUTO_INCREMENT PRIMARY KEY, + country VARCHAR(255), + state VARCHAR(255), + street VARCHAR(255) +); + + +--DROP TABLE IF EXISTS employee; + +CREATE TABLE IF NOT EXISTS employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL, + salary INT NOT NULL, + address_id INT, + CONSTRAINT FK_ADDRESS_ID FOREIGN KEY (address_id) REFERENCES address(id) +); + diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerMockTests.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerMockTests.java new file mode 100644 index 00000000..524f0e9a --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerMockTests.java @@ -0,0 +1,187 @@ +/* +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.Arrays; + +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) +@Sql({"/schema.sql","/data.sql"}) +@Slf4j +class EmployeeControllerMockTests { + + + @Autowired + private MockMvc mockMvc; + + @MockBean + EmployeeService employeeService; + + + @Test + void contextLoads() { + } + + @Test + void testGraphQLGetEmployeeById() throws Exception { + when(employeeService.getEmployee(anyLong())).thenReturn(new Employee(1L,"adarsh","kumar","it",220L)); + String document = """ + { + "query": "query{getEmployee(id:1){ id firstName lastName salary}}" + } + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLGetAllEmployee() throws Exception { + + when(employeeService.getAllEmployee()).thenReturn(Arrays.asList( + new Employee(1L,"adarsh","kumar","it",220L), + new Employee(2L,"radha","singh","it",300L)) + ); + String document = """ + {"query":"query{getAllEmployee{ id firstName lastName salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLSavingEmployee() throws Exception { + Employee savedEmployee = new Employee(10L,"sonu","singh","it",3L); + when(employeeService.saveEmployee(ArgumentMatchers.any())).thenReturn(savedEmployee); + String document = """ + {"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\\"sonu\\",lastName:\\"singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLUpdatingEmployee() throws Exception { + Employee updateEmployee = new Employee(1L,"adarsh","kumar singh","it",3L); + when(employeeService.updateEmployee(anyLong(),ArgumentMatchers.any())).thenReturn(updateEmployee); + String document = """ + {"query":"mutation{updateEmployee(employeeBean:{ id:1,firstName:\\"adarsh\\",lastName:\\"kumar singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}\\n}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLDeleteEmployee() throws Exception { + Employee deleteEmployee = new Employee(1L,"adarsh","kumar singh","it",3L); + when(employeeService.removeEmployee(anyLong())).thenReturn(deleteEmployee); + String document = """ + { + "query": "mutation{removeEmployee(id: 1){ id firstName lastName career}\\n}" + } + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLFilterEmployee() throws Exception { + + when(employeeService.employeesFilter(ArgumentMatchers.any())).thenReturn(Arrays.asList( + new Employee(1L,"adarsh","kumar","it",10L), + new Employee(2L,"radha","singh","it",10L), + new Employee(4L,"amit","kumar","it",8L)) + ); + String document = """ + {"query":"query { employeesFilter(filter: { salary: { operator: \\"gt\\" value: \\"5\\" } }) { id firstName lastName salary } }"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + +} +*/ diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerTest.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerTest.java new file mode 100644 index 00000000..bca904ba --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerTest.java @@ -0,0 +1,178 @@ +/* +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureGraphQlTester; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.graphql.test.tester.GraphQlTester; + + +import javax.annotation.PostConstruct; +import java.util.List; + +@AutoConfigureGraphQlTester +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +public class EmployeeControllerTest { + + + @Autowired + GraphQlTester graphQlTester; + + @PostConstruct + void init() { + + } + + @Test + void testGetEmployeeById() { + String document = """ + query{ + getEmployee(id:1){ + id + firstName + lastName + salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + @Test + void testSavingEmployee() { + String document = """ + mutation{ + saveEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"singh",career:"it", salary: 3}) { + id firstName lastName career salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.saveEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test + void testFilterEmployee() { + String document = """ + query { + employeesFilter(filter: { salary: { operator: "gt" value: "5" } }) { id firstName lastName salary }\s + } + """; + List employees = graphQlTester.document(document) + .execute() + .path("data.employeesFilter[*]") + .entityList(Employee.class) + .get(); + Assertions.assertTrue(employees.size() > 0); + Assertions.assertNotNull(employees.get(0).getId()); + Assertions.assertNotNull(employees.get(0).getFirstName()); + } + + @Test + void testUpdatingEmployee() { + String document = """ + mutation{ + updateEmployee(employeeBean:{ id:10,firstName:"sonu",lastName:"kumar singh",career:"it", salary: 3}) { + id firstName lastName career salary + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.updateEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test + void testGetAllEmployee() { + String document = """ + query{ + getAllEmployee{ + id + firstName + lastName + salary + } + } + """; + List employees = graphQlTester.document(document) + .execute() + .path("data.getAllEmployee[*]") + .entityList(Employee.class) + .get(); + Assertions.assertTrue(employees.size() > 0); + Assertions.assertNotNull(employees.get(0).getId()); + Assertions.assertNotNull(employees.get(0).getFirstName()); + } + + @Test + void testDeleteEmployee() { + String document = """ + mutation{ + removeEmployee(id: 3){ + id + firstName + lastName + career + } + } + """; + Employee employee = graphQlTester.document(document) + .execute() + .path("data.removeEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + + + @Test() + void testGetEmployeeNotFoundException() { + String document = """ + query{ + getEmployee(id:10){ + id + firstName + lastName + salary + } + } + """; + + java.lang.AssertionError exception = Assertions.assertThrows(java.lang.AssertionError.class, () -> { + graphQlTester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + }); + Assertions.assertTrue(exception.getMessage().toString().contains("employee not found")); + } + + +} +*/ diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerWebTests.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerWebTests.java new file mode 100644 index 00000000..16c480ff --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/EmployeeControllerWebTests.java @@ -0,0 +1,65 @@ +/* +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureGraphQlTester; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.graphql.test.tester.HttpGraphQlTester; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.servlet.client.MockMvcWebTestClient; +import org.springframework.web.context.WebApplicationContext; + +import javax.annotation.PostConstruct; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@AutoConfigureGraphQlTester +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +class EmployeeControllerWebTests { + + HttpGraphQlTester tester; + + public EmployeeControllerWebTests(WebApplicationContext context) { + WebTestClient client = + MockMvcWebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl("/graphql") + .defaultHeader("name","my-header") + .build(); + tester = HttpGraphQlTester.create(client); + } + + + + + @Test + void testWebControllerGetEmployeeById(ApplicationContext context) { + String document = """ + query{ + getEmployee(id:1){ + id + firstName + lastName + salary + } + } + """; + Employee employee = this.tester.document(document) + .execute() + .path("data.getEmployee") + .entity(Employee.class) + .get(); + Assertions.assertTrue(employee.getId() > 0); + Assertions.assertNotNull(employee.getFirstName() != null); + Assertions.assertNotNull(employee.getLastName() != null); + } + +} +*/ diff --git a/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java new file mode 100644 index 00000000..dcede299 --- /dev/null +++ b/APPLICATIONS/springboot-graphql-one-to-one-example/src/test/java/com/espark/adarsh/SpringbootBasicExampleApplicationTests.java @@ -0,0 +1,155 @@ +/* +package com.espark.adarsh; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.hamcrest.Matchers.notNullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) +@Sql({"/data.sql"}) +@Slf4j +class SpringbootBasicExampleApplicationTests { + + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void contextLoads() { + } + + @Test + void testGraphQLGetEmployeeById() throws Exception { + String document = """ + { + "query": "query{getEmployee(id:1){ id firstName lastName salary}}" + } + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLGetAllEmployee() throws Exception { + String document = """ + {"query":"query{getAllEmployee{ id firstName lastName salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + @Test + void testGraphQLSavingEmployee() throws Exception { + String document = """ + {"query":"mutation{saveEmployee(employeeBean:{ id:10,firstName:\\"sonu\\",lastName:\\"singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLUpdatingEmployee() throws Exception { + String document = """ + {"query":"mutation{updateEmployee(employeeBean:{ id:1,firstName:\\"adarsh\\",lastName:\\"kumar singh\\",career:\\"it\\", salary: 3}) { id firstName lastName career salary}\\n}"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLDeleteEmployee() throws Exception { + String document = """ + { + "query": "mutation{removeEmployee(id: 1){ id firstName lastName career}\\n}" + } + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + + + @Test + void testGraphQLFilterEmployee() throws Exception { + String document = """ + {"query":"query { employeesFilter(filter: { salary: { operator: \\"gt\\" value: \\"5\\" } }) { id firstName lastName salary } }"} + """; + MvcResult mvcResult = mockMvc.perform(post("/graphql") + .content(document) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(notNullValue())) + .andReturn(); + mockMvc.perform(asyncDispatch(mvcResult)) + .andDo(print()) + .andExpect(status().isOk()); + log.info(mvcResult.getResponse().getContentAsString()); + } + +} +*/ diff --git a/APPLICATIONS/springboot-groovy-java/.gitignore b/APPLICATIONS/springboot-groovy-java/.gitignore new file mode 100644 index 00000000..c456c4a3 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ diff --git a/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/APPLICATIONS/springboot-groovy-java/doc/help.txt b/APPLICATIONS/springboot-groovy-java/doc/help.txt new file mode 100644 index 00000000..a14d2fdb --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/doc/help.txt @@ -0,0 +1,5 @@ + +$ mvn clean package +$ mvn spring-boot:run + +http://localhost:8080/message \ No newline at end of file diff --git a/APPLICATIONS/springboot-groovy-java/pom.xml b/APPLICATIONS/springboot-groovy-java/pom.xml new file mode 100644 index 00000000..72d695c5 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/pom.xml @@ -0,0 +1,80 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.espark.adarsh + springboot-groovy-java + 0.0.1-SNAPSHOT + springboot-groovy-java + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.codehaus.groovy + groovy-all + 2.4.3 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + groovy-eclipse-compiler + true + + + + org.codehaus.groovy + groovy-eclipse-compiler + 2.7.0-01 + + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.9 + + + org.eclipse.jdt.groovy.core.groovyNature + + + **/*.groovy + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/DataMaskingService.groovy b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/DataMaskingService.groovy new file mode 100644 index 00000000..550f1521 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/DataMaskingService.groovy @@ -0,0 +1,15 @@ +package com.espark.adarsh + +import org.springframework.stereotype.Service + +@Service +class DataMaskingService { + + def dataMaskingProcessor(def inputJSON ) { + inputJSON?.each{ + it?.contact.mobile='*****' + it?.address.apt='*****' + } + return inputJSON; + } +} diff --git a/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageService.groovy b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageService.groovy new file mode 100644 index 00000000..f81c1db6 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageService.groovy @@ -0,0 +1,7 @@ +package com.espark.adarsh + +interface MessageService { + + def getMessage(); + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageServiceImpl.groovy b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageServiceImpl.groovy new file mode 100644 index 00000000..d8863b00 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/MessageServiceImpl.groovy @@ -0,0 +1,19 @@ +package com.espark.adarsh + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service + + +@Service +class MessageServiceImpl implements MessageService { + + @Autowired + ReaderService reader + + @Override + def getMessage() { + return this.reader.readJsonData(); + } + + +} diff --git a/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/ReaderService.groovy b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/ReaderService.groovy new file mode 100644 index 00000000..4eed2188 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/groovy/com/espark/adarsh/ReaderService.groovy @@ -0,0 +1,35 @@ +package com.espark.adarsh + +import groovy.json.JsonSlurper +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Component + +import javax.annotation.PostConstruct + +@Component +class ReaderService { + + @Autowired + ApplicationContext context; ; + + @Autowired + DataMaskingService dataMaskingService; + + def inputJSON = null; ; + + @PostConstruct + public void init() { + File inputFile = this.context.getResource('classpath:data/input.json').getFile(); + if (!inputFile.exists()) { + throw new FileNotFoundException("input.json") + } + inputJSON = new JsonSlurper().parseFile(inputFile, 'UTF-8') + } + + def readJsonData(){ + inputJSON = this.dataMaskingService.dataMaskingProcessor(inputJSON); + return inputJSON; + } + +} diff --git a/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..b58e7cbc --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} + diff --git a/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/controller/MessageController.java b/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/controller/MessageController.java new file mode 100644 index 00000000..3f297a83 --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/java/com/espark/adarsh/controller/MessageController.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MessageController { + + @Autowired + private MessageService messageService; + + @RequestMapping(value = "/message", method = RequestMethod.GET) + public Object getMessage() { + return this.messageService.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-groovy-java/src/main/resources/application.properties b/APPLICATIONS/springboot-groovy-java/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-groovy-java/src/main/resources/data/input.json b/APPLICATIONS/springboot-groovy-java/src/main/resources/data/input.json new file mode 100644 index 00000000..6ecc42bd --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/main/resources/data/input.json @@ -0,0 +1,44 @@ +[ + { + "name": "adarsh kumar", + "dob": "13-sept-1983", + "contact": { + "mobile": 6822561688, + "email": "adarsh@kumar.com" + }, + "address": { + "street": "5250 Town & coutry blvd.", + "apt": "4203", + "city": "firsco", + "state": "tx" + } + }, + { + "name": "amit kumar", + "dob": "04-jan-1986", + "contact": { + "mobile": 9902323520, + "email": "amit@kumar.com" + }, + "address": { + "street": "5250 Town & coutry blvd.", + "apt": "4203", + "city": "firsco", + "state": "tx" + } + }, + { + "name": "radha singh", + "dob": "04-jan-1986", + "contact": { + "mobile": 9902323520, + "email": "amit@kumar.com" + }, + "address": { + "street": "5250 Town & coutry blvd.", + "apt": "4203", + "city": "firsco", + "state": "tx" + } + } +] \ No newline at end of file diff --git a/APPLICATIONS/springboot-groovy-java/src/test/java/com/espark/adarsh/springbootgroovyjava/SpringbootGroovyJavaApplicationTests.java b/APPLICATIONS/springboot-groovy-java/src/test/java/com/espark/adarsh/springbootgroovyjava/SpringbootGroovyJavaApplicationTests.java new file mode 100644 index 00000000..7db6dced --- /dev/null +++ b/APPLICATIONS/springboot-groovy-java/src/test/java/com/espark/adarsh/springbootgroovyjava/SpringbootGroovyJavaApplicationTests.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.springbootgroovyjava; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringbootGroovyJavaApplicationTests { + + @Test + public void contextLoads() { + } + +} + diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/.gitignore b/APPLICATIONS/springboot-h2-db-remote-debugging/.gitignore new file mode 100644 index 00000000..66ccf4ff --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/.gitignore @@ -0,0 +1,35 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +.DS_Store +*.DS_Store +*/.DS_Store + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/README.md b/APPLICATIONS/springboot-h2-db-remote-debugging/README.md new file mode 100644 index 00000000..770ff3e2 --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/README.md @@ -0,0 +1,103 @@ +# springboot-h2-db-docker-remote-debugging + +--- + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +### To Test the api +* curl -X GET http://localhost:8080/employees +```` +[ + { + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" + }, + { + "id": 2, + "firstName": "radha", + "lastName": "singh", + "career": "IT" + }, + { + "id": 3, + "firstName": "sonu", + "lastName": "singh", + "career": "IT" + }, + { + "id": 4, + "firstName": "amit", + "lastName": "kumar", + "career": "Finance" + } +] +```` + +## Create a `application-debugging.sh` with below content +```` +# application-debugging.sh +java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8090,suspend=n -jar springboot-h2-db-docker-remote-debugging.jar +```` + +### Start Running Application in Debug mode using `application-debugging.sh` +* $ sh application-debugging.sh +```` +Listening for transport dt_socket at address: 8090 + + . ____ _ __ _ _ + /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ +( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ + \\/ ___)| |_)| | | | | || (_| | ) ) ) ) + ' |____| .__|_| |_|_| |_\__, | / / / / + =========|_|==============|___/=/_/_/_/ + :: Spring Boot :: (v2.2.6.RELEASE) + +2022-02-25 22:16:22.720 INFO 15948 --- [ main] com.espark.adarsh.ApplicationMain : Starting ApplicationMain v0.0.1-SNAPSHOT on USMB113823.attlocal.net with PID 15948 (/Users/us-guest/Desktop/springboot-h2-db-remote-debugging/target/springboot-h2-db-remote-debugging.jar started by us-guest in /Users/us-guest/Desktop/springboot-h2-db-remote-debugging) +2022-02-25 22:16:22.722 INFO 15948 --- [ main] com.espark.adarsh.ApplicationMain : No active profile set, falling back to default profiles: default +2022-02-25 22:16:23.224 INFO 15948 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. +2022-02-25 22:16:23.282 INFO 15948 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 50ms. Found 1 JPA repository interfaces. +2022-02-25 22:16:23.815 INFO 15948 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) +2022-02-25 22:16:23.826 INFO 15948 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] +2022-02-25 22:16:23.826 INFO 15948 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33] +2022-02-25 22:16:23.885 INFO 15948 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext +2022-02-25 22:16:23.886 INFO 15948 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1123 ms +2022-02-25 22:16:23.931 INFO 15948 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... +2022-02-25 22:16:24.120 INFO 15948 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. +2022-02-25 22:16:24.125 INFO 15948 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb' +2022-02-25 22:16:24.255 INFO 15948 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] +2022-02-25 22:16:24.340 INFO 15948 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final +2022-02-25 22:16:24.508 INFO 15948 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final} +2022-02-25 22:16:24.640 INFO 15948 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect +2022-02-25 22:16:25.250 INFO 15948 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] +2022-02-25 22:16:25.258 INFO 15948 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' +2022-02-25 22:16:25.561 WARN 15948 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning +2022-02-25 22:16:25.768 INFO 15948 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' +2022-02-25 22:16:26.154 INFO 15948 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' +2022-02-25 22:16:26.156 INFO 15948 --- [ main] com.espark.adarsh.ApplicationMain : Started ApplicationMain in 3.808 seconds (JVM running for 4.534) +```` + +### To Add Remote Debugging in Intellj ide +* Go to Edit Configuration of Run + * Click on + button in left corner + * Search for the Remote JVM Debugging + * provide the name = xxx + * Debugger mode = attach to remote jvm + * host = host name + * port = which we have given for remote debugging and save it +* start the application in debugging +```` +Connected to the target VM, address: 'localhost:8090', transport: 'socket' +```` +* add the debugging point in the code and hit the api for debugging \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/application-debugging.sh b/APPLICATIONS/springboot-h2-db-remote-debugging/application-debugging.sh new file mode 100644 index 00000000..e3b47f6d --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/application-debugging.sh @@ -0,0 +1,2 @@ +# application-debugging.sh +java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8090,suspend=n -jar ./target/springboot-h2-db-remote-debugging.jar \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/pom.xml b/APPLICATIONS/springboot-h2-db-remote-debugging/pom.xml new file mode 100644 index 00000000..6cf1b70a --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-h2-db-remote-debugging + 0.0.1-SNAPSHOT + springboot-h2-db-remote-debugging + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + springboot-h2-db-remote-debugging + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..57a3e3de --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..5a452947 --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.exception; + +public class EmployeeNotFoundException extends RuntimeException{ + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..59a2bf6a --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/application.properties b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/application.properties new file mode 100644 index 00000000..bf8b7d8f --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/application.properties @@ -0,0 +1,10 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/data.sql b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-db-remote-debugging/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-h2-db-remote-debugging/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-h2-db-remote-debugging/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-h2-jpa/.gitignore b/APPLICATIONS/springboot-h2-jpa/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-h2-jpa/pom.xml b/APPLICATIONS/springboot-h2-jpa/pom.xml new file mode 100644 index 00000000..3c321a92 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-h2-jpa + 0.0.1-SNAPSHOT + springboot-h2-jpa + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + + io.dropwizard + dropwizard-core + 2.0.8 + + + + io.dropwizard.metrics + metrics-healthchecks + 4.1.6 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/BaseEntity.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/BaseEntity.java new file mode 100644 index 00000000..1b95fdd6 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/BaseEntity.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.entity; + + +import javax.persistence.Id; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.MappedSuperclass; +import java.io.Serializable; + +@MappedSuperclass +public class BaseEntity implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected int id; + +} diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Permission.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Permission.java new file mode 100644 index 00000000..e51ae4d8 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Permission.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.entity; + +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name = "permission") +public class Permission extends BaseEntity { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Role.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Role.java new file mode 100644 index 00000000..34c2494d --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/Role.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.entity; + + +import java.util.List; + +import javax.persistence.*; + +@Entity +@Table(name = "role") +public class Role extends BaseEntity { + + private String name; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "permission_role", joinColumns = { + @JoinColumn(name = "role_id", referencedColumnName = "id") }, inverseJoinColumns = { + @JoinColumn(name = "permission_id", referencedColumnName = "id") }) + private List permissions; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getPermissions() { + return permissions; + } + + public void setPermissions(List permissions) { + this.permissions = permissions; + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/User.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/User.java new file mode 100644 index 00000000..54b47b54 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/entity/User.java @@ -0,0 +1,95 @@ +package com.espark.adarsh.entity; + +import java.util.List; + +import javax.persistence.*; + +@Entity +@Table(name = "user") +public class User extends BaseEntity { + + private String email; + private String username; + private String password; + private boolean enabled; + + @Column(name = "account_locked") + private boolean accountNonLocked; + + @Column(name = "account_expired") + private boolean accountNonExpired; + + @Column(name = "credentials_expired") + private boolean credentialsNonExpired; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "role_user", joinColumns = { + @JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = { + @JoinColumn(name = "role_id", referencedColumnName = "id")}) + private List roles; + + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isAccountNonLocked() { + return accountNonLocked; + } + + public void setAccountNonLocked(boolean accountNonLocked) { + this.accountNonLocked = accountNonLocked; + } + + public boolean isAccountNonExpired() { + return accountNonExpired; + } + + public void setAccountNonExpired(boolean accountNonExpired) { + this.accountNonExpired = accountNonExpired; + } + + public boolean isCredentialsNonExpired() { + return credentialsNonExpired; + } + + public void setCredentialsNonExpired(boolean credentialsNonExpired) { + this.credentialsNonExpired = credentialsNonExpired; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/repository/UserRepository.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/repository/UserRepository.java new file mode 100644 index 00000000..b51da3bd --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.repository; + +import javax.transaction.Transactional; + + +import com.espark.adarsh.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + + +@Repository +@Transactional +public interface UserRepository extends JpaRepository { + + User findByUsername(String username); + +} diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..4a4ebb17 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.service; + +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.health.HealthCheck; +import com.codahale.metrics.health.HealthCheckRegistry; +import com.espark.adarsh.util.DatabaseHealthCheck; +import com.zaxxer.hikari.HikariDataSource; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Slf4j +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @Bean + public MetricRegistry metricRegistry(){ + return new MetricRegistry(); + } + + @PostConstruct + public void init() { + /* Resource initSchema = new ClassPathResource("DB.SQL"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource);*/ + log.info("label=init() execution successful"); + + if(dataSource instanceof HikariDataSource) { + ((HikariDataSource) dataSource).setMetricRegistry(metricRegistry()); + } + HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + healthCheckRegistry.register("db", new DatabaseHealthCheck()); + healthCheckRegistry.runHealthCheck("db"); + log.info("label=setUpHikariWithMetrics() execution successful"); + } +} diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/util/DatabaseHealthCheck.java b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/util/DatabaseHealthCheck.java new file mode 100644 index 00000000..3705a0f2 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/java/com/espark/adarsh/util/DatabaseHealthCheck.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.util; + +import com.codahale.metrics.health.HealthCheck; +import com.zaxxer.hikari.HikariDataSource; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; + +@Slf4j +@Service +public class DatabaseHealthCheck extends HealthCheck { + + @Autowired + DataSource dataSource; + + protected Result check() throws Exception { + // this has to linked with acchuater + log.info("label=dbCheck() execution "); + if(!((HikariDataSource) dataSource).isClosed()) { + return Result.healthy(); + }else{ + return Result.unhealthy("CONNECTION POOL IS DOWN"); + } + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/resources/DB.SQL b/APPLICATIONS/springboot-h2-jpa/src/main/resources/DB.SQL new file mode 100644 index 00000000..6480a438 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/resources/DB.SQL @@ -0,0 +1,37 @@ + +DROP TABLE IF EXISTS permission; + +CREATE TABLE permission( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL , + name VARCHAR(255), +); + +DROP TABLE IF EXISTS role; +CREATE TABLE role( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL , + name VARCHAR(255) +); + +DROP TABLE IF EXISTS permission_role; +CREATE TABLE permission_role( + role_id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + permission_id INTEGER NOT NULL +); + +DROP TABLE IF EXISTS role_user; +CREATE TABLE role_user( + user_id INTEGER NOT NULL, + role_id INTEGER NOT NULL +); + +DROP TABLE IF EXISTS user; +CREATE TABLE user( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + account_expired BOOLEAN, + account_locked BOOLEAN, + credenntials_expired BOOLEAN, + email VARCHAR(255), + enable BOOLEAN NOT NULL, + password VARCHAR(255), + uesrnname VARCHAR(255) +); diff --git a/APPLICATIONS/springboot-h2-jpa/src/main/resources/application.yml b/APPLICATIONS/springboot-h2-jpa/src/main/resources/application.yml new file mode 100644 index 00000000..180a3273 --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/main/resources/application.yml @@ -0,0 +1,35 @@ +## http://localhost:8080/h2-console +server: + port: 8080 + +spring: + h2: + console: + enabled: true + application: + name: h2-jpa + datasource: + url: jdbc:h2:mem:db + username: root + password: root + driver-class-name: org.h2.Driver + initialization-mode: always + hikari: + connection-timeout: 20000 #maximum number of milliseconds that a client will wait for a connection + minimum-idle: 10 #minimum number of idle connections maintained by HikariCP in a connection pool + maximum-pool-size: 10 #maximum pool size + idle-timeout: 10000 #maximum idle time for connection + max-lifetime: 1000 # maximum lifetime in milliseconds of a connection in the pool after it is closed. + auto-commit: true #default auto-commit behavior. + jpa: + database-platform: org.hibernate.dialect.H2Dialect + generate-ddl: true + hibernate: + ddl-auto: update + naming: + implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + +logging: + level: + root: DEBUG \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-jpa/src/test/java/com/espark/adarsh/SpringbootH2JapApplicationTests.java b/APPLICATIONS/springboot-h2-jpa/src/test/java/com/espark/adarsh/SpringbootH2JapApplicationTests.java new file mode 100644 index 00000000..227d4fbe --- /dev/null +++ b/APPLICATIONS/springboot-h2-jpa/src/test/java/com/espark/adarsh/SpringbootH2JapApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootH2JapApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/.gitignore b/APPLICATIONS/springboot-h2-redis-cache-example/.gitignore new file mode 100644 index 00000000..e91d115f --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +.DS_Store +*.DS_Store +*/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/README.md b/APPLICATIONS/springboot-h2-redis-cache-example/README.md new file mode 100644 index 00000000..2038f3d4 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/README.md @@ -0,0 +1,73 @@ +# springboot-h2-redis-cache-example + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +### To run redis cache +* docker pull redis +* docker run --rm -p 6379:6379 --name redis-espark redis + +### Get Request +* http://localhost:8080/employee/1 +* curl --location --request GET 'http://localhost:8080/employee/1' +``` + { + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" +} +``` + +### Post Request +* http://localhost:8080/employee +* curl --location --request POST 'http://localhost:8080/employee' \ + --header 'Content-Type: application/json' \ + --data-raw '{"id": 5,"firstName": "shakti","lastName": "singh","career": "Operatons" }' +``` + { + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "Operatons" +} +``` + +### Put Request +* http://localhost:8080/employee/5 +* curl --location --request PUT 'http://localhost:8080/employee/5' \ + --header 'Content-Type: application/json' \ + --data-raw '{"id": 5,"firstName": "shakti","lastName": "singh","career": "founder"}' +``` +{ + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "founder" +} +``` + +### Patch Request +* http://localhost:8080/employee/5 +* curl --location --request PATCH 'http://localhost:8080/employee/5' \ + --header 'Content-Type: application/json' \ + --data-raw '{"career": "founder-invester"}' +``` + { + "id": 5, + "firstName": "shakti", + "lastName": "singh", + "career": "founder-invester" +} +``` + + diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/pom.xml b/APPLICATIONS/springboot-h2-redis-cache-example/pom.xml new file mode 100644 index 00000000..42f8cf38 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-h2-redis-cache-example + 0.0.1-SNAPSHOT + springboot-h2-redis-cache-example + Demo project for Spring Boot + + + 1.8 + 1.17.2 + + + + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-web + + + + redis.clients + jedis + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + org.testcontainers + junit-jupiter + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..a5a88dd3 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..715b7f36 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Bean; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericToStringSerializer; + +@Configuration +public class ApplicationConfig { + + @Value("${spring.redis.host}") + private String host; + + @Value("${spring.redis.port}") + private Integer port; + + @Bean + public JedisConnectionFactory jedisConnectionFactory() { + RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); + config.setHostName(host); + config.setPort(port); + return new JedisConnectionFactory(config); + } + + @Bean + public RedisTemplate redisTemplate(){ + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(jedisConnectionFactory()); + redisTemplate.setValueSerializer(new GenericToStringSerializer(Object.class)); + return redisTemplate; + } + + +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..91630730 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Table(name = "employee") +public class Employee implements Serializable { + + @Id + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java new file mode 100644 index 00000000..b503d9e7 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; + +import java.util.Date; + +@ControllerAdvice +public class ApplicationExceptionHandler { + + @ExceptionHandler(value = {EmployeeNotFoundException.class}) + public ResponseEntity resourceNotFoundException(EmployeeNotFoundException ex, WebRequest request) { + ErrorMessage message = new ErrorMessage( + HttpStatus.NOT_FOUND.value(), + new Date(), + ex.getMessage(), + ex.getMessage()); + + return new ResponseEntity(message, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity globalExceptionHandler(Exception ex, WebRequest request) { + ErrorMessage message = new ErrorMessage( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + new Date(), + ex.getMessage(), + request.getDescription(false)); + + return new ResponseEntity(message, HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..0c56a8db --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.exception; + + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +public class EmployeeNotFoundException extends RuntimeException { + + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ErrorMessage.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ErrorMessage.java new file mode 100644 index 00000000..e775ce1e --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/exception/ErrorMessage.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.exception; + +import java.util.Date; + +public class ErrorMessage { + private int statusCode; + private Date timestamp; + private String message; + private String description; + + public ErrorMessage(int statusCode, Date timestamp, String message, String description) { + this.statusCode = statusCode; + this.timestamp = timestamp; + this.message = message; + this.description = description; + } + + public int getStatusCode() { + return statusCode; + } + + public Date getTimestamp() { + return timestamp; + } + + public String getMessage() { + return message; + } + + public String getDescription() { + return description; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..23998271 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + org.springframework.core.io.Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..def351fc --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,57 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Cacheable(value = "Employee") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @Cacheable(value = "Employee", key = "#id") + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + } + + @CachePut(value = "Employee", key = "#id") + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + @CachePut(value = "Employee", key = "#id") + public Employee updateEmployee(Long id, Employee employee) { + Employee employeeToUpdate = this.employeeRepository.findById(id) + .orElseThrow(() -> new EmployeeNotFoundException("employee not found")); + employeeToUpdate.setFirstName(employee.getFirstName()); + employeeToUpdate.setLastName(employee.getLastName()); + employeeToUpdate.setCareer(employee.getCareer()); + return this.employeeRepository.save(employeeToUpdate); + } +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..1dec06e7 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public ResponseEntity> getAllEmployee() { + return ResponseEntity.ok(this.employeeService.getAllEmployee()); + } + + @GetMapping("/employee/{id}") + public ResponseEntity getEmployee(@PathVariable("id") Long id) { + return ResponseEntity.ok(this.employeeService.getEmployee(id)); + } + + @DeleteMapping("/employee/{id}") + public ResponseEntity removeEmployee(@PathVariable("id") Long id) { + return ResponseEntity.ok(this.employeeService.removeEmployee(id)); + } + + @PostMapping("/employee") + public ResponseEntity saveEmployee(@RequestBody Employee employee) { + return ResponseEntity.status(201).body(this.employeeService.saveEmployee(employee)); + } + + @PutMapping("/employee/{id}") + public ResponseEntity updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return ResponseEntity.status(202).body(this.employeeService.updateEmployee(id, employee)); + } + +} diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/application.properties b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/application.properties new file mode 100644 index 00000000..2485aaff --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/application.properties @@ -0,0 +1,27 @@ + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +spring.jpa.properties.hibernate.show_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true +spring.jpa.properties.hibernate.format_sql=true + +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type=TRACE + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true + + +spring.redis.host=localhost +spring.redis.port=6379 + +spring.cache.type=redis +spring.cache.redis.cache-null-values=true +#spring.cache.redis.time-to-live=40000 + diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/data.sql b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-h2-redis-cache-example/src/test/java/com/espark/adarsh/SpringbootRedisCacheApplicationTests.java b/APPLICATIONS/springboot-h2-redis-cache-example/src/test/java/com/espark/adarsh/SpringbootRedisCacheApplicationTests.java new file mode 100644 index 00000000..589a9fe4 --- /dev/null +++ b/APPLICATIONS/springboot-h2-redis-cache-example/src/test/java/com/espark/adarsh/SpringbootRedisCacheApplicationTests.java @@ -0,0 +1,120 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.shaded.org.hamcrest.CoreMatchers; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@Testcontainers +@RunWith(SpringRunner.class) +@AutoConfigureMockMvc +@SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class SpringbootRedisCacheApplicationTests { + + + @Container + public static GenericContainer container = new GenericContainer("redis:latest") + .withExposedPorts(6379); + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("spring.redis.host", container::getContainerIpAddress); + registry.add("spring.redis.port", container::getFirstMappedPort); + } + + @Autowired + EmployeeService employeeService; + + @Autowired + private MockMvc mockMvc; + + @Test + void testGetAllEmployee() throws Exception { + Employee employeeAdmin = new Employee(10l, "admin", "admin", "admin"); + Employee employeeUser = new Employee(20l, "user", "user", "user"); + employeeService.saveEmployee(employeeAdmin); + employeeService.saveEmployee(employeeUser); + mockMvc.perform(MockMvcRequestBuilders + .get("/employees") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.[*]").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.[*].id").isNotEmpty()); + } + + @Test + void testGetEmployee() throws Exception { + Employee employeeAdmin = new Employee(10l, "admin", "admin", "admin"); + Employee employeeUser = new Employee(20l, "user", "user", "user"); + employeeService.saveEmployee(employeeAdmin); + employeeService.saveEmployee(employeeUser); + + mockMvc.perform(MockMvcRequestBuilders + .get("/employee/{id}", 1) + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.*").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } + + @Test + void testSaveEmployee() throws Exception { + Employee employeeAdmin = new Employee(10l, "admin", "admin", "admin"); + mockMvc.perform(MockMvcRequestBuilders + .post("/employee") + .content(new ObjectMapper().writeValueAsString((employeeAdmin))) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(10)); + } + + @Test + void testUpdateEmployee() throws Exception { + Employee employeeAdmin = new Employee(1l, "admin", "admin", "admin"); + mockMvc.perform(MockMvcRequestBuilders + .put("/employee/{id}", 1) + .content(new ObjectMapper().writeValueAsString((employeeAdmin))) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) + .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("admin")) + .andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("admin")) + .andExpect(MockMvcResultMatchers.jsonPath("$.career").value("admin")); + } + + + @Test + public void deleteEmployeeAPI() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete("/employee/{id}", 1)) + .andExpect(status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)); + } + +} diff --git a/APPLICATIONS/springboot-haproxy/.dockerignore b/APPLICATIONS/springboot-haproxy/.dockerignore new file mode 100644 index 00000000..39ea0ef3 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/.dockerignore @@ -0,0 +1,4 @@ +/kubernates/ +/README.md +/config +/server.* \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/.gitignore b/APPLICATIONS/springboot-haproxy/.gitignore new file mode 100644 index 00000000..b1cc65d4 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/.gitignore @@ -0,0 +1,34 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +/log/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-haproxy/Dockerfile b/APPLICATIONS/springboot-haproxy/Dockerfile new file mode 100644 index 00000000..d90dcdca --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8 +MAINTAINER adarsh.kumar@gmail.com +COPY target/springboot-haproxy.jar springboot-haproxy.jar +ENTRYPOINT ["java","-jar","springboot-haproxy.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/README.md b/APPLICATIONS/springboot-haproxy/README.md new file mode 100644 index 00000000..96c7612f --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/README.md @@ -0,0 +1,105 @@ +# SPRING BOOT LOG SAMPLE + +### build the code +* $ mvn clean package +* $ mvn spring-boot:run +* $ java -jar target/springboot-haproxy.jar + +### To Execute all server +* sh servers.sh +* sh servers-stop.sh + + +### Manually install in Mac +```` +### To install +$ brew update +$ brew install haproxy + +### To start ther server +$ sudo haproxy -f ./config/standalone/etc/haproxy/haproxy.cfg + +### Service test +http://localhost/actuator/env +http://localhost/actuator/info +http://localhost/actuator/beans +http://localhost/actuator/metrics +http://localhost/actuator/health + +### for admin ui +http://localhost:9999/stats + +### To kill process on port 80 + $ sudo lsof -i tcp:80 + $ kill -9 + +### To unstall +$ brew uninstall haproxy + +```` + +```` +frontend: defines a reverse proxy which will listen for incoming requests on a specific IP address and port. +backend: defines a pool of servers that the frontend will forward requests to. +listen: a shorthand notation that combines frontend and backend features into a single command. + +```` + + +### To Execute ha proxy +* $ docker run --name espark-haproxy -p80:80 -v $(pwd)/config/docker/etc/haproxy:/usr/local/etc/haproxy:ro haproxy + +### To view docker logs +* $ docker logs --follow espark-haproxy + +### To stop the container +* $ docker stop espark-haproxy + +* docker ps -a +* docker container rm + +### To reload config file +* docker kill -s HUP espark-haproxy + + +### TO BUILD & RUN TFS API SERVER VIA DOCKER +* $ docker build -f Dockerfile -t springboot-haproxy . +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 8081:8081 -t springboot-haproxy +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 8082:8082 -t springboot-haproxy +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 8083:8083 -t springboot-haproxy +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 8084:8084 -t springboot-haproxy + +### to debug the logs of the docker container +* $ docker ps -a +* $ docker exec -it cat /var/[docker-container-file-system-path]]/logs/application.log > $HOME/spring.log [host-machine-file-system ] +* $ docker exec -it friendly_boyd cat /var/logs/application.log > $HOME/spring.log + + +### FOR DIRECTLY PRODUCING LOGS TO HOST MACHINE RATHER THEN THE DOCKER CONTAINER +* $ docker run -v /path/on/host:/path/in/container +* $ docker container run -p 8080:8080 -v $HOME/log:/var/logs springboot-haproxy + +### To ssh to the container +* $ docker ps -a +* $ docker exec -it [container-name] /bin/bash + +---- +### DOCKER COMPOSE TESTING +* $ docker-compose up +* $ docker-compose down + +### FOR TESTING +* http://localhost/actuator/health +* http://localhost/actuator/info +* http://localhost/actuator/env +* http://localhost/actuator/beans +* http://localhost/actuator/metrics + +### TO DELETE ALL THE CONTAINERS WITH VOLUMES +* $ docker rm -vf $(docker ps -a -q) +### TO DELETE ALL THE IMAGES +* $ docker rmi -f $(docker images -a -q) + +---- + + diff --git a/APPLICATIONS/springboot-haproxy/config/docker/etc/haproxy/haproxy.cfg b/APPLICATIONS/springboot-haproxy/config/docker/etc/haproxy/haproxy.cfg new file mode 100644 index 00000000..f67ac852 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/config/docker/etc/haproxy/haproxy.cfg @@ -0,0 +1,38 @@ +#HA Proxy Config +# http:localhost:9999/stats +global + daemon + maxconn 256 + +defaults + mode http + log global + timeout connect 5000ms + timeout client 50000ms + timeout server 50000ms + +listen stats + bind *:9999 + stats enable + stats hide-version + stats uri /stats + stats auth admin:admin + +frontend springboot + bind *:80 + mode http + use_backend springboot_api_server + +backend springboot_api_server + mode http + balance roundrobin + option forwardfor + http-request set-header X-Forwarded-Port %[dst_port] + http-request add-header X-Forwarded-Proto https if { ssl_fc } + option httpchk GET /actuator/health HTTP/1.1\r\nHost:localhost + http-check expect status 200 + default-server inter 90s fall 3 + server springboot_api1 springboot-haproxy1:8080 check + server springboot_api2 springboot-haproxy2:8080 check + server springboot_api3 springboot-haproxy3:8080 check + server springboot_api4 springboot-haproxy4:8080 check diff --git a/APPLICATIONS/springboot-haproxy/config/standalone/etc/haproxy/haproxy.cfg b/APPLICATIONS/springboot-haproxy/config/standalone/etc/haproxy/haproxy.cfg new file mode 100644 index 00000000..dc827f45 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/config/standalone/etc/haproxy/haproxy.cfg @@ -0,0 +1,37 @@ +#HA Proxy Config +# http:localhost:9999/stats +global + daemon + maxconn 256 + +defaults + mode http + log global + timeout connect 5000ms + timeout client 50000ms + timeout server 50000ms + +listen stats + bind *:9999 + stats enable + stats hide-version + stats uri /stats + stats auth admin:admin + +frontend springboot + bind *:80 + mode http + use_backend springboot_api_server + +backend springboot_api_server + mode http + balance roundrobin + option forwardfor + http-request set-header X-Forwarded-Port %[dst_port] + http-request add-header X-Forwarded-Proto https if { ssl_fc } + option httpchk GET /actuator/health HTTP/1.1\r\nHost:localhost + http-check expect status 200 + server springboot_api1 localhost:8081 check + server springboot_api2 localhost:8082 check + server springboot_api3 localhost:8083 check + server springboot_api4 localhost:8084 check diff --git a/APPLICATIONS/springboot-haproxy/docker-compose.yml b/APPLICATIONS/springboot-haproxy/docker-compose.yml new file mode 100644 index 00000000..021519d1 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/docker-compose.yml @@ -0,0 +1,70 @@ +version: '3' +services: + + springboot-haproxy1: + container_name: springboot-haproxy1 + build: + context: ./ + dockerfile: Dockerfile + restart: on-failure:5 + ports: + - '8081:8081' + networks: + - spring-ms + + springboot-haproxy2: + container_name: springboot-haproxy2 + build: + context: ./ + dockerfile: Dockerfile + restart: on-failure:5 + ports: + - '8082:8082' + networks: + - spring-ms + + springboot-haproxy3: + container_name: springboot-haproxy3 + build: + context: ./ + dockerfile: Dockerfile + restart: on-failure:5 + ports: + - '8083:8083' + networks: + - spring-ms + + springboot-haproxy4: + container_name: springboot-haproxy4 + build: + context: ./ + dockerfile: Dockerfile + restart: on-failure:5 + ports: + - '8084:8084' + networks: + - spring-ms + + haproxy: + image: haproxy + container_name: haproxy + ports: + - 80:80 + - 9999:9999 + volumes: + - ./config/docker/etc/haproxy:/usr/local/etc/haproxy:ro + depends_on: + - springboot-haproxy1 + - springboot-haproxy2 + - springboot-haproxy3 + - springboot-haproxy4 + links: + - springboot-haproxy1 + - springboot-haproxy2 + - springboot-haproxy3 + - springboot-haproxy4 + networks: + - spring-ms + +networks: + spring-ms: \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/pom.xml b/APPLICATIONS/springboot-haproxy/pom.xml new file mode 100644 index 00000000..df9825e0 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.espark.adarsh + springboot-haproxy + 0.0.1-SNAPSHOT + springboot-haproxy + Demo project for Spring Boot + + + 1.8 + Hoxton.SR6 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-haproxy/servers-stop.sh b/APPLICATIONS/springboot-haproxy/servers-stop.sh new file mode 100644 index 00000000..46942b94 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/servers-stop.sh @@ -0,0 +1,16 @@ +#!/bin/bash +procs=`ps aux | grep "springboot-haproxy" | awk '{print $2}'` + +for i in $procs +do + `sudo kill $i` +done + +procs=`ps aux | grep "haproxy" | awk '{print $2}'` + +for i in $procs +do + `sudo kill $i` +done + +echo "server stopped" \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/servers.sh b/APPLICATIONS/springboot-haproxy/servers.sh new file mode 100644 index 00000000..79eff492 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/servers.sh @@ -0,0 +1,6 @@ +#!/bin/bash +nohup java -jar -Dserver.port=8081 target/springboot-haproxy.jar > ./log/log8081.log & +nohup java -jar -Dserver.port=8082 target/springboot-haproxy.jar > ./log/log8082.log & +nohup java -jar -Dserver.port=8083 target/springboot-haproxy.jar > ./log/log8083.log & +nohup java -jar -Dserver.port=8084 target/springboot-haproxy.jar > ./log/log8084.log & +echo "server started "& \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/LogsApplication.java b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/LogsApplication.java new file mode 100644 index 00000000..a1c4c311 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/LogsApplication.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@Slf4j +@SpringBootApplication +public class LogsApplication { + + public static void main(String[] args) { + SpringApplication.run(LogsApplication.class, args); + log.info("label=LogsApplication main()"); + } + +} diff --git a/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerConfiguration.java b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerConfiguration.java new file mode 100644 index 00000000..3089a3c8 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerConfiguration.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Slf4j +@Configuration +public class RequestHandlerConfiguration implements WebMvcConfigurer { + + @Autowired + RequestHandlerInterceptor interceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + log.debug("label=RequestHandlerConfiguration addInterceptors()"); + InterceptorRegistration interceptorRegistration = registry.addInterceptor(interceptor); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerInterceptor.java b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerInterceptor.java new file mode 100644 index 00000000..30a26884 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/src/main/java/com/espark/adarsh/config/RequestHandlerInterceptor.java @@ -0,0 +1,23 @@ +/** + * + */ +package com.espark.adarsh.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Slf4j +@Component +public class RequestHandlerInterceptor implements HandlerInterceptor { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + log.debug("label=RequestHandlerInterceptor preHandle() requestUrl={},requestMethod={}, requestHeader={} ", + request.getRequestURL(), request.getMethod(), request.getHeaderNames()); + return true; + } +} diff --git a/APPLICATIONS/springboot-haproxy/src/main/resources/application.yaml b/APPLICATIONS/springboot-haproxy/src/main/resources/application.yaml new file mode 100644 index 00000000..9d751812 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/src/main/resources/application.yaml @@ -0,0 +1,43 @@ + +server: + port: 8080 + +spring: + application: + name: springboot-haproxy + +info: + app: + name: springboot-haproxy + description: springboot-haproxy + version: 1.0.0 + +management: + endpoints: + web: + exposure: + include: "*" + info: + enabled: true + health: + enabled: true + env: + enabled: true + security: + enabled: false + +logging: + level: + root: INFO + com.espark.adarsh: DEBUG + org.springframework.web: INFO + group: + com.espark.adarsh: DEBUG + org.springframework.web: INFO + file: + name: /var/logs/application.log + max-size: 1MB + max-history: 10 + pattern: + rolling-file-name: ${LOG_FILE}.%d{yyyy-MM-dd}.%i.zip + level: '${spring.application.name} - [%X{traceId}/%X{spanId}] %X{sessionId} %-5p [%t] %C{2} - %m%n' diff --git a/APPLICATIONS/springboot-haproxy/src/test/java/com/espark/adarsh/LogsApplicationTests.java b/APPLICATIONS/springboot-haproxy/src/test/java/com/espark/adarsh/LogsApplicationTests.java new file mode 100644 index 00000000..b1b15601 --- /dev/null +++ b/APPLICATIONS/springboot-haproxy/src/test/java/com/espark/adarsh/LogsApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class LogsApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-hibrenate-plugin/.gitignore b/APPLICATIONS/springboot-hibrenate-plugin/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/MavenWrapperDownloader.java b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..e76d1f32 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..2cc7d4a5 Binary files /dev/null and b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..642d572c --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/APPLICATIONS/springboot-hibrenate-plugin/document/help.txt b/APPLICATIONS/springboot-hibrenate-plugin/document/help.txt new file mode 100644 index 00000000..e289d3bb --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/document/help.txt @@ -0,0 +1,6 @@ + +copy the mysql or driver class jar from the m2 dir of the user.home +got to userhome dir then +cmd+shift + . to show the hidden dir .m2 + +jdbc:mysql://localhost:3306/dbname?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/mvnw b/APPLICATIONS/springboot-hibrenate-plugin/mvnw new file mode 100644 index 00000000..a16b5431 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/APPLICATIONS/springboot-hibrenate-plugin/mvnw.cmd b/APPLICATIONS/springboot-hibrenate-plugin/mvnw.cmd new file mode 100644 index 00000000..c8d43372 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/APPLICATIONS/springboot-hibrenate-plugin/pom.xml b/APPLICATIONS/springboot-hibrenate-plugin/pom.xml new file mode 100644 index 00000000..032d97b6 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-hibrenate-plugin + 0.0.1-SNAPSHOT + springboot-jpa-inellj-plugin + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/SpringbootJpaInelljPluginApplication.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/SpringbootJpaInelljPluginApplication.java new file mode 100644 index 00000000..7080aff5 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/SpringbootJpaInelljPluginApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootJpaInelljPluginApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootJpaInelljPluginApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/abc.txt b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/abc.txt new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/HibernateSequence.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/HibernateSequence.java new file mode 100644 index 00000000..533c347d --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/HibernateSequence.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +@Table(name = "hibernate_sequence") +@Data +@Entity +public class HibernateSequence implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "next_val") + private Long nextVal; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthAccessToken.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthAccessToken.java new file mode 100644 index 00000000..77a4d254 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthAccessToken.java @@ -0,0 +1,42 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; + +[B; + +@Data +@Entity +@Table(name = "oauth_access_token") +public class OauthAccessToken implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "authentication") + private byte[] authentication; + + @Id + @Column(insertable = false, name = "authentication_id", nullable = false) + private String authenticationId; + + @Column(name = "client_id") + private String clientId; + + @Column(name = "refresh_token") + private String refreshToken; + + @Column(name = "token") + private byte[] token; + + @Column(name = "token_id") + private String tokenId; + + @Column(name = "user_name") + private String userName; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthApprovals.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthApprovals.java new file mode 100644 index 00000000..ad7db122 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthApprovals.java @@ -0,0 +1,36 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; +import java.sql.Timestamp; + +@Table(name = "oauth_approvals") +@Data +@Entity +public class OauthApprovals implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "clientId") + private String clientId; + + @Column(name = "expiresAt") + private Timestamp expiresAt; + + @Column(name = "lastModifiedAt") + private Timestamp lastModifiedAt; + + @Column(name = "scope") + private String scope; + + @Column(name = "status") + private String status; + + @Column(name = "userId") + private String userId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientDetails.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientDetails.java new file mode 100644 index 00000000..1f86fcac --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientDetails.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; + +@Data +@Table(name = "oauth_client_details") +@Entity +public class OauthClientDetails implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "access_token_validity") + private Integer accessTokenValidity; + + @Column(name = "additional_information") + private String additionalInformation; + + @Column(name = "authorities") + private String authorities; + + @Column(name = "authorized_grant_types") + private String authorizedGrantTypes; + + @Column(name = "autoapprove") + private String autoapprove; + + @Id + @Column(insertable = false, name = "client_id", nullable = false) + private String clientId; + + @Column(name = "client_secret", nullable = false) + private String clientSecret; + + @Column(name = "refresh_token_validity") + private Integer refreshTokenValidity; + + @Column(name = "resource_ids") + private String resourceIds; + + @Column(name = "scope") + private String scope; + + @Column(name = "web_server_redirect_uri") + private String webServerRedirectUri; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientToken.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientToken.java new file mode 100644 index 00000000..b5bd2b02 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthClientToken.java @@ -0,0 +1,34 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; + +@Entity +@Table(name = "oauth_client_token") +@Data +public class OauthClientToken implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(insertable = false, name = "authentication_id", nullable = false) + private String authenticationId; + + @Column(name = "client_id") + private String clientId; + + @Column(name = "token") + private byte[] token; + + @Column(name = "token_id") + private String tokenId; + + @Column(name = "user_name") + private String userName; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthCode.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthCode.java new file mode 100644 index 00000000..1936dfb6 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthCode.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + + +@Table(name = "oauth_code") +@Data +@Entity +public class OauthCode implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "authentication") + private byte[] authentication; + + @Column(name = "code") + private String code; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthRefreshToken.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthRefreshToken.java new file mode 100644 index 00000000..3cc8de86 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/OauthRefreshToken.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + + +@Data +@Entity +@Table(name = "oauth_refresh_token") +public class OauthRefreshToken implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "authentication") + private byte[] authentication; + + @Column(name = "token") + private byte[] token; + + @Column(name = "token_id") + private String tokenId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Permission.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Permission.java new file mode 100644 index 00000000..315411e3 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Permission.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Data +@Entity +@Table(name = "permission") +public class Permission implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", insertable = false, nullable = false) + private Integer id; + + @Column(name = "name") + private String name; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/PermissionRole.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/PermissionRole.java new file mode 100644 index 00000000..93fb2d6d --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/PermissionRole.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +@Table(name = "permission_role") +@Entity +@Data +public class PermissionRole implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "permission_id") + private Integer permissionId; + + @Column(name = "role_id") + private Integer roleId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Role.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Role.java new file mode 100644 index 00000000..fabf5672 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/Role.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Table(name = "role") +@Entity +@Data +public class Role implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", insertable = false, nullable = false) + private Integer id; + + @Column(name = "name") + private String name; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/RoleUser.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/RoleUser.java new file mode 100644 index 00000000..96bcf2d8 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/RoleUser.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +@Table(name = "role_user") +@Data +@Entity +public class RoleUser implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "role_id") + private Integer roleId; + + @Column(name = "user_id") + private Integer userId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/User.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/User.java new file mode 100644 index 00000000..11f5e0cd --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/entites/User.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.espark.entites; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Table(name = "user") +@Entity +@Data +public class User implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "accountNonExpired", nullable = false) + private Integer accountNonExpired; + + @Column(name = "accountNonLocked", nullable = false) + private Integer accountNonLocked; + + @Column(name = "credentialsNonExpired", nullable = false) + private Integer credentialsNonExpired; + + @Column(name = "email", nullable = false) + private String email; + + @Column(name = "enabled", nullable = false) + private Integer enabled; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", insertable = false, nullable = false) + private Integer id; + + @Column(name = "password", nullable = false) + private String password; + + @Column(name = "username", nullable = false) + private String username; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/HibernateSequenceRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/HibernateSequenceRepository.java new file mode 100644 index 00000000..19cda2f4 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/HibernateSequenceRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.HibernateSequence; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface HibernateSequenceRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthAccessTokenRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthAccessTokenRepository.java new file mode 100644 index 00000000..4410de79 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthAccessTokenRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthAccessToken; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthAccessTokenRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthApprovalsRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthApprovalsRepository.java new file mode 100644 index 00000000..67cec434 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthApprovalsRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthApprovals; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthApprovalsRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientDetailsRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientDetailsRepository.java new file mode 100644 index 00000000..3c392ab5 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientDetailsRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthClientDetails; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthClientDetailsRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientTokenRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientTokenRepository.java new file mode 100644 index 00000000..4cfaf349 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthClientTokenRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthClientToken; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthClientTokenRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthCodeRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthCodeRepository.java new file mode 100644 index 00000000..563d40c0 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthCodeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthCode; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthCodeRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthRefreshTokenRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthRefreshTokenRepository.java new file mode 100644 index 00000000..5564bd84 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/OauthRefreshTokenRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.OauthRefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface OauthRefreshTokenRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRepository.java new file mode 100644 index 00000000..d21b61d3 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.Permission; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface PermissionRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRoleRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRoleRepository.java new file mode 100644 index 00000000..f04ad0ef --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/PermissionRoleRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.PermissionRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface PermissionRoleRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleRepository.java new file mode 100644 index 00000000..383fdfd6 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.Role; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface RoleRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleUserRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleUserRepository.java new file mode 100644 index 00000000..51831d88 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/RoleUserRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.RoleUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface RoleUserRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/UserRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/UserRepository.java new file mode 100644 index 00000000..4e10906f --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/espark/respository/UserRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.espark.respository; + +import com.espark.adarsh.espark.entites.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface UserRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PERMISSION.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PERMISSION.java new file mode 100644 index 00000000..b4fd3b1c --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PERMISSION.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.oauthdb.enitities; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Data +@Table(name = "PERMISSION") +public class PERMISSION implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID", insertable = false, nullable = false) + private Integer ID; + + @Column(name = "NAME") + private String NAME; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PermissionRole.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PermissionRole.java new file mode 100644 index 00000000..fcb05b48 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/PermissionRole.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.oauthdb.enitities; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +@Table(name = "permission_role") +@Data +@Entity +public class PermissionRole implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "PERMISSION_ID") + private Integer permissionId; + + @Column(name = "ROLE_ID") + private Integer roleId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/ROLE.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/ROLE.java new file mode 100644 index 00000000..b76ca524 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/ROLE.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.oauthdb.enitities; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Data +@Table(name = "ROLE") +public class ROLE implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID", insertable = false, nullable = false) + private Integer ID; + + @Column(name = "NAME") + private String NAME; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/RoleUser.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/RoleUser.java new file mode 100644 index 00000000..c3a37ce1 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/RoleUser.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.oauthdb.enitities; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; +import java.io.Serializable; + +@Data +@Table(name = "role_user") +@Entity +public class RoleUser implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "ROLE_ID") + private Integer roleId; + + @Column(name = "USER_ID") + private Integer userId; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/USER.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/USER.java new file mode 100644 index 00000000..00d3ad21 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/enitities/USER.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.oauthdb.enitities; + +import lombok.Data; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Data +@Table(name = "USER") +public class USER implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "ACCOUNT_EXPIRED", nullable = false) + private Boolean accountExpired; + + @Column(name = "ACCOUNT_LOCKED", nullable = false) + private Boolean accountLocked; + + @Column(name = "CREDENTIALS_EXPIRED", nullable = false) + private Boolean credentialsExpired; + + @Column(name = "EMAIL", nullable = false) + private String EMAIL; + + @Column(name = "ENABLED", nullable = false) + private Boolean ENABLED; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID", insertable = false, nullable = false) + private Integer ID; + + @Column(name = "PASSWORD", nullable = false) + private String PASSWORD; + + @Column(name = "USERNAME", nullable = false) + private String USERNAME; + + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PERMISSIONRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PERMISSIONRepository.java new file mode 100644 index 00000000..0dd6cc87 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PERMISSIONRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.oauthdb.respository; + +import com.espark.adarsh.oauthdb.enitities.PERMISSION; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface PERMISSIONRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PermissionRoleRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PermissionRoleRepository.java new file mode 100644 index 00000000..baac438b --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/PermissionRoleRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.oauthdb.respository; + +import com.espark.adarsh.oauthdb.enitities.PermissionRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface PermissionRoleRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/ROLERepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/ROLERepository.java new file mode 100644 index 00000000..7cf6769e --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/ROLERepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.oauthdb.respository; + +import com.espark.adarsh.oauthdb.enitities.ROLE; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface ROLERepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/RoleUserRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/RoleUserRepository.java new file mode 100644 index 00000000..b9d44a9a --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/RoleUserRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.oauthdb.respository; + +import com.espark.adarsh.oauthdb.enitities.RoleUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface RoleUserRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/USERRepository.java b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/USERRepository.java new file mode 100644 index 00000000..deb63398 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/java/com/espark/adarsh/oauthdb/respository/USERRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.oauthdb.respository; + +import com.espark.adarsh.oauthdb.enitities.USER; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +public interface USERRepository extends JpaRepository, JpaSpecificationExecutor { + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/main/resources/application.properties b/APPLICATIONS/springboot-hibrenate-plugin/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-hibrenate-plugin/src/test/java/com/espark/adarsh/SpringbootJpaInelljPluginApplicationTests.java b/APPLICATIONS/springboot-hibrenate-plugin/src/test/java/com/espark/adarsh/SpringbootJpaInelljPluginApplicationTests.java new file mode 100644 index 00000000..ae682784 --- /dev/null +++ b/APPLICATIONS/springboot-hibrenate-plugin/src/test/java/com/espark/adarsh/SpringbootJpaInelljPluginApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootJpaInelljPluginApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-import-selector/.gitignore b/APPLICATIONS/springboot-import-selector/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-import-selector/document/help.txt b/APPLICATIONS/springboot-import-selector/document/help.txt new file mode 100644 index 00000000..73a68df4 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/document/help.txt @@ -0,0 +1,8 @@ +$ mvn clean package +$mvn spring-boot:run + +#based on thie ApplicationConfiguration @EnableConfiguration("remote") value +local +or +remote + diff --git a/APPLICATIONS/springboot-import-selector/pom.xml b/APPLICATIONS/springboot-import-selector/pom.xml new file mode 100644 index 00000000..7a37e3a2 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-import-selector + 0.0.1-SNAPSHOT + springboot-import-selector + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..71f695fc --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,21 @@ +package com.espark.adarsh; + +import com.espark.adarsh.configuration.ApplicationConfiguration; +import com.espark.adarsh.service.ApplicationService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + ApplicationContext context = + new AnnotationConfigApplicationContext( + ApplicationConfiguration.class); + ApplicationService bean = context.getBean(ApplicationService.class); + System.out.println(bean.getMessage()); + } + +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java new file mode 100644 index 00000000..c2322d35 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/bean/ApplicationMessageBean.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.bean; + +public class ApplicationMessageBean { + + String message; + + public ApplicationMessageBean() { + } + + public ApplicationMessageBean(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java new file mode 100644 index 00000000..d7ac54cf --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.configuration; + +import com.espark.adarsh.configuration.annotation.EnableConfiguration; +import com.espark.adarsh.service.ApplicationService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration +@EnableConfiguration("remote") +@PropertySource("classpath:application.properties") +public class ApplicationConfiguration { + + @Bean + public ApplicationService getApplicationService() { + return new ApplicationService(); + } +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/LocalConfiguration.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/LocalConfiguration.java new file mode 100644 index 00000000..57d0e592 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/LocalConfiguration.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.configuration; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class LocalConfiguration { + + @Value("${local.configuration.msg}") + String localConfigurationMessage; + + @Bean + ApplicationMessageBean getApplicationMessageBean() { + return new ApplicationMessageBean(localConfigurationMessage); + } +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/RemoteConfiguration.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/RemoteConfiguration.java new file mode 100644 index 00000000..b0f7218d --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/RemoteConfiguration.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.configuration; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RemoteConfiguration { + + @Value("${remote.configuration.msg}") + String remoteConfigurationMessage; + + @Bean + ApplicationMessageBean getApplicationMessageBean() { + return new ApplicationMessageBean(remoteConfigurationMessage); + } +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/annotation/EnableConfiguration.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/annotation/EnableConfiguration.java new file mode 100644 index 00000000..205b3397 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/annotation/EnableConfiguration.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.configuration.annotation; + +import com.espark.adarsh.configuration.util.ApplicationImportSelector; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Import(ApplicationImportSelector.class) +public @interface EnableConfiguration { + String value() default ""; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/util/ApplicationImportSelector.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/util/ApplicationImportSelector.java new file mode 100644 index 00000000..346e7cee --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/configuration/util/ApplicationImportSelector.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.configuration.util; + +import com.espark.adarsh.configuration.LocalConfiguration; +import com.espark.adarsh.configuration.RemoteConfiguration; +import com.espark.adarsh.configuration.annotation.EnableConfiguration; +import org.springframework.context.annotation.ImportSelector; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.type.AnnotationMetadata; + +public class ApplicationImportSelector implements ImportSelector { + + @Override + public String[] selectImports(AnnotationMetadata importingClassMetadata) { + AnnotationAttributes attributes = AnnotationAttributes.fromMap( + importingClassMetadata.getAnnotationAttributes( + EnableConfiguration.class.getName(), false)); + if ("local".equals(attributes.get("value"))) { + return new String[]{LocalConfiguration.class.getName()}; + } else { + return new String[]{RemoteConfiguration.class.getName()}; + } + } +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/service/ApplicationService.java b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/service/ApplicationService.java new file mode 100644 index 00000000..ae712b03 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/java/com/espark/adarsh/service/ApplicationService.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.ApplicationMessageBean; +import org.springframework.beans.factory.annotation.Autowired; + +public class ApplicationService { + + @Autowired + ApplicationMessageBean applicationMessageBean; + + public String getMessage(){ + return this.applicationMessageBean.getMessage(); + } + +} diff --git a/APPLICATIONS/springboot-import-selector/src/main/resources/application.properties b/APPLICATIONS/springboot-import-selector/src/main/resources/application.properties new file mode 100644 index 00000000..6e18a479 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/main/resources/application.properties @@ -0,0 +1,3 @@ + +local.configuration.msg=hello from local +remote.configuration.msg=hello from remote \ No newline at end of file diff --git a/APPLICATIONS/springboot-import-selector/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-import-selector/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-import-selector/src/test/resources/application.properties b/APPLICATIONS/springboot-import-selector/src/test/resources/application.properties new file mode 100644 index 00000000..b63505c7 --- /dev/null +++ b/APPLICATIONS/springboot-import-selector/src/test/resources/application.properties @@ -0,0 +1,6 @@ + +enable.configuration=local +#enable.configuration=remote + +local.configuration.msg=hello from local +remote.configuration.msg=hello from remote \ No newline at end of file diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/.gitignore b/APPLICATIONS/springboot-inmemo-hazelcast-cache/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/document/help.txt b/APPLICATIONS/springboot-inmemo-hazelcast-cache/document/help.txt new file mode 100644 index 00000000..ea728acb --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/document/help.txt @@ -0,0 +1,9 @@ +http post +localhost:8080/write +{ + "id":"100", + "name":"adarsh kumar" +} + +http get +localhost:8080/read/100 diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/pom.xml b/APPLICATIONS/springboot-inmemo-hazelcast-cache/pom.xml new file mode 100644 index 00000000..f931c875 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-inmemo-hazelcast-cache + 0.0.1-SNAPSHOT + jar + + springboot-inmemo-hazelcast-cache + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-cache + + + com.hazelcast + hazelcast + + + com.hazelcast + hazelcast-spring + + + + org.codehaus.jackson + jackson-smile + 1.9.13 + + + + org.springframework.boot + spring-boot-starter-cache + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..d401d0ce --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,18 @@ +package com.espark.adarsh; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..28cfb35e --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.bean; + +public class Employee { + + private String id; + private String name; + + public Employee() { + } + + public Employee(String id) { + this.id = id; + } + + 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; + } +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java new file mode 100644 index 00000000..ca98ee87 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/ApplicationConfiguration.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.bean.Employee; +import com.hazelcast.config.*; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.spring.cache.HazelcastCacheManager; +import org.springframework.cache.CacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfiguration { + + @Bean + public Config hazelCastConfig(){ + Config config= new Config() + .setInstanceName("hazelcast-instance") + .addMapConfig( + new MapConfig() + .setName("employee") + .setMaxSizeConfig(new MaxSizeConfig(200, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE)) + .setEvictionPolicy(EvictionPolicy.LRU) + .setTimeToLiveSeconds(20)); + + + config.getSerializationConfig().getSerializerConfigs().add( + new SerializerConfig(). + setTypeClass(Employee.class). + setImplementation(new EmployeeSerializer())); + + + /* NetworkConfig network = config.getNetworkConfig(); + network.setPort(5701).setPortCount(20); + network.setPortAutoIncrement(true); + JoinConfig join = network.getJoin(); + join.getMulticastConfig().setEnabled(false); + join.getTcpIpConfig() + .addMember("machine1") + .addMember("localhost").setEnabled(true);*/ + + return config; + } + + /* @Bean + public HazelcastInstance hazelcastInstance() { + return Hazelcast.newHazelcastInstance(hazelCastConfig()); + } + + @Bean + public CacheManager cacheManager() { + return new HazelcastCacheManager(hazelcastInstance()); + } + */ +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/EmployeeSerializer.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/EmployeeSerializer.java new file mode 100644 index 00000000..46a004a3 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/config/EmployeeSerializer.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.bean.Employee; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.nio.ObjectDataInput; +import com.hazelcast.nio.ObjectDataOutput; +import com.hazelcast.nio.serialization.ByteArraySerializer; +import java.io.IOException; +import java.io.InputStream; + +public class EmployeeSerializer implements ByteArraySerializer { + + ObjectMapper mapper = new ObjectMapper(); + + public int getTypeId() { + return 5; + } + + public void write(ObjectDataOutput out, Employee object) + throws IOException { + byte[] data = mapper.writeValueAsBytes(object); + System.out.println("Size is " + data.length); + out.write(data); + } + + public Employee read(ObjectDataInput in) throws IOException { + return mapper.readValue((InputStream) in, + Employee.class); + } + + public void destroy() { + } + + @Override + public byte[] write(Employee employee) throws IOException { + return mapper.writeValueAsBytes(employee); + } + + @Override + public Employee read(byte[] bytes) throws IOException { + return mapper.readValue(bytes, Employee.class); + } +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..f2ae65da --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,57 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.service.CacheService; +import com.hazelcast.core.HazelcastInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + + + +@RestController +public class ApplicationController { + + Logger logger = LoggerFactory.getLogger(getClass()); + + @Autowired + private HazelcastInstance instance; + + @Autowired + private CacheService cacheService; + + + + @RequestMapping(value = "/employee",method = RequestMethod.GET) + public Object getCachedObject(){ +// long start = System.nanoTime(); +// Employee employee = this.cacheService.getData(); +// long end = System.nanoTime(); +// long time = TimeUnit.NANOSECONDS.toMillis(end - start); +// logger.info(time+" "+employee); +// return employee; + return null; + } + + @RequestMapping(value = "/employee",method = RequestMethod.POST) + public void setCachedObject(@RequestBody Employee employee){ + // this.cacheService.setData(employee); + } + + @RequestMapping("/write") + public String write(@RequestBody Employee employee) { + java.util.Map instanceMap = instance.getMap("employee"); // get map from hazel cast + instanceMap.put(employee.getId(),employee); // write value, This value will be accessible from another jvm also + return "Employee has been write to Hazelcast"; + } + + @RequestMapping("/read/{id}") + public Employee read(@PathVariable("id") String id) { + java.util.Map instanceMap = instance.getMap("employee"); // get map from hazel cast + Employee employee= instanceMap.get(id); // read value + return employee; + } + +} + diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java new file mode 100644 index 00000000..9c116f86 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheService.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; + +public interface CacheService { + @CacheEvict(allEntries = true) + void clearCache(); + + @Cacheable(condition = "#employee.getId('100')") + Employee getEmployee(); + + void setEmployee(Employee employee); +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheServiceImpl.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheServiceImpl.java new file mode 100644 index 00000000..9df2e915 --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/java/com/espark/adarsh/service/CacheServiceImpl.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +@Service +@CacheConfig(cacheNames = "employee") +public class CacheServiceImpl implements CacheService{ + + private static Logger log = LoggerFactory.getLogger(CacheServiceImpl.class); + + @CacheEvict(allEntries = true) + @Override + public void clearCache(){} + + @Cacheable("employee") + @Override + public Employee getEmployee() { + return new Employee(); + } + + + @CachePut(value = "employee", key = "#employee + 1") // (2) + public void setEmployee(Employee employee){ + log.info("employee saved ",employee); + } +} diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/application.properties b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/application.properties new file mode 100644 index 00000000..3137553d --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.hazelcast.config=classpath:config/hazelcast.xml \ No newline at end of file diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/hazelcast.xml b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/hazelcast.xml new file mode 100644 index 00000000..691f5f8b --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/main/resources/hazelcast.xml @@ -0,0 +1,13 @@ + + + + + 200 + LFU + 20 + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..7a2139fb --- /dev/null +++ b/APPLICATIONS/springboot-inmemo-hazelcast-cache/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationMainTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-java-modules/.gitignore b/APPLICATIONS/springboot-java-modules/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-java-modules/README.md b/APPLICATIONS/springboot-java-modules/README.md new file mode 100644 index 00000000..157ec7a6 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/README.md @@ -0,0 +1,16 @@ +# SPRINGBOOT-JAVA-MODULES + +> spring boot java 9 modules examaples +--- + +### To Build +* mvn clean package + +### To Run +* mvn spring-boot:run + + +### Application Url +* http://localhost:8080/list +* curl -X GET http://localhost:8080/list + diff --git a/APPLICATIONS/springboot-java-modules/pom.xml b/APPLICATIONS/springboot-java-modules/pom.xml new file mode 100644 index 00000000..a6ee2e1e --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.11.RELEASE + + + com.espark.adarsh + springboot-java-modules + 0.0.1-SNAPSHOT + springboot-java-modules + Demo project for Spring Boot and java 9 modules + + 11 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/SpringbootJavaModulesApplication.java b/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/SpringbootJavaModulesApplication.java new file mode 100644 index 00000000..9b62a496 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/SpringbootJavaModulesApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootJavaModulesApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootJavaModulesApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..cd1c69da --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@RestController +public class ApplicationController { + + @GetMapping("/list") + List getMessages(){ + return Arrays.asList("adarsh", "kumar", "radha", "singh"); + } +} diff --git a/APPLICATIONS/springboot-java-modules/src/main/java/module-info.java b/APPLICATIONS/springboot-java-modules/src/main/java/module-info.java new file mode 100644 index 00000000..56714223 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/src/main/java/module-info.java @@ -0,0 +1,6 @@ +open module springboot.java.modules { + requires spring.web; + requires spring.boot; + requires spring.boot.autoconfigure; + requires com.fasterxml.jackson.databind; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java-modules/src/main/resources/application.properties b/APPLICATIONS/springboot-java-modules/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-java-modules/src/test/java/com/espark/adarsh/SpringbootJavaModulesApplicationTests.java b/APPLICATIONS/springboot-java-modules/src/test/java/com/espark/adarsh/SpringbootJavaModulesApplicationTests.java new file mode 100644 index 00000000..06017ad6 --- /dev/null +++ b/APPLICATIONS/springboot-java-modules/src/test/java/com/espark/adarsh/SpringbootJavaModulesApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = com.espark.adarsh.SpringbootJavaModulesApplication.class) +class SpringbootJavaModulesApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-java9-modules-h2db/.gitignore b/APPLICATIONS/springboot-java9-modules-h2db/.gitignore new file mode 100644 index 00000000..449718a7 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +*.DS_Store +*/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-java9-modules-h2db/README.md b/APPLICATIONS/springboot-java9-modules-h2db/README.md new file mode 100644 index 00000000..5eeb5b8b --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/README.md @@ -0,0 +1,29 @@ +# SPRINGBOOT JAVA9 H2DB MODULE EXAMPLE + +---- + + +### To Build +* mvn clean package + + +### To Run +* mvn spring-boot:run + + +### To Access Application +* http://localhost:8080/employees +* curl -X GET http://localhost:8080/employees + + + ### log into the homepage of db + * http://localhost:8080/h2-console + * username, pwd , db url and db driver class is mentioned in application.properties file + + + ### Maven dependency tree + * mvn dependency:tree -Dverbose + + + ### To View jar content + * jar tvf springboot-web/target/springboot-web-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-modules-h2db/pom.xml b/APPLICATIONS/springboot-java9-modules-h2db/pom.xml new file mode 100644 index 00000000..be764e5c --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.5.1 + + + com.espark.adarsh + springboot-java9-modules-h2db + 0.0.1-SNAPSHOT + springboot-java9-modules-h2db + Demo project for Spring Boot and java9 with h2 db + + 11 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.sun.activation + jakarta.activation + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..57a3e3de --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..dc490612 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,46 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/module-info.java new file mode 100644 index 00000000..e9f363e3 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/java/module-info.java @@ -0,0 +1,22 @@ +module springboot.java9.modules.h2db { + + requires spring.boot; + requires spring.core; + requires spring.beans; + requires spring.context; + requires spring.tx; + requires spring.data.jpa; + requires spring.data.commons; + requires spring.boot.autoconfigure; + requires spring.web; + requires spring.webmvc; + requires java.xml.bind; + requires java.sql; + requires spring.jdbc; + requires java.annotation; + requires java.persistence; + requires com.fasterxml.classmate; + requires com.fasterxml.jackson.core; + requires com.fasterxml.jackson.databind; + opens com.espark.adarsh; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/application.properties b/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/application.properties new file mode 100644 index 00000000..cc398596 --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/application.properties @@ -0,0 +1,12 @@ + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/data.sql b/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-modules-h2db/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-java9-modules-h2db/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..fadfd6ad --- /dev/null +++ b/APPLICATIONS/springboot-java9-modules-h2db/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = com.espark.adarsh.ApplicationMain.class) +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/.gitignore b/APPLICATIONS/springboot-java9-multimodules-h2/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/README.md b/APPLICATIONS/springboot-java9-multimodules-h2/README.md new file mode 100644 index 00000000..12caa0c8 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/README.md @@ -0,0 +1,30 @@ +# SPRING BOOT JAVA9 H2DB MULTI MODULE MAVEN EXAMPLE + +--- + +### To build +* mvn clean package + +### To Run +* mvn install && mvn spring-boot:run -pl espark-web +* cd espark-web + * mvn spring-boot:run +* java -jar espark-web/target/espark-web-0.0.1-SNAPSHOT.jar + +### To Access Application +* http://localhost:8080/employees +* curl -X GET http://localhost:8080/employees +* curl -X GET http://localhost:8080/api/wish + + +### log into the homepage of db +* http://localhost:8080/h2-console +* username, pwd , db url and db driver class is mentioned in application.properties file + + +### Maven dependency tree +* mvn dependency:tree -Dverbose + + +### To View jar content +* jar tvf springboot-web/target/springboot-web-1.0-SNAPSHOT.jar \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/pom.xml b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/pom.xml new file mode 100644 index 00000000..2c1b264c --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/pom.xml @@ -0,0 +1,41 @@ + + + + springboot-java9-multimodules-h2 + com.espark.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + espark-persistence + 0.0.1-SNAPSHOT + espark-persistence + + + 11 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.sun.activation + jakarta.activation + + + + + + com.h2database + h2 + runtime + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java new file mode 100644 index 00000000..8de8d9f9 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.persistence.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java new file mode 100644 index 00000000..0991198b --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.persistence.respository; + +import com.espark.adarsh.persistence.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java new file mode 100644 index 00000000..c99a354d --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.persistence.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/module-info.java new file mode 100644 index 00000000..511097bd --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/java/module-info.java @@ -0,0 +1,22 @@ +module espark.persistence { + + exports com.espark.adarsh.persistence.entity; + exports com.espark.adarsh.persistence.respository; + requires spring.boot; + requires spring.core; + requires org.slf4j; + requires spring.orm; + requires java.annotation; + requires spring.beans; + requires spring.context; + requires spring.data.commons; + requires spring.data.jpa; + requires spring.tx; + requires spring.jdbc; + requires java.sql; + requires com.zaxxer.hikari; + requires spring.boot.autoconfigure; + requires java.persistence; + opens com.espark.adarsh.persistence.service to spring.beans, spring.core; + opens com.espark.adarsh.persistence.entity to org.hibernate.orm.core, spring.core; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/application.properties b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/application.properties new file mode 100644 index 00000000..cc398596 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/application.properties @@ -0,0 +1,12 @@ + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/data.sql b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-persistence/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/pom.xml b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/pom.xml new file mode 100644 index 00000000..8df94fe1 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/pom.xml @@ -0,0 +1,30 @@ + + + + springboot-java9-multimodules-h2 + com.espark.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + espark-services + 0.0.1-SNAPSHOT + espark-services + + + 11 + + + + + com.espark.adarsh + espark-persistence + 0.0.1-SNAPSHOT + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java new file mode 100644 index 00000000..0f93af37 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.persistence.entity.Employee; + +import java.util.List; + +public interface EmployeeService { + + List getAllEmployee(); + + Employee getEmployee(Long id); + + Employee saveEmployee(Employee employee); + + Employee updateEmployee(Long id, Employee employee); +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java new file mode 100644 index 00000000..7dc9554c --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.services.impl; + +import com.espark.adarsh.persistence.entity.Employee; +import com.espark.adarsh.persistence.respository.EmployeeRepository; +import com.espark.adarsh.services.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import java.util.LinkedList; +import java.util.List; + +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Override + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @Override + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id).get(); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @Override + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + @Override + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/module-info.java new file mode 100644 index 00000000..18b05fb0 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-services/src/main/java/module-info.java @@ -0,0 +1,13 @@ +module espark.services { + requires org.slf4j; + requires spring.beans; + requires spring.context; + requires spring.core; + requires java.annotation; + requires spring.boot.autoconfigure; + requires transitive espark.persistence; + exports com.espark.adarsh.services; + exports com.espark.adarsh.services.impl; + + opens com.espark.adarsh.services.impl to spring.core; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/pom.xml b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/pom.xml new file mode 100644 index 00000000..4bf8abca --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/pom.xml @@ -0,0 +1,65 @@ + + + + springboot-java9-multimodules-h2 + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + espark-web + 0.0.1-SNAPSHOT + espark-web + + + 11 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.espark.adarsh + espark-services + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..1ac6f214 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @GetMapping("/wish") + public Map wish() { + return new HashMap<>() { + { + put("name", "adarsh kumar"); + put("msg", "welcome to the application"); + } + }; + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..5bf18436 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.persistence.entity.Employee; +import com.espark.adarsh.services.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id, employee); + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/module-info.java new file mode 100644 index 00000000..af5ae531 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/java/module-info.java @@ -0,0 +1,24 @@ +/** + * + */ +module espark.web { + + requires org.slf4j; + requires spring.web; + requires spring.boot; + requires spring.core; + requires spring.beans; + requires spring.webmvc; + requires net.bytebuddy; + requires spring.context; + requires java.annotation; + requires java.xml.bind; + requires java.instrument; + requires espark.services; + requires com.fasterxml.classmate; + requires spring.boot.autoconfigure; + requires com.fasterxml.jackson.core; + requires com.fasterxml.jackson.databind; + opens com.espark.adarsh; + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/resources/application.properties b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/resources/application.properties new file mode 100644 index 00000000..b0d30bd7 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/main/resources/application.properties @@ -0,0 +1,4 @@ + +spring.logging.level.root=ALL +spring.logging.level.org.springframework=ALL +spring.logging.level.org.springframework.web=DEBUG \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..a7ca394c --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = com.espark.adarsh.ApplicationMain.class) +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-h2/pom.xml b/APPLICATIONS/springboot-java9-multimodules-h2/pom.xml new file mode 100644 index 00000000..238648d3 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-h2/pom.xml @@ -0,0 +1,54 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 2.5.1 + + + 4.0.0 + + com.espark.adarsh + springboot-java9-multimodules-h2 + 0.0.1-SNAPSHOT + + springboot-java9-multimodules-h2 + Demo project for Spring Boot and java 9 multi modules + + + 11 + + + pom + + + espark-persistence + espark-services + espark-web + + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + + + jakarta.activation + jakarta.activation + + + test + + + + diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/.gitignore b/APPLICATIONS/springboot-java9-multimodules-mysql/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/README.md b/APPLICATIONS/springboot-java9-multimodules-mysql/README.md new file mode 100644 index 00000000..b21840e8 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/README.md @@ -0,0 +1,42 @@ +# SPRING BOOT JAVA9 MULTI MODULE MYSQL MAVEN EXAMPLE + +--- + +### To build +* mvn clean package + +### To Run +* mvn install && mvn spring-boot:run -pl espark-web +* cd springboot-web + * mvn spring-boot:run +* java -jar espark-web/target/espark-web-0.0.1-SNAPSHOT.jar + +### To Access Application +* http://localhost:8080/employees +* curl -X GET http://localhost:8080/employees +* curl -X GET http://localhost:8080/api/wish + +-- + +## Mysql Docker Image Operation + +### To list the local docker images +* $ docker images + +### To pull the mysql image to the local +* $ docker pull mysql + +### To run the mysql docker image +* $ docker run --name [mysql-instance-name] -e MYSQL_ROOT_PASSWORD=[root-user-ped] -e MYSQL_DATABASE=[mysql-db-name] -d mysql:[5.6]] +* $ docker run --name espark-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=espark -d mysql:latest + +### Docker container listing +* $ docker container ls + +### Docker process list +* $ docker ps -a + +# to delete docker +$ docker rm -f espark-mysql + + diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/pom.xml b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/pom.xml new file mode 100644 index 00000000..aa9af19d --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/pom.xml @@ -0,0 +1,50 @@ + + + + springboot-java9-multimodules-mysql + com.espark.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + espark-persistence + 0.0.1-SNAPSHOT + + espark-persistence + + + 11 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.sun.activation + jakarta.activation + + + + + + mysql + mysql-connector-java + runtime + + + + + com.zaxxer + HikariCP + 2.6.0 + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java new file mode 100644 index 00000000..8de8d9f9 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.persistence.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java new file mode 100644 index 00000000..0991198b --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.persistence.respository; + +import com.espark.adarsh.persistence.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java new file mode 100644 index 00000000..c99a354d --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.persistence.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/module-info.java new file mode 100644 index 00000000..3eb113bf --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/java/module-info.java @@ -0,0 +1,22 @@ +module espark.persistence { + + exports com.espark.adarsh.persistence.entity; + exports com.espark.adarsh.persistence.respository; + requires spring.boot; + requires spring.core; + requires org.slf4j; + requires spring.orm; + requires java.annotation; + requires spring.beans; + requires spring.context; + requires spring.data.commons; + requires spring.data.jpa; + requires spring.tx; + requires spring.jdbc; + requires java.sql; + requires spring.boot.autoconfigure; + requires java.persistence; + // opens com.espark.adarsh.persistence.entity; + opens com.espark.adarsh.persistence.service to spring.beans, spring.core; + opens com.espark.adarsh.persistence.entity to org.hibernate.orm.core, spring.core; +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/application.yml b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/application.yml new file mode 100644 index 00000000..66547027 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/application.yml @@ -0,0 +1,14 @@ + +spring: + datasource: + url: jdbc:mysql://localhost:3306/espark?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC + username: root + password: root + jpa: + hibernate: + ddl-auto: 'create-drop' + properties: + hibernate: + format-sql: true + generate-ddl: true + show-sql: true \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/data.sql b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/data.sql new file mode 100644 index 00000000..df2bc4db --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-persistence/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; +CREATE TABLE employee ( + id bigint NOT NULL AUTO_INCREMENT, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL, + PRIMARY KEY (id) +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/pom.xml b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/pom.xml new file mode 100644 index 00000000..18f138cf --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/pom.xml @@ -0,0 +1,29 @@ + + + + springboot-java9-multimodules-mysql + com.espark.adarsh + 0.0.1-SNAPSHOT + + + 4.0.0 + espark-services + 0.0.1-SNAPSHOT + espark-services + + + 11 + + + + + com.espark.adarsh + espark-persistence + 0.0.1-SNAPSHOT + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java new file mode 100644 index 00000000..0f93af37 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/EmployeeService.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.persistence.entity.Employee; + +import java.util.List; + +public interface EmployeeService { + + List getAllEmployee(); + + Employee getEmployee(Long id); + + Employee saveEmployee(Employee employee); + + Employee updateEmployee(Long id, Employee employee); +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java new file mode 100644 index 00000000..7dc9554c --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java @@ -0,0 +1,44 @@ +package com.espark.adarsh.services.impl; + +import com.espark.adarsh.persistence.entity.Employee; +import com.espark.adarsh.persistence.respository.EmployeeRepository; +import com.espark.adarsh.services.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import java.util.LinkedList; +import java.util.List; + +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Override + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @Override + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id).get(); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @Override + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + @Override + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/module-info.java new file mode 100644 index 00000000..5afde452 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-services/src/main/java/module-info.java @@ -0,0 +1,15 @@ +module espark.services { + + requires org.slf4j; + requires spring.beans; + requires spring.context; + requires spring.core; + requires java.annotation; + requires spring.boot.autoconfigure; + requires transitive espark.persistence; + exports com.espark.adarsh.services; + exports com.espark.adarsh.services.impl; + + opens com.espark.adarsh.services.impl to spring.core; + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/pom.xml b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/pom.xml new file mode 100644 index 00000000..21aa9e0f --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/pom.xml @@ -0,0 +1,53 @@ + + + + springboot-java9-multimodules-mysql + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + espark-web + 0.0.1-SNAPSHOT + espark-web + + + 11 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.espark.adarsh + espark-services + 0.0.1-SNAPSHOT + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..1ac6f214 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @GetMapping("/wish") + public Map wish() { + return new HashMap<>() { + { + put("name", "adarsh kumar"); + put("msg", "welcome to the application"); + } + }; + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..5bf18436 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.persistence.entity.Employee; +import com.espark.adarsh.services.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id, employee); + } + +} diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/module-info.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/module-info.java new file mode 100644 index 00000000..639ec742 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/java/module-info.java @@ -0,0 +1,21 @@ +module espark.web { + + requires org.slf4j; + requires spring.web; + requires spring.boot; + requires spring.core; + requires spring.beans; + requires spring.webmvc; + requires net.bytebuddy; + requires spring.context; + requires java.annotation; + requires java.xml.bind; + requires java.instrument; + requires espark.services; + requires com.fasterxml.classmate; + requires spring.boot.autoconfigure; + requires com.fasterxml.jackson.core; + requires com.fasterxml.jackson.databind; + opens com.espark.adarsh; + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/resources/application.properties b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/resources/application.properties new file mode 100644 index 00000000..11298f5d --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/main/resources/application.properties @@ -0,0 +1,3 @@ + +spring.logging.level.root=ALL +spring.logging.level.org.springframework=ALL \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..58758163 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/espark-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +//@SpringBootTest(classes = com.espark.adarsh.ApplicationMain.class) +class ApplicationMainTests { + + // @Test + void contextLoads() { + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-java9-multimodules-mysql/pom.xml b/APPLICATIONS/springboot-java9-multimodules-mysql/pom.xml new file mode 100644 index 00000000..f1085358 --- /dev/null +++ b/APPLICATIONS/springboot-java9-multimodules-mysql/pom.xml @@ -0,0 +1,56 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 2.5.0 + + + + 4.0.0 + pom + + + espark-persistence + espark-services + espark-web + + + com.espark.adarsh + springboot-java9-multimodules-mysql + 0.0.1-SNAPSHOT + + springboot-java9-multimodules-mysql + Demo project for Spring Boot and java 9 multi modules + + + 11 + + + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/.gitignore b/APPLICATIONS/springboot-jelasticsearch-restclient/.gitignore new file mode 100644 index 00000000..7f1963e1 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/.gitignore @@ -0,0 +1,29 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +.idea/* + +*/target/** + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +.idea/ +demo.iml diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/Dockerfile b/APPLICATIONS/springboot-jelasticsearch-restclient/Dockerfile new file mode 100644 index 00000000..46744f7d --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/Dockerfile @@ -0,0 +1,6 @@ +FROM frolvlad/alpine-oraclejdk8:slim +VOLUME /tmp +ADD target/springboot-jelasticsearch-restclient-0.0.1-SNAPSHOT.jar app.jar +RUN sh -c 'touch /app.jar' +ENV JAVA_OPTS="" +ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/docker-compose.yml b/APPLICATIONS/springboot-jelasticsearch-restclient/docker-compose.yml new file mode 100644 index 00000000..8bc0b8e2 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/docker-compose.yml @@ -0,0 +1,93 @@ +version: '2.2' +services: + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2 + container_name: elasticsearch + environment: + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + - http.cors.enabled=true + - http.cors.allow-origin=* + - discovery.zen.minimum_master_nodes=2 + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - esdata1:/usr/share/elasticsearch/data + ports: + - 9200:9200 + networks: + - esnet + + elasticsearch2: + image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2 + container_name: elasticsearch2 + environment: + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + - "discovery.zen.ping.unicast.hosts=elasticsearch" + - http.cors.enabled=true + - http.cors.allow-origin=* + - discovery.zen.minimum_master_nodes=2 + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - esdata2:/usr/share/elasticsearch/data + networks: + - esnet + + elasticsearch3: + image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2 + container_name: elasticsearch3 + environment: + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + - "discovery.zen.ping.unicast.hosts=elasticsearch" + - http.cors.enabled=true + - http.cors.allow-origin=* + - discovery.zen.minimum_master_nodes=2 + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - esdata3:/usr/share/elasticsearch/data + networks: + - esnet + + kibana: + image: 'docker.elastic.co/kibana/kibana:6.4.2' + container_name: kibana + environment: + SERVER_NAME: kibana.local + ELASTICSEARCH_URL: http://elasticsearch:9200 + ports: + - '5601:5601' + networks: + - esnet + + headPlugin: + image: 'mobz/elasticsearch-head:5' + container_name: head + ports: + - '9100:9100' + networks: + - esnet + +volumes: + esdata1: + driver: local + esdata2: + driver: local + esdata3: + driver: local + +networks: + esnet: + driver: bridge \ No newline at end of file diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/document/create docker-compose.yml b/APPLICATIONS/springboot-jelasticsearch-restclient/document/create docker-compose.yml new file mode 100644 index 00000000..f4e8e170 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/document/create docker-compose.yml @@ -0,0 +1,52 @@ +version: '2' +services: + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:5.2.2 + volumes: + - esdata1:/usr/share/elasticsearch/data + networks: + - elknet + ports: + - "9200:9200" + - "9300:9300" + environment: + - cluster.name=es-cluster + - "xpack.security.enabled=false" + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + mem_limit: 1g + cap_add: + - IPC_LOCK + elasticsearch2: + image: docker.elastic.co/elasticsearch/elasticsearch:5.2.2 + volumes: + - esdata2:/usr/share/elasticsearch/data + networks: + - elknet + ports: + - "9201:9200" + - "9301:9300" + environment: + - cluster.name=es-cluster + - "discovery.zen.ping.unicast.hosts=elasticsearch" + - "xpack.security.enabled=false" + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + mem_limit: 1g + cap_add: + - IPC_LOCK + kibana: + image: docker.elastic.co/kibana/kibana:5.2.2 + networks: + - elknet + ports: + - "9400:5601" + environment: + SERVER_NAME: localhost + ELASTICSEARCH_URL: http://elasticsearch2:9200 + XPACK_SECURITY_ENABLED: "false" + depends_on: + - "elasticsearch" +volumes: + esdata1: + esdata2: \ No newline at end of file diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/document/docker-compose.yml b/APPLICATIONS/springboot-jelasticsearch-restclient/document/docker-compose.yml new file mode 100644 index 00000000..2c08315f --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/document/docker-compose.yml @@ -0,0 +1,45 @@ +version: '3' +services: + + # https://www.docker.elastic.co/ + + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2 + restart: always + #network_mode: host + ports: + - "9200:9200" + - "9300:9300" + volumes: + - esdata:/usr/share/elasticsearch/data + environment: + - discovery.type=single-node + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "xpack.security.enabled=false" + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + networks: + - elk-network + + kibana: + image: docker.elastic.co/kibana/kibana:6.4.2 + restart: always + #network_mode: host + ports: + - "5601:5601" + environment: + ELASTICSEARCH_URL: http://elasticsearch:9200 + depends_on: + - elasticsearch + networks: + - elk-network + + +# Must be mounted like this or else permission aren't correct +volumes: + esdata: + driver: local + +networks: + elk-network: + driver: bridge \ No newline at end of file diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/document/help.txt b/APPLICATIONS/springboot-jelasticsearch-restclient/document/help.txt new file mode 100644 index 00000000..f18950b2 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/document/help.txt @@ -0,0 +1,94 @@ +$ mvn clean package + +$ docker-compose up + +$ java -jar target/springboot-jelasticsearch-restclient-0.0.1-SNAPSHOT.jar + +#To Vew the health of the nodes +$ curl http://localhost:9200/_cluster/health?pretty + + +POST +$ curl -d '{"id":100,"name":"adarsh Kumar"}' -H "Content-Type: application/json" -X POST http://localhost:8080/person + +GET +$ curl -X GET http://localhost:8080/person/100 + +PUT +$ curl -d '{"id":100,"name":"adarsh Kumar Singh"}' -H "Content-Type: application/json" -X PUT http://localhost:8080/person/100 + +GET +$ curl -X GET http://localhost:8080/persons + +DELETE +$ curl -X DELETE http://localhost:8080/person/100 + + +# Elasticsearch is running at + http://localhost:9200, but receives direct communication from Spring via 9300 + +#Kibana is running at +http://localhost:5601 (credentials are elastic/changeme) + +#Elasticsearch head plugin dashboard +http://localhost:9100/ + + +$ docker-compose down + +#To see the cluseter is working +http://localhost:9200/ + +# To list the image in docker +$ docker images + +#To remove the docker +$ docker image rm -f <8e16816b7a1a> + +========================================================================================================================= +$ curl -X PUT "localhost:9200/person/_doc/1?pretty" -H 'Content-Type: application/json' -d'{"id":100,"firstName":"adarsh","lastName":"Kumar"}' +{ + "_index" : "person", + "_type" : "_doc", + "_id" : "1", + "_version" : 1, + "result" : "created", + "_shards" : { + "total" : 2, + "successful" : 2, + "failed" : 0 + }, + "_seq_no" : 0, + "_primary_term" : 1 +} +========================================================================================================================= +$ curl localhost:9200/person/_search?pretty +{ + "took" : 284, + "timed_out" : false, + "_shards" : { + "total" : 5, + "successful" : 5, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : 1, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "person", + "_type" : "_doc", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "id" : 100, + "firstName" : "adarsh", + "lastName" : "Kumar" + } + } + ] + } +} +========================================================================================================================= + diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/document/temp-docker-compose.yml b/APPLICATIONS/springboot-jelasticsearch-restclient/document/temp-docker-compose.yml new file mode 100644 index 00000000..aefae8d1 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/document/temp-docker-compose.yml @@ -0,0 +1,49 @@ +version: '2.2' +services: + es01: + image: docker.elastic.co/elasticsearch/elasticsearch:7.1.1 + container_name: es01 + environment: + - node.name=es01 + - discovery.seed_hosts=es02 + - cluster.initial_master_nodes=es01,es02 + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - esdata01:/usr/share/elasticsearch/data + ports: + - 9200:9200 + networks: + - esnet + es02: + image: docker.elastic.co/elasticsearch/elasticsearch:7.1.1 + container_name: es02 + environment: + - node.name=es02 + - discovery.seed_hosts=es01 + - cluster.initial_master_nodes=es01,es02 + - cluster.name=docker-cluster + - bootstrap.memory_lock=true + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - esdata02:/usr/share/elasticsearch/data + networks: + - esnet + +volumes: + esdata01: + driver: local + esdata02: + driver: local + +networks: + esnet: \ No newline at end of file diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/pom.xml b/APPLICATIONS/springboot-jelasticsearch-restclient/pom.xml new file mode 100644 index 00000000..8a093c5c --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + springboot-jelasticsearch-restclient + springboot-jelasticsearch-restclient + 0.0.1-SNAPSHOT + jar + + springboot-jelasticsearch-restclient + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.elasticsearch + elasticsearch + LATEST + + + + org.projectlombok + lombok + + + + com.google.code.gson + gson + 2.8.5 + + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + LATEST + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.6 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/Application.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/Application.java new file mode 100644 index 00000000..203b430a --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/Application.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/config/ElasticsearchConfig.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/config/ElasticsearchConfig.java new file mode 100644 index 00000000..e8471064 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/config/ElasticsearchConfig.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.config; + +import org.apache.http.HttpHost; + + +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.elasticsearch.client.RestClient; + +import org.elasticsearch.client.RestClientBuilder; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ElasticsearchConfig { + + + @Value("${elasticsearch.host}") + private String host; + + @Value("${elasticsearch.port}") + private int port; + + @Value("${elasticsearch.username}") + private String userName; + + @Value("${elasticsearch.password}") + private String password; + + @Bean(destroyMethod = "close") + public RestHighLevelClient restClient() { + + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(userName, password)); + + RestClientBuilder builder = RestClient.builder(new HttpHost(host, port)) + .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); + + RestHighLevelClient client = new RestHighLevelClient(builder); + + + return client; + + } + + +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/controller/PersonController.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/controller/PersonController.java new file mode 100644 index 00000000..41a95c3e --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/controller/PersonController.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.controller; + + +import com.espark.adarsh.document.Person; +import com.espark.adarsh.service.PersonService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class PersonController { + + @Autowired + private PersonService service; + + + @PostMapping("/person") + public ResponseEntity createPerson(@RequestBody Person person) throws Exception { + return new ResponseEntity(service.createPersonDocument(person), HttpStatus.CREATED); + } + + @PutMapping("/person") + public ResponseEntity updatePerson(@RequestBody Person person) throws Exception { + return new ResponseEntity(service.updatePerson(person), HttpStatus.CREATED); + } + + @GetMapping("/person/{id}") + public Person findById(@PathVariable String id) throws Exception { + return service.findById(id); + } + + @GetMapping("/person") + public List findAll() throws Exception { + return service.findAll(); + } + + @DeleteMapping("/person/{id}") + public String deletePersonDocument(@PathVariable String id) throws Exception { + return service.deletePersonDocument(id); + } + + @GetMapping(value = "/search") + public List search(@RequestParam(value = "technology") String technology) throws Exception { + return service.searchByTechnology(technology); + } + + @GetMapping(value = "/api/v1/profiles/name-search") + public List searchByName(@RequestParam(value = "name") String name) throws Exception { + return service.findPersonByName(name); + } + +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/document/Person.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/document/Person.java new file mode 100644 index 00000000..9c7e9950 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/document/Person.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.document; + +import lombok.Data; + + +@Data +public class Person { + + private String id; + private String name; + + +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/model/Technologies.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/model/Technologies.java new file mode 100644 index 00000000..992f5e8a --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/model/Technologies.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.model; + +import lombok.Data; + +@Data +public class Technologies { + + private String name; + private String yearsOfExperience; + +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/service/PersonService.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/service/PersonService.java new file mode 100644 index 00000000..58cf366e --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/service/PersonService.java @@ -0,0 +1,194 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.document.Person; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.apache.lucene.search.join.ScoreMode; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.delete.DeleteResponse; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.update.UpdateRequest; +import org.elasticsearch.action.update.UpdateResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; + +import org.elasticsearch.index.query.MatchQueryBuilder; +import org.elasticsearch.index.query.Operator; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +import static com.espark.adarsh.util.Constant.INDEX; +import static com.espark.adarsh.util.Constant.TYPE; + +@Service +@Slf4j +public class PersonService { + + + private RestHighLevelClient client; + + + private ObjectMapper objectMapper; + + @Autowired + public PersonService(RestHighLevelClient client, ObjectMapper objectMapper) { + this.client = client; + this.objectMapper = objectMapper; + } + + public String createPersonDocument(Person document) throws Exception { + + UUID uuid = UUID.randomUUID(); + document.setId(uuid.toString()); + + IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, document.getId()) + .source(convertPersonDocumentToMap(document)); + + IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); + return indexResponse.getResult().name(); + } + + public Person findById(String id) throws Exception { + + GetRequest getRequest = new GetRequest(INDEX, TYPE, id); + + GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); + Map resultMap = getResponse.getSource(); + + return convertMapToPersonDocument(resultMap); + + } + + + public String updatePerson(Person document) throws Exception { + + Person resultDocument = findById(document.getId()); + + UpdateRequest updateRequest = new UpdateRequest( + INDEX, + TYPE, + resultDocument.getId()); + + updateRequest.doc(convertPersonDocumentToMap(document)); + UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT); + + return updateResponse + .getResult() + .name(); + + } + + public List findAll() throws Exception { + + + SearchRequest searchRequest = buildSearchRequest(INDEX, TYPE); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + searchSourceBuilder.query(QueryBuilders.matchAllQuery()); + searchRequest.source(searchSourceBuilder); + + SearchResponse searchResponse = + client.search(searchRequest, RequestOptions.DEFAULT); + + return getSearchResult(searchResponse); + } + + + public List findPersonByName(String name) throws Exception { + + + SearchRequest searchRequest = new SearchRequest(); + searchRequest.indices(INDEX); + searchRequest.types(TYPE); + + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + + MatchQueryBuilder matchQueryBuilder = QueryBuilders + .matchQuery("name", name) + .operator(Operator.AND); + + searchSourceBuilder.query(matchQueryBuilder); + + searchRequest.source(searchSourceBuilder); + + SearchResponse searchResponse = + client.search(searchRequest, RequestOptions.DEFAULT); + + return getSearchResult(searchResponse); + + } + + public String deletePersonDocument(String id) throws Exception { + + DeleteRequest deleteRequest = new DeleteRequest(INDEX, TYPE, id); + DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT); + + return response + .getResult() + .name(); + + } + + private Map convertPersonDocumentToMap(Person profileDocument) { + return objectMapper.convertValue(profileDocument, Map.class); + } + + private Person convertMapToPersonDocument(Map map) { + return objectMapper.convertValue(map, Person.class); + } + + + public List searchByTechnology(String technology) throws Exception { + + SearchRequest searchRequest = buildSearchRequest(INDEX, TYPE); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + + QueryBuilder queryBuilder = QueryBuilders + .boolQuery() + .must(QueryBuilders + .matchQuery("technologies.name", technology)); + + searchSourceBuilder.query(QueryBuilders.nestedQuery("technologies", queryBuilder, ScoreMode.Avg)); + + searchRequest.source(searchSourceBuilder); + + SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); + + return getSearchResult(response); + } + + private List getSearchResult(SearchResponse response) { + + SearchHit[] searchHit = response.getHits().getHits(); + + List profileDocuments = new ArrayList<>(); + + for (SearchHit hit : searchHit) { + profileDocuments + .add(objectMapper + .convertValue(hit + .getSourceAsMap(), Person.class)); + } + + return profileDocuments; + } + + private SearchRequest buildSearchRequest(String index, String type) { + + SearchRequest searchRequest = new SearchRequest(); + searchRequest.indices(index); + searchRequest.types(type); + + return searchRequest; + } +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/util/Constant.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/util/Constant.java new file mode 100644 index 00000000..ecd89304 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/java/com/espark/adarsh/util/Constant.java @@ -0,0 +1,7 @@ +package com.espark.adarsh.util; + +public interface Constant { + + String INDEX = "lead"; + String TYPE = "lead"; +} diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/resources/application.properties b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/resources/application.properties new file mode 100644 index 00000000..03142477 --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/main/resources/application.properties @@ -0,0 +1,5 @@ + +elasticsearch.host=localhost +elasticsearch.port=9100 +elasticsearch.username= +elasticsearch.password= diff --git a/APPLICATIONS/springboot-jelasticsearch-restclient/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-jelasticsearch-restclient/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-jelasticsearch-restclient/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/.gitignore b/APPLICATIONS/springboot-jpa-h2-testing/.gitignore new file mode 100644 index 00000000..80a18165 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/.gitignore @@ -0,0 +1,35 @@ +.DS_Store +.mvn +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-jpa-h2-testing/README.md b/APPLICATIONS/springboot-jpa-h2-testing/README.md new file mode 100644 index 00000000..86893a0f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/README.md @@ -0,0 +1,94 @@ +# springboot-jpa-h2-testing + +> unit testing, mock testing and smoke testing of repository, service and controller +--- + +### to build the application +### Docker must be running in local env to build this code +* $ mvn clean package +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +* >username, pwd , dburl and db driver class is mention in application.properties file + +## To test api + +--- + +### To get all the employee +* $ curl localhost:8080/api/employees +``` +[ + { + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" + }, + { + "id": 2, + "firstName": "radha", + "lastName": "singh", + "career": "IT" + }, + { + "id": 3, + "firstName": "sonu", + "lastName": "singh", + "career": "IT" + }, + { + "id": 4, + "firstName": "amit", + "lastName": "kumar", + "career": "Finance" + } +] +``` +### To get only one employee +* $ curl localhost:8080/api/employee/1 +``` +{ + "id": 1, + "firstName": "adarsh", + "lastName": "kumar", + "career": "It" +} +``` + +### To Create a new Employee +* $ curl localhost:8080/api/employee -X POST -H "Content-Type: application/json" -d '{"firstName": "sonu","lastName": "singh","career": "It"}' +* Response +``` +{ + "id": 5, + "firstName": "sonu", + "lastName": "singh", + "career": "It" +} +``` + +### To update a existing Employee +* $ curl localhost:8080/api/employee/5 -X PUT -H "Content-Type: application/json" -d '{"id":5, "firstName": "sonu","lastName": "singh","career": "operation"}' +* Response +``` +{ + "id": 5, + "firstName": "sonu", + "lastName": "singh", + "career": "operation" +} +``` + +### To delete a Employee +* $ curl localhost:8080/api/employee/5 -X DELETE +* Response +``` +{ + "id": 5, + "firstName": "sonu", + "lastName": "singh", + "career": "operation" +} +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/pom.xml b/APPLICATIONS/springboot-jpa-h2-testing/pom.xml new file mode 100644 index 00000000..181cce81 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.2 + + + com.espark.adarsh + springboot-jpa-h2-testing + 0.0.1-SNAPSHOT + springboot-jpa-h2-testing + Springboot He Jpa Testing + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + build-image + + + + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/SpringbootJpaUnittestingApplication.java b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/SpringbootJpaUnittestingApplication.java new file mode 100644 index 00000000..dcbf40eb --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/SpringbootJpaUnittestingApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootJpaUnittestingApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootJpaUnittestingApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..77484ea1 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..99c75d4f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..188da365 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Slf4j +@Service +public class EmployeeService { + + + @Autowired + EmployeeRepository employeeRepository; + + public List getAllEmployee() { + log.info("EmployeeService.getAllEmployee()"); + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public Employee getEmployee(Long id) { + log.info("EmployeeService.getEmployee(), {}", id); + return this.employeeRepository.findById(id).get(); + } + + public Employee removeEmployee(Long id) { + log.info("EmployeeService.removeEmployee(), {}", id); + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + public Employee saveEmployee(Employee employee) { + log.info("EmployeeService.saveEmployee() ,{} ", employee); + return this.employeeRepository.save(employee); + } + + public Employee updateEmployee(Long id, Employee employee) { + log.info("EmployeeService.updateEmployee() ,{} ,{} ", id, employee); + return this.employeeRepository.save(employee); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..e03ee6f7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,48 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Slf4j +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + log.info("EmployeeController.getAllEmployee()"); + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + log.info("EmployeeController.getEmployee(), {}", id); + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + log.info("EmployeeController.removeEmployee(), {}", id); + return this.employeeService.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + log.info("EmployeeController.saveEmployee() ,{} ", employee); + return this.employeeService.saveEmployee(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + log.info("EmployeeController.updateEmployee() ,{} ,{} ", id, employee); + return this.employeeService.updateEmployee(id, employee); + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/application.properties b/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/application.properties new file mode 100644 index 00000000..f1b25d66 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/application.properties @@ -0,0 +1,11 @@ + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/data.sql b/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/data.sql new file mode 100644 index 00000000..c3c9dd8c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/main/resources/data.sql @@ -0,0 +1,21 @@ +-- To Check Employee Table Exist then drop +DROP TABLE IF EXISTS employee; + +-- To Create Employee Table +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +-- To Override hibernate sequence and start with 5 +DROP SEQUENCE IF EXISTS HIBERNATE_SEQUENCE; +CREATE SEQUENCE IF NOT EXISTS HIBERNATE_SEQUENCE START WITH 5 INCREMENT BY 1 ; + +-- To Insert the data into the Employee Table +INSERT INTO employee (first_name, last_name, career) VALUES + ( 'adarsh', 'kumar', 'It'), + ( 'radha', 'singh', 'IT'), + ( 'sonu', 'singh', 'IT'), + ( 'amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerMockTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerMockTest.java new file mode 100644 index 00000000..a6473fb2 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerMockTest.java @@ -0,0 +1,51 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultHandlers; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import java.util.LinkedList; +import java.util.List; +import static org.mockito.Mockito.times; + +/** + * load the whole context but with server start + */ +@Slf4j +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerMockTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private EmployeeService employeeService; + + @Test + public void getAllEmployeeTest() throws Exception{ + List employeeList = new LinkedList<>(); + Employee employee = new Employee(); + employee.setId(1L); + employee.setFirstName("xxx"); + employee.setLastName("kkk"); + employee.setCareer("oooo"); + employeeList.add(employee); + Mockito.when(employeeService.getAllEmployee()).thenReturn(employeeList); + this.mockMvc.perform(MockMvcRequestBuilders.get("/api/employees")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("ooo"))); + Mockito.verify(employeeService, times(1)).getAllEmployee(); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerUnitTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerUnitTest.java new file mode 100644 index 00000000..7094952c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeControllerUnitTest.java @@ -0,0 +1,35 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import lombok.extern.slf4j.Slf4j; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import java.util.Arrays; +import java.util.List; + + +@Slf4j +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class EmployeeControllerUnitTest { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void getAllEmployeeTest() throws Exception { + String url = "http://localhost:" + port + "/api/employees"; + Employee[] employeeArray = this.restTemplate.getForObject(url, Employee[].class); + List employeeList = Arrays.asList(employeeArray); + Assertions.assertThat(employeeList.get(0).getId()).isEqualTo(1); + Assertions.assertThat(employeeList.get(1).getId()).isEqualTo(2); + Assertions.assertThat(employeeList.get(2).getId()).isEqualTo(3); + Assertions.assertThat(employeeList.get(3).getId()).isEqualTo(4); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceMockTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceMockTest.java new file mode 100644 index 00000000..d8729f84 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceMockTest.java @@ -0,0 +1,39 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.MockBeans; +import java.util.LinkedList; +import java.util.List; +import static org.mockito.Mockito.times; + +@Slf4j +@SpringBootTest +@MockBeans({@MockBean(EmployeeService.class), @MockBean(EmployeeRepository.class)}) +class EmployeeServiceMockTest { + + @Autowired + private EmployeeService employeeService; + + @Test + public void getAllEmployeeTest() { + List employeeList = new LinkedList<>(); + Employee employee = new Employee(); + employee.setId(1L); + employee.setFirstName("xxx"); + employee.setLastName("kkk"); + employee.setCareer("oooo"); + employeeList.add(employee); + Mockito.when(employeeService.getAllEmployee()).thenReturn(employeeList); + List employees = employeeService.getAllEmployee(); + Mockito.verify(employeeService, times(1)).getAllEmployee(); + log.info("==> {}", employees); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceUnitTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceUnitTest.java new file mode 100644 index 00000000..18cc1f23 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/EmployeeServiceUnitTest.java @@ -0,0 +1,28 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import java.util.LinkedList; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@DataJpaTest +class EmployeeServiceUnitTest { + + @Autowired + EmployeeRepository employeeRepository; + + + @Test + public void getAllEmployee(){ + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + assertNotNull(employeeList.get(0)); + assertNotNull(employeeList.get(1)); + assertNotNull(employeeList.get(2)); + assertNotNull(employeeList.get(3)); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/OnlyEmployeeControllerMockTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/OnlyEmployeeControllerMockTest.java new file mode 100644 index 00000000..b42939d7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/OnlyEmployeeControllerMockTest.java @@ -0,0 +1,52 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import com.espark.adarsh.web.EmployeeController; +import lombok.extern.slf4j.Slf4j; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultHandlers; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.LinkedList; +import java.util.List; + +import static org.mockito.Mockito.times; + +/** + * load the whole context but without server start + */ +@Slf4j +@WebMvcTest(EmployeeController.class) +public class OnlyEmployeeControllerMockTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private EmployeeService employeeService; + + @Test + public void getAllEmployeeTest() throws Exception { + List employeeList = new LinkedList<>(); + Employee employee = new Employee(); + employee.setId(1L); + employee.setFirstName("xxx"); + employee.setLastName("kkk"); + employee.setCareer("oooo"); + employeeList.add(employee); + Mockito.when(employeeService.getAllEmployee()).thenReturn(employeeList); + this.mockMvc.perform(MockMvcRequestBuilders.get("/api/employees")) + .andDo(MockMvcResultHandlers.print()) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("ooo"))); + Mockito.verify(employeeService, times(1)).getAllEmployee(); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/RepositoryServiceControllerSmokeTest.java b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/RepositoryServiceControllerSmokeTest.java new file mode 100644 index 00000000..5d429fa2 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2-testing/src/test/java/com/espark/adarsh/RepositoryServiceControllerSmokeTest.java @@ -0,0 +1,31 @@ +package com.espark.adarsh; + +import com.espark.adarsh.respository.EmployeeRepository; +import com.espark.adarsh.service.EmployeeService; +import com.espark.adarsh.web.EmployeeController; +import lombok.extern.slf4j.Slf4j; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@Slf4j +@SpringBootTest +public class RepositoryServiceControllerSmokeTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Autowired + private EmployeeService employeeService; + + @Autowired + private EmployeeController employeeController; + + @Test + void contextLoads() { + Assertions.assertThat(this.employeeRepository).isNotNull(); + Assertions.assertThat(this.employeeService).isNotNull(); + Assertions.assertThat(this.employeeController).isNotNull(); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/.gitignore b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/README.md b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/README.md new file mode 100644 index 00000000..a3b8e46a --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/README.md @@ -0,0 +1,22 @@ +# spring boot jpa h2db multi module + +--- + +### To build +* mvn clean package + +### To Run +* mvn install && mvn spring-boot:run -pl spring-web +* cd spring-web + * mvn spring-boot:run +* java -jar spring-web/target/spring-web-0.0.1-SNAPSHOT.jar + +### To Access Application +* http://localhost:8080/employees +* curl -X GET http://localhost:8080/employees +* curl -X GET http://localhost:8080/api/wish + + +### log into the homepage of db +* http://localhost:8080/h2-console +* username, pwd , db url and db driver class is mentioned in application.properties file \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/pom.xml b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/pom.xml new file mode 100644 index 00000000..2787c366 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + pom + + spring-persistence + spring-services + spring-web + + + org.springframework.boot + spring-boot-starter-parent + 2.5.1 + + + com.espark.adarsh + springboot-jpa-h2db-mutlmodule + 0.0.1-SNAPSHOT + springboot-jpa-h2db-mutlmodule + Demo project for Spring Boot + + 11 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/pom.xml b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/pom.xml new file mode 100644 index 00000000..15d75028 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/pom.xml @@ -0,0 +1,28 @@ + + + + springboot-jpa-h2db-mutlmodule + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + spring-persistence + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java new file mode 100644 index 00000000..8de8d9f9 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.persistence.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java new file mode 100644 index 00000000..4086521f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.persistence.respository; + +import com.espark.adarsh.persistence.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java new file mode 100644 index 00000000..c99a354d --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/java/com/espark/adarsh/persistence/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.persistence.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/application.properties b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/application.properties new file mode 100644 index 00000000..0797c13f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/application.properties @@ -0,0 +1,12 @@ + + + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true + diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/data.sql b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-persistence/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/pom.xml b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/pom.xml new file mode 100644 index 00000000..cf5cd3b1 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/pom.xml @@ -0,0 +1,23 @@ + + + + springboot-jpa-h2db-mutlmodule + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + spring-services + 0.0.1-SNAPSHOT + + + + com.espark.adarsh + spring-persistence + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/EmployeeService.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/EmployeeService.java new file mode 100644 index 00000000..0f93af37 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/EmployeeService.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.persistence.entity.Employee; + +import java.util.List; + +public interface EmployeeService { + + List getAllEmployee(); + + Employee getEmployee(Long id); + + Employee saveEmployee(Employee employee); + + Employee updateEmployee(Long id, Employee employee); +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java new file mode 100644 index 00000000..b08c131f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-services/src/main/java/com/espark/adarsh/services/impl/EmployeeServiceImpl.java @@ -0,0 +1,45 @@ +package com.espark.adarsh.services.impl; + +import com.espark.adarsh.services.EmployeeService; +import com.espark.adarsh.persistence.entity.Employee; +import com.espark.adarsh.persistence.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service("employeeService") +public class EmployeeServiceImpl implements EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Override + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @Override + public Employee getEmployee(Long id) { + return this.employeeRepository.findById(id).get(); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @Override + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + @Override + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/pom.xml b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/pom.xml new file mode 100644 index 00000000..23994881 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/pom.xml @@ -0,0 +1,47 @@ + + + + springboot-jpa-h2db-mutlmodule + com.espark.adarsh + 0.0.1-SNAPSHOT + + 4.0.0 + + spring-web + 0.0.1-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-web + + + + com.espark.adarsh + spring-services + 0.0.1-SNAPSHOT + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..f28ace5f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..1ac6f214 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.web; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @GetMapping("/wish") + public Map wish() { + return new HashMap<>() { + { + put("name", "adarsh kumar"); + put("msg", "welcome to the application"); + } + }; + } + +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..457f64fc --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,41 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.services.EmployeeService; +import com.espark.adarsh.persistence.entity.Employee; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.removeEmployee(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id, employee); + } + +} diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/resources/application.properties b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/resources/application.properties new file mode 100644 index 00000000..52a48771 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/main/resources/application.properties @@ -0,0 +1,5 @@ + + +spring.logging.level.root=ALL +spring.logging.level.org.springframework.context=ALL +spring.logging.level.org.springframework.web=DEBUG diff --git a/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..6b6fe54c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-h2db-mutlmodule/spring-web/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = com.espark.adarsh.ApplicationMain.class) +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/.gitignore b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/README.md b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/README.md new file mode 100644 index 00000000..af51a9cb --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/README.md @@ -0,0 +1,305 @@ +# SPRING BOOT JPA ORACLE DB LIQUID BASE STORED FUNCTION + +--- + +### To Build Code +* mvn clean package + +### TO CHECK DATA INTO THE DB +* SELECT * FROM SYSTEM.EMPLOYEE; +* SELECT * FROM SYSTEM.DATABASECHANGELOG; + +## TO CHECK SQL SCRPT WORKED OR NOT +* SELECT * FROM SYSTEM.DATABASECHANGELOG; +* TRUNCATE TABLE SYSTEM.DATABASECHANGELOG; + +## TO DROP THE TABLES IN DB +* DROP PROCEDURE SYSTEM.getEmpFunction; +* DROP PROCEDURE SYSTEM.getAllEmpFunction; +* DROP PROCEDURE SYSTEM.insertEmpFunction; +* DROP PROCEDURE SYSTEM.updateEmpFunction; +* DROP PROCEDURE SYSTEM.deleteEmpFunction; +* DROP TABLE SYSTEM.EMPLOYEE; +* DROP TABLE SYSTEM.DATABASECHANGELOG; +* DROP TABLE SYSTEM.DATABASECHANGELOGLOCK; + + +## To Test the getEmpFunction +``` + SET SERVEROUTPUT ON; + DECLARE + V_ONE_EMP_DATA_CURSOR SYS_REFCURSOR; + V_EMPNO EMPLOYEE.EMP_NO%TYPE; + V_EMPNAME EMPLOYEE.EMP_NAME%TYPE; + V_EMPEMAIL EMPLOYEE.EMP_EMAIL%TYPE; + V_SELECT_ERROR_MSG VARCHAR(50); + BEGIN + V_ONE_EMP_DATA_CURSOR :=getEmpFunction(&EMPNO,V_SELECT_ERROR_MSG); + IF V_SELECT_ERROR_MSG IS NULL THEN + LOOP + FETCH V_ONE_EMP_DATA_CURSOR INTO V_EMPNO,V_EMPNAME,V_EMPEMAIL; + EXIT WHEN V_ONE_EMP_DATA_CURSOR%NOTFOUND; + DBMS_OUTPUT.PUT_LINE('EMPLOYEE DATA '||V_EMPNO||','||V_EMPNAME||','||V_EMPEMAIL); + END LOOP; + + ELSE + DBMS_OUTPUT.PUT_LINE(V_SELECT_ERROR_MSG); + END IF; + DBMS_OUTPUT.PUT_LINE(V_SELECT_ERROR_MSG); + IF V_ONE_EMP_DATA_CURSOR%ISOPEN THEN + CLOSE V_ONE_EMP_DATA_CURSOR; + END IF; + END; + / +``` + +### TO TEST getAllEmpFunction +```` + SET SERVEROUTPUT ON; + DECLARE + V_EMP_ALL_DATA_CURSOR SYS_REFCURSOR; + V_EMPNO EMPLOYEE.EMP_NO%TYPE; + V_EMPNAME EMPLOYEE.EMP_NAME%TYPE; + V_EMPEMAIL EMPLOYEE.EMP_EMAIL%TYPE; + V_SELECT_ERROR_MSG VARCHAR(50); + BEGIN + V_EMP_ALL_DATA_CURSOR :=getAllEmpFunction(V_SELECT_ERROR_MSG); + IF V_SELECT_ERROR_MSG IS NULL THEN + LOOP + FETCH V_EMP_ALL_DATA_CURSOR INTO V_EMPNO,V_EMPNAME,V_EMPEMAIL; + EXIT WHEN V_EMP_ALL_DATA_CURSOR%NOTFOUND; + DBMS_OUTPUT.PUT_LINE('EMPLOYEE DATA '||V_EMPNO||','||V_EMPNAME||','||V_EMPEMAIL); + END LOOP; + CLOSE V_EMP_ALL_DATA_CURSOR; + ELSE + DBMS_OUTPUT.PUT_LINE(V_SELECT_ERROR_MSG); + END IF; + END; + / +```` + +### TO TEST insertEmpFunction +``` +SET SERVEROUTPUT ON; +DECLARE + DATA VARCHAR2(500) ; +BEGIN +DATA :=insertEmpFunction('&EMPNAME','&EMPEMAIL'); +DBMS_OUTPUT.PUT_LINE(DATA); +END; +/ +``` + +### TO TEST THE updateEmpFunction +``` +SET SERVEROUTPUT ON; +DECLARE + DATA VARCHAR(500) ; +BEGIN +DATA :=updateEmpFunction(&EMPNO,'&EMPNAME','&EMPEMAIL'); +DBMS_OUTPUT.PUT_LINE(DATA); +END; +/ +``` + +### TO TEST THE deleteEmpFunction +``` +SET SERVEROUTPUT ON; +DECLARE + DATA VARCHAR(500) ; +BEGIN +DATA := deleteEmpFunction(&EMPNO); +DBMS_OUTPUT.PUT_LINE(DATA); +END; +/ +``` + +--- +# ORACLE DB DOCKER IMAGE AND DEPLOYMENT +## Clone the git hub from oracle +* git clone git@github.com:oracle/docker-images.git + +## move to the docker file directory +* $ cd docker-images/OracleDatabase/SingleInstance/dockerfiles + +# list the supported version +* $ ls +``` +11.2.0.2 12.2.0.1 18.4.0 21.3.0 +12.1.0.2 18.3.0 19.3.0 buildContainerImage.sh +``` + +## url to download the version of oracle zip +* https://www.oracle.com/database/technologies/xe18c-downloads.html +* copy into the same directory of the version in ls cmd + +## Build the docker image +* $ sh buildContainerImage.sh -v 18.4.0 -x + +``` +Oracle Database container image for 'xe' version 18.4.0 is ready to be extended: + + --> oracle/database:18.4.0-xe + + Build completed in 510 seconds. +``` + +## db client opensource +* https://dbeaver.io/download/ + +## launch the db +* $ docker run --name OracleXE \ + --shm-size=1g \ + -p 1521:1521 \ + -p 8081:8080 \ + -e ORACLE_PWD=12345 \ + -v oracle-data:/u01/app/oracle/oradata \ + oracle/database:18.4.0-xe + +``` +ORACLE PASSWORD FOR SYS AND SYSTEM: 12345 +Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts: +Confirm the password: +Configuring Oracle Listener. +Listener configuration succeeded. +Configuring Oracle Database XE. +Enter SYS user password: +****** +Enter SYSTEM user password: +***** +Enter PDBADMIN User Password: +***** +Prepare for db operation +7% complete +Copying database files +29% complete +Creating and starting Oracle instance +Completing Database Creation +47% complete +50% complete +Creating Pluggable Databases +54% complete +71% complete +Executing Post Configuration Actions +93% complete +Running Custom Scripts +100% complete +Database creation complete. For details check the logfiles at: + /opt/oracle/cfgtoollogs/dbca/XE. +Database Information: +Global Database Name:XE +System Identifier(SID):XE +Look at the log file "/opt/oracle/cfgtoollogs/dbca/XE/XE.log" for further details. + +Connect to Oracle Database using one of the connect strings: + Pluggable database: 2f7354fc4ee1/XEPDB1 + Multitenant container database: 2f7354fc4ee1 +Use https://localhost:5500/em to access Oracle Enterprise Manager for Oracle Database XE +The Oracle base remains unchanged with value /opt/oracle +######################### +DATABASE IS READY TO USE! +######################### +The following output is now a tail of the alert.log: +2021-10-05T23:03:43.054971+00:00 +XEPDB1(3):Resize operation completed for file# 10, old size 358400K, new size 368640K +2021-10-05T23:03:56.975470+00:00 +XEPDB1(3):CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):Completed: CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):ALTER DATABASE DEFAULT TABLESPACE "USERS" +XEPDB1(3):Completed: ALTER DATABASE DEFAULT TABLESPACE "USERS" +2021-10-05T23:04:03.318085+00:00 +ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE +Completed: ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE + +``` + +## Connect to db +``` +Host: localhost +Port: 1521 +Database: XE +Use SID +User name: SYS +Role: SYSDBA +Password: 12345 +``` + +## Clean up +* docker ps -a +* docker rm [OPTIONS] CONTAINER [CONTAINER...] +* docker rm -f [CONTAINER_ID] +* docker rm -f 2f7354fc4ee1 +* docker rm -f [CONTAINER_NAME] OracleXE +* docker rm -f OracleXE + +[HELP FROM BLOG](https://www.codesanook.com/setup-oracle-xe-database-on-docker-container-and-connect-with-dbeaver) + +--- + + +## Api Testing +### To Fetch the Employee +* $ curl -X GET http://localhost:8080/employee/1 +``` +{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +### To Creating the Employee +* $ curl -X POST http://localhost:8080/employee -H 'Content-Type: application/json' -d '{"empName":"adi","empEmail":"adi@kumar"}' +``` + {"empNo":5,"empName":"adi","empEmail":"adi@kumar"} +``` + +### To Create employee using procedure +* $ curl -X POST http://localhost:8080/employee/fun -H 'Content-Type: application/json' -d '{"empName":"adi","empEmail":"adi@kumar"}' +``` +EMPLOYEE INSERT SUCCESSFUL 1 EMPLOYEE DATA 5 adi adi@kumar +``` + +### To Update employee +* $ curl -X PUT http://localhost:8080/employee/5 -H 'Content-Type: application/json' -d '{"empNo":5,"empName":"adik","empEmail":"adi@kumar"}' +``` +{"empNo":5,"empName":"adik","empEmail":"adi@kumar"} +``` + +### To Update employee using procedure +* $ curl -X PUT http://localhost:8080/employee/fun/5 -H 'Content-Type: application/json' -d '{"empNo":5,"empName":"adiii","empEmail":"adi@kumar"}' +``` +EMPLOYEE UPDATED SUCCESSFUL 1UPDATED EMPLOYEE DATA5 adiii adi@kumar +``` + +## To Delete employee +* curl -X DELETE http://localhost:8080/employee/5 +``` +{"empNo":5,"empName":"adik","empEmail":"adi@kumar"} +``` + +## To Delete employee using procedure +* curl -X DELETE http://localhost:8080/employee/fun/5 +``` +EMPLOYEE DELETED SUCCESSFUL 1 EMPLOYEE DELETED 5 adiii adi@kumar +``` + +## To fetch employee +* $ curl -X GET http://localhost:8080/employee/1 +``` + {"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +## To Fetch employee using procedure +* curl -X GET http://localhost:8080/employee/fun/1 +``` +{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +## To fetch employees +* $ curl -X GET http://localhost:8080/employees +``` +[{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"},{"empNo":2,"empName":"radha","empEmail":"radha@singh"},{"empNo":3,"empName":"sonu","empEmail":"sonu@singh"},{"empNo":4,"empName":"amit","empEmail":"amit@kumar"}] +``` + +## To Fetch employees using procedure +* $ curl -X GET http://localhost:8080/employees/fun +``` +[{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"},{"empNo":2,"empName":"radha","empEmail":"radha@singh"},{"empNo":3,"empName":"sonu","empEmail":"sonu@singh"},{"empNo":4,"empName":"amit","empEmail":"amit@kumar"}] +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/pom.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/pom.xml new file mode 100644 index 00000000..f3026ca5 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-liquidbase-oracle-db-stored-function + 0.0.1-SNAPSHOT + springboot-jpa-liquidbase-oracle-db-stored-function + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.oracle.database.jdbc + ojdbc10 + 19.3.0.0 + + + + org.projectlombok + lombok + + + + org.liquibase + liquibase-core + + + + com.zaxxer + HikariCP + 2.6.0 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/.DS_Store new file mode 100644 index 00000000..8813de11 Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/.DS_Store new file mode 100644 index 00000000..e8e05c2d Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/.DS_Store new file mode 100644 index 00000000..3705dc35 Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..08d27d3d Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/.DS_Store new file mode 100644 index 00000000..35af2b5e Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..9813300f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,62 @@ +package com.espark.adarsh.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +@JsonIgnoreProperties(ignoreUnknown = true) +public class Employee { + + @Id + @Column(name = "EMP_NO") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMP_SEQ") + @SequenceGenerator(sequenceName = "EMPLOYEE_SEQ", allocationSize = 1, name = "EMP_SEQ") + private Long empNo; + + @Column(name = "EMP_NAME") + private String empName; + + @Column(name = "EMP_EMAIL") + private String empEmail; + + public Employee() { + } + + public Employee(String firstName, String empEmail) { + this.empName = firstName; + this.empEmail = empEmail; + } + + public Employee(Long empNo, String firstName, String empEmail) { + this.empNo = empNo; + this.empName = firstName; + this.empEmail = empEmail; + } + + public Long getEmpNo() { + return empNo; + } + + public void setEmpNo(Long empNo) { + this.empNo = empNo; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public String getEmpEmail() { + return empEmail; + } + + public void setEmpEmail(String empEmail) { + this.empEmail = empEmail; + } +} + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..a4975847 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + + +@Repository +public interface EmployeeRepository extends CrudRepository { + + @Procedure(procedureName = "GET_EMPLOYEE_INFO_FUNCTION", outputParameterName = "V_EMP_MSG") + String getEmployeeData(@Param("V_EMP_NO") Long empNo); + + + @Procedure(procedureName = "insertEmpFunction") + String saveEmployeeByFunction( + @Param("V_EMPNAME") String empName + , @Param("V_EMPEMAIL") String empEmail + ); + + @Procedure(procedureName = "updateEmpFunction") + String updateEmployeeByFunction(@Param("V_EMPNO") Long empNo + , @Param("V_EMPNAME") String empName + , @Param("V_EMPEMAIL") String empEmail + ); + + @Procedure(procedureName = "deleteEmpFunction") + String deleteEmployeeByFunction(@Param("V_EMP_NO") Long empNo); + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java new file mode 100644 index 00000000..34505dbf --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.ParameterMode; +import javax.persistence.StoredProcedureQuery; +import java.util.List; + +@Repository +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class EmployeeSpRepository { + + private final EntityManager entityManager; + + public List getEmployeeByFunction(Long empNo) { + StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getEmpFunction", Employee.class); + storedProcedureQuery.registerStoredProcedureParameter("V_EMP_NO", Long.class, ParameterMode.IN); + storedProcedureQuery.registerStoredProcedureParameter("V_SELECT_ERROR_MSG", String.class, ParameterMode.OUT); + storedProcedureQuery.registerStoredProcedureParameter("V_EMP_DATA_CURSOR", List.class, ParameterMode.REF_CURSOR); + storedProcedureQuery.setParameter("V_EMP_NO", empNo); + storedProcedureQuery.execute(); + return storedProcedureQuery.getResultList(); + } + + public List getEmployeesByFunction() { + StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getAllEmpFunction", Employee.class); + storedProcedureQuery.registerStoredProcedureParameter("V_SELECT_ERROR_MSG", String.class, ParameterMode.OUT); + storedProcedureQuery.execute(); + return storedProcedureQuery.getResultList(); + } +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..0d8f6149 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,69 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import com.espark.adarsh.respository.EmployeeSpRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + EmployeeSpRepository employeeSpRepository; + + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public List getEmployeesByFunction() { + return this.employeeSpRepository.getEmployeesByFunction(); + } + + + public Employee getEmployee(Long id) { + return employeeRepository.findById(id).get(); + } + + public Employee getEmployeeByFunction(Long id) { + return this.employeeSpRepository.getEmployeeByFunction(id).get(0); + } + + public String getEmployeeStringByFunction(Long id) { + return employeeRepository.getEmployeeData(id); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + public String removeEmployeeByFunction(Long id){ + return this.employeeRepository.deleteEmployeeByFunction(id); + } + + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + public String saveEmployeeByFunction(Employee employee) { + return this.employeeRepository.saveEmployeeByFunction(employee.getEmpName(),employee.getEmpEmail()); + } + + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } + + public String updateEmployeeByFunction(Long id, Employee employee) { + return this.employeeRepository.updateEmployeeByFunction(id,employee.getEmpName(),employee.getEmpEmail()); + } +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..94cea014 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,71 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employees/fun") + public List getEmployeesByFunction() { + return this.employeeService.getEmployeesByFunction(); + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @GetMapping("/employee/fun/{id}") + public Employee getEmployeeByFunction(@PathVariable("id") Long id) { + return this.employeeService.getEmployeeByFunction(id); + } + + @GetMapping("/employee/fun/str/{id}") + public String getEmployeeData(@PathVariable("id") Long id) { + return this.employeeService.getEmployeeStringByFunction(id); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @DeleteMapping("/employee/fun/{id}") + public String removeEmployeeByFunction(@PathVariable("id") Long id) { + return this.employeeService.removeEmployeeByFunction(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PostMapping("/employee/fun") + public String saveEmployeeByFunction(@RequestBody Employee employee) { + return this.employeeService.saveEmployeeByFunction(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id, employee); + } + + @PutMapping("/employee/fun/{id}") + public String updateEmployeeByFunction(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployeeByFunction(id, employee); + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/application.properties b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/application.properties new file mode 100644 index 00000000..4a8b960c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/application.properties @@ -0,0 +1,29 @@ + + + + +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE +spring.datasource.username=SYSTEM +spring.datasource.password=12345 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.generate-ddl=false + + +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml +spring.liquibase.drop-first=true + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/create_schema.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/create_schema.xml new file mode 100644 index 00000000..0d985dd7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/create_schema.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/delete_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/delete_employee.xml new file mode 100644 index 00000000..5b0a5cd7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/delete_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employee.xml new file mode 100644 index 00000000..32973eef --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employees.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employees.xml new file mode 100644 index 00000000..261ee668 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/get_employees.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_data.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_data.xml new file mode 100644 index 00000000..5465b722 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_employee.xml new file mode 100644 index 00000000..666b36f4 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/insert_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/select_data.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/select_data.xml new file mode 100644 index 00000000..233310b3 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/select_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/create_schema.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/create_schema.sql new file mode 100644 index 00000000..55fc3a79 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/create_schema.sql @@ -0,0 +1,14 @@ +DROP TABLE SYSTEM.EMPLOYEE; +DROP SEQUENCE SYSTEM.EMPLOYEE_SEQ; + +CREATE TABLE SYSTEM.Employee ( + EMP_NO INTEGER PRIMARY KEY, + EMP_NAME VARCHAR(250) NOT NULL, + EMP_EMAIL VARCHAR(250) NOT NULL +); + +CREATE SEQUENCE SYSTEM.EMPLOYEE_SEQ + MINVALUE 1 + MAXVALUE 9999999999 + START WITH 1 + INCREMENT BY 1; \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/delete_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/delete_employee.sql new file mode 100644 index 00000000..eb39e490 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/delete_employee.sql @@ -0,0 +1,38 @@ +CREATE OR REPLACE FUNCTION deleteEmpFunction(V_EMP_NO IN EMPLOYEE.EMP_NO%TYPE)RETURN VARCHAR + IS + V_EMP_DEL_MSG VARCHAR2(500); + V_EMP_DEL_COUNT NUMBER(10) DEFAULT 0; + V_EMP_COUNT NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(200); + BEGIN + IF V_EMP_NO IS NOT NULL THEN + + SELECT COUNT(EMP.EMP_NO) INTO V_EMP_COUNT FROM EMPLOYEE EMP WHERE EMP.EMP_NO =NVL(V_EMP_NO,0); + + IF V_EMP_COUNT > 0 THEN + + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = NVL(V_EMP_NO,0); + + DELETE FROM EMPLOYEE WHERE EMP_NO = NVL(V_EMP_NO,0); + V_EMP_DEL_COUNT := SQL%ROWCOUNT; + + IF V_EMP_DEL_COUNT >0 THEN + V_EMP_DEL_MSG:='EMPLOYEE DELETED SUCCESSFUL '||V_EMP_DEL_COUNT||' EMPLOYEE DELETED '||V_EMP_MSG; + ELSE + V_EMP_DEL_MSG:='EMPLOYEE NOT DELETED '||V_EMP_DEL_COUNT; + END IF; + COMMIT; + + ELSE + V_EMP_DEL_MSG:='INVALID ARGUMENTS ID SUPPLIED TO FUNCTION'; + END IF; + ELSE + V_EMP_DEL_MSG:='IMPROPER ARGUMENTS SUPPLIED TO FUNCTION'; + END IF; + RETURN (V_EMP_DEL_MSG); + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20001, V_EMP_NO || ':$:' || SQLERRM, TRUE); + END deleteEmpFunction; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employee.sql new file mode 100644 index 00000000..d8e4f6b3 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employee.sql @@ -0,0 +1,31 @@ +CREATE OR REPLACE FUNCTION getEmpFunction(V_EMP_NO IN EMPLOYEE.EMP_NO%TYPE ,V_SELECT_ERROR_MSG OUT VARCHAR) RETURN SYS_REFCURSOR +IS + V_COUNT NUMBER; + V_EMP_DATA_CURSOR SYS_REFCURSOR; + BEGIN + + SELECT COUNT(*) INTO V_COUNT FROM EMPLOYEE WHERE EMP_NO = V_EMP_NO; + + IF V_COUNT != 0 THEN + OPEN V_EMP_DATA_CURSOR + FOR SELECT EMP.EMP_NO,EMP.EMP_NAME,EMP.EMP_EMAIL FROM EMPLOYEE EMP WHERE EMP.EMP_NO = V_EMP_NO; + ELSE + V_SELECT_ERROR_MSG :='NO EMPLOYEE FOUND FOR EMP_NO '||V_EMP_NO; + END IF; + + RETURN(V_EMP_DATA_CURSOR); + + EXCEPTION + WHEN NO_DATA_FOUND THEN + BEGIN + V_SELECT_ERROR_MSG:='NO EMPLOYEE FOUND'; + END; + WHEN TOO_MANY_ROWS THEN + BEGIN + RAISE_APPLICATION_ERROR(-20612,'MORE THEN ONE EMPLOYEE FOUND FOR EMP_NO '||V_EMP_NO); + END; + WHEN OTHERS THEN + RAISE_APPLICATION_ERROR(-20001, V_EMP_NO || ':$:' || SQLERRM, TRUE) ; +END getEmpFunction; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employees.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employees.sql new file mode 100644 index 00000000..ec74948c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/get_employees.sql @@ -0,0 +1,25 @@ + + CREATE OR REPLACE FUNCTION getAllEmpFunction(V_SELECT_ERROR_MSG OUT VARCHAR) RETURN SYS_REFCURSOR +IS + V_COUNT NUMBER; + V_EMP_ALL_DATA_CURSOR SYS_REFCURSOR; +BEGIN + SELECT COUNT(*) INTO V_COUNT FROM EMPLOYEE; + IF V_COUNT != 0 THEN + OPEN V_EMP_ALL_DATA_CURSOR + FOR SELECT EMP.EMP_NO,EMP.EMP_NAME,EMP.EMP_EMAIL FROM EMPLOYEE EMP; + ELSE + V_SELECT_ERROR_MSG :='NO EMPLOYEE FOUND'; + END IF; + + RETURN(V_EMP_ALL_DATA_CURSOR); + CLOSE V_EMP_ALL_DATA_CURSOR; + EXCEPTION + WHEN NO_DATA_FOUND THEN + BEGIN + V_SELECT_ERROR_MSG :='NO EMPLOYEE FOUND'; + END; + WHEN OTHERS THEN + RAISE_APPLICATION_ERROR (-20001, 'EXCEPTION GENERATED :$:' || SQLERRM, TRUE) ; +END getAllEmpFunction; +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_data.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_data.sql new file mode 100644 index 00000000..e59b69c0 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_data.sql @@ -0,0 +1,4 @@ +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES (SYSTEM.EMPLOYEE_SEQ.nextval,'adarsh', 'adarsh@kumar'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES (SYSTEM.EMPLOYEE_SEQ.nextval,'radha', 'radha@singh'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,'sonu', 'sonu@singh'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,'amit', 'amit@kumar'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_employee.sql new file mode 100644 index 00000000..269e6173 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/insert_employee.sql @@ -0,0 +1,33 @@ +CREATE OR REPLACE FUNCTION insertEmpFunction( + V_EMPNAME IN EMPLOYEE.EMP_NAME%TYPE + ,V_EMPEMAIL IN EMPLOYEE.EMP_EMAIL%TYPE)RETURN VARCHAR +IS + V_EMP_INSERT_MSG VARCHAR2(500); + V_EMP_INSERT_COUNT NUMBER(10) DEFAULT 0; + ID_EMP NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(500); + PRAGMA AUTONOMOUS_TRANSACTION; +BEGIN + IF V_EMPNAME||V_EMPEMAIL IS NOT NULL THEN + + INSERT INTO EMPLOYEE (EMP_NO,EMP_NAME,EMP_EMAIL) + VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,NVL(V_EMPNAME,'NOT AVAILABLE'),NVL(V_EMPEMAIL,'NOT AVAILABLE')) + RETURNING EMP_NO INTO ID_EMP; + + V_EMP_INSERT_COUNT := SQL%ROWCOUNT; + IF V_EMP_INSERT_COUNT >0 THEN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = ID_EMP; + V_EMP_INSERT_MSG:='EMPLOYEE INSERT SUCCESSFUL '||V_EMP_INSERT_COUNT ||' EMPLOYEE DATA '|| V_EMP_MSG; + ELSE + V_EMP_INSERT_MSG:='EMPLOYEE NOT INSERT '||V_EMP_INSERT_COUNT; + END IF; + COMMIT; + ELSE + V_EMP_INSERT_MSG:='IMPROPER ARGUMENTS SUPPLIED TO FUNCTION'; + END IF; + RETURN (V_EMP_INSERT_MSG); + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20001, V_EMPNAME||':$:'||V_EMPEMAIL|| ':$:' ||SQLERRM, TRUE) ; +END insertEmpFunction; +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/select_data.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/select_data.sql new file mode 100644 index 00000000..a45a7201 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/select_data.sql @@ -0,0 +1,9 @@ +CREATE OR REPLACE FUNCTION GET_EMPLOYEE_INFO_FUNCTION +( V_EMP_NO IN EMPLOYEE.EMP_NO%TYPE, V_EMP_MSG OUT VARCHAR ) +AS +BEGIN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = V_EMP_NO; +END; +// + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/update_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/update_employee.sql new file mode 100644 index 00000000..9c63887d --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/sql/update_employee.sql @@ -0,0 +1,30 @@ +CREATE OR REPLACE FUNCTION updateEmpFunction( + V_EMPNO IN EMPLOYEE.EMP_NO%TYPE + ,V_EMPNAME IN EMPLOYEE.EMP_NAME%TYPE + ,V_EMPEMAIL IN EMPLOYEE.EMP_EMAIL%TYPE)RETURN VARCHAR +IS + V_EMP__UPDATE_MSG VARCHAR2(500); + V_EMP_UPDATE_COUNT NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(200); +BEGIN + IF V_EMPNO IS NOT NULL THEN + UPDATE EMPLOYEE SET EMP_NAME=V_EMPNAME, EMP_EMAIL=V_EMPEMAIL WHERE EMP_NO=NVL(V_EMPNO,0); + V_EMP_UPDATE_COUNT := SQL%ROWCOUNT; + IF V_EMP_UPDATE_COUNT >0 THEN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = V_EMPNO; + V_EMP__UPDATE_MSG:='EMPLOYEE UPDATED SUCCESSFUL '||V_EMP_UPDATE_COUNT || 'UPDATED EMPLOYEE DATA' ||V_EMP_MSG; + ELSE + V_EMP__UPDATE_MSG:='EMPLOYEE NOT UPDATED '||V_EMP_UPDATE_COUNT; + END IF; + COMMIT; + ELSE + V_EMP__UPDATE_MSG:='IMPROPER ARGUMENTS SUPPLIED TO FUNCTION'; + END IF; + RETURN (V_EMP__UPDATE_MSG); + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20001, V_EMPNO || ':$:' || SQLERRM, TRUE); +COMMIT; +END updateEmpFunction; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/update_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/update_employee.xml new file mode 100644 index 00000000..c6e5db16 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/changes/update_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/db.changelog-master.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 00000000..48423a5f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-function/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/.gitignore b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/README.md b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/README.md new file mode 100644 index 00000000..804051bf --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/README.md @@ -0,0 +1,299 @@ +# SPRING BOOT JPA ORACLE DB LIQUID BASE STORED PROCEDURE + +--- + +### To Build Code +* mvn clean package + +### TO CHECK DATA INTO THE DB +* SELECT * FROM SYSTEM.EMPLOYEE; +* SELECT * FROM SYSTEM.DATABASECHANGELOG; + +## TO CHECK SQL SCRPT WORKED OR NOT +* SELECT * FROM SYSTEM.DATABASECHANGELOG; +* TRUNCATE TABLE SYSTEM.DATABASECHANGELOG; + +## TO DROP THE TABLES IN DB +* DROP PROCEDURE SYSTEM.getEmpProcedure; +* DROP PROCEDURE SYSTEM.getAllEmpProcedure; +* DROP PROCEDURE SYSTEM.insertEmpProcedure; +* DROP PROCEDURE SYSTEM.updateEmpProcedure; +* DROP PROCEDURE SYSTEM.deleteEmpProcedure; +* DROP TABLE SYSTEM.EMPLOYEE; +* DROP TABLE SYSTEM.DATABASECHANGELOG; +* DROP TABLE SYSTEM.DATABASECHANGELOGLOCK; + + +## To Test the getEmpProcedure +``` +SET SERVEROUTPUT ON; + DECLARE + V_EMP_DATA_CURSOR SYS_REFCURSOR; + V_EMPNO EMPLOYEE.EMP_NO%TYPE; + V_EMPNAME EMPLOYEE.EMP_NAME%TYPE; + V_EMPEMAIL EMPLOYEE.EMP_EMAIL%TYPE; + V_SELECT_ERROR_MSG VARCHAR(50); + BEGIN + getEmpProcedure(&EMPNO,V_EMP_DATA_CURSOR,V_SELECT_ERROR_MSG); + IF V_SELECT_ERROR_MSG IS NULL THEN + LOOP + FETCH V_EMP_DATA_CURSOR INTO V_EMPNO,V_EMPNAME,V_EMPEMAIL; + EXIT WHEN V_EMP_DATA_CURSOR%NOTFOUND; + DBMS_OUTPUT.PUT_LINE('EMPLOYEE DATA '||V_EMPNO||','||V_EMPNAME||','||V_EMPEMAIL); + END LOOP; + CLOSE V_EMP_DATA_CURSOR; + ELSE + DBMS_OUTPUT.PUT_LINE(V_SELECT_ERROR_MSG); + END IF; + END; + / +``` + +### TO TEST getAllEmpProcedure +```` + SET SERVEROUTPUT ON; + DECLARE + V_EMP_DATA_CURSOR SYS_REFCURSOR; + V_EMPNO EMPLOYEE.EMP_NO%TYPE; + V_EMPNAME EMPLOYEE.EMP_NAME%TYPE; + V_EMPEMAIL EMPLOYEE.EMP_EMAIL%TYPE; + V_SELECT_ERROR_MSG VARCHAR(50); + BEGIN + getAllEmpProcedure(V_EMP_DATA_CURSOR,V_SELECT_ERROR_MSG); + IF V_SELECT_ERROR_MSG IS NULL THEN + LOOP + FETCH V_EMP_DATA_CURSOR INTO V_EMPNO,V_EMPNAME,V_EMPEMAIL; + EXIT WHEN V_EMP_DATA_CURSOR%NOTFOUND; + DBMS_OUTPUT.PUT_LINE('EMPLOYEE DATA '||V_EMPNO||','||V_EMPNAME||','||V_EMPEMAIL); + END LOOP; + CLOSE V_EMP_DATA_CURSOR; + ELSE + DBMS_OUTPUT.PUT_LINE(V_SELECT_ERROR_MSG); + END IF; + END; + / +```` + +### TO TEST insertEmpProcedure +``` +SET SERVEROUTPUT ON; +DECLARE + DATA VARCHAR2(500) ; +BEGIN +insertEmpProcedure('&EMPNAME','&EMPEMAIL' ,DATA); +DBMS_OUTPUT.PUT_LINE(DATA); +END; +/ +``` + +### TO TEST THE updateEmpProcedure +``` +SET SERVEROUTPUT ON; +DECLARE + DATA VARCHAR2(500) ; +BEGIN +updateEmpProcedure(&EMPNO,'&EMPNAME','&EMPEMAIL' ,DATA); +DBMS_OUTPUT.PUT_LINE(DATA); +END; +/ +``` + +### TO TEST THE deleteEmpProcedure +``` +SET SERVEROUTPUT ON; +DECLARE + V_EMP_DEL_MSG VARCHAR2(500) ; +BEGIN + deleteEmpProcedure(&EMPNO,V_EMP_DEL_MSG); + DBMS_OUTPUT.PUT_LINE(V_EMP_DEL_MSG); +END; +/ +``` + +--- +# ORACLE DB DOCKER IMAGE AND DEPLOYMENT +## Clone the git hub from oracle +* git clone git@github.com:oracle/docker-images.git + +## move to the docker file directory +* $ cd docker-images/OracleDatabase/SingleInstance/dockerfiles + +# list the supported version +* $ ls +``` +11.2.0.2 12.2.0.1 18.4.0 21.3.0 +12.1.0.2 18.3.0 19.3.0 buildContainerImage.sh +``` + +## url to download the version of oracle zip +* https://www.oracle.com/database/technologies/xe18c-downloads.html +* copy into the same directory of the version in ls cmd + +## Build the docker image +* $ sh buildContainerImage.sh -v 18.4.0 -x + +``` +Oracle Database container image for 'xe' version 18.4.0 is ready to be extended: + + --> oracle/database:18.4.0-xe + + Build completed in 510 seconds. +``` + +## db client opensource +* https://dbeaver.io/download/ + +## launch the db +* $ docker run --name OracleXE \ + --shm-size=1g \ + -p 1521:1521 \ + -p 8081:8080 \ + -e ORACLE_PWD=12345 \ + -v oracle-data:/u01/app/oracle/oradata \ + oracle/database:18.4.0-xe + +``` +ORACLE PASSWORD FOR SYS AND SYSTEM: 12345 +Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts: +Confirm the password: +Configuring Oracle Listener. +Listener configuration succeeded. +Configuring Oracle Database XE. +Enter SYS user password: +****** +Enter SYSTEM user password: +***** +Enter PDBADMIN User Password: +***** +Prepare for db operation +7% complete +Copying database files +29% complete +Creating and starting Oracle instance +Completing Database Creation +47% complete +50% complete +Creating Pluggable Databases +54% complete +71% complete +Executing Post Configuration Actions +93% complete +Running Custom Scripts +100% complete +Database creation complete. For details check the logfiles at: + /opt/oracle/cfgtoollogs/dbca/XE. +Database Information: +Global Database Name:XE +System Identifier(SID):XE +Look at the log file "/opt/oracle/cfgtoollogs/dbca/XE/XE.log" for further details. + +Connect to Oracle Database using one of the connect strings: + Pluggable database: 2f7354fc4ee1/XEPDB1 + Multitenant container database: 2f7354fc4ee1 +Use https://localhost:5500/em to access Oracle Enterprise Manager for Oracle Database XE +The Oracle base remains unchanged with value /opt/oracle +######################### +DATABASE IS READY TO USE! +######################### +The following output is now a tail of the alert.log: +2021-10-05T23:03:43.054971+00:00 +XEPDB1(3):Resize operation completed for file# 10, old size 358400K, new size 368640K +2021-10-05T23:03:56.975470+00:00 +XEPDB1(3):CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):Completed: CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):ALTER DATABASE DEFAULT TABLESPACE "USERS" +XEPDB1(3):Completed: ALTER DATABASE DEFAULT TABLESPACE "USERS" +2021-10-05T23:04:03.318085+00:00 +ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE +Completed: ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE + +``` + +## Connect to db +``` +Host: localhost +Port: 1521 +Database: XE +Use SID +User name: SYS +Role: SYSDBA +Password: 12345 +``` + +## Clean up +* docker ps -a +* docker rm [OPTIONS] CONTAINER [CONTAINER...] +* docker rm -f [CONTAINER_ID] +* docker rm -f 2f7354fc4ee1 +* docker rm -f [CONTAINER_NAME] OracleXE +* docker rm -f OracleXE + +[HELP FROM BLOG](https://www.codesanook.com/setup-oracle-xe-database-on-docker-container-and-connect-with-dbeaver) + +--- +## Api Testing +### To Fetch the Employee +* $ curl -X GET http://localhost:8080/employee/1 +``` +{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +### To Creating the Employee +* $ curl -X POST http://localhost:8080/employee -H 'Content-Type: application/json' -d '{"empName":"adi","empEmail":"adi@kumar"}' +``` + {"empNo":5,"empName":"adi","empEmail":"adi@kumar"} +``` + +### To Create employee using procedure +* $ curl -X POST http://localhost:8080/employee/pro -H 'Content-Type: application/json' -d '{"empName":"adi","empEmail":"adi@kumar"}' +``` +EMPLOYEE INSERT SUCCESSFUL 1 EMPLOYEE DATA 5 adi adi@kumar +``` + +### To Update employee +* $ curl -X PUT http://localhost:8080/employee/5 -H 'Content-Type: application/json' -d '{"empNo":5,"empName":"adik","empEmail":"adi@kumar"}' +``` +{"empNo":5,"empName":"adik","empEmail":"adi@kumar"} +``` + +### To Update employee using procedure +* $ curl -X PUT http://localhost:8080/employee/pro/5 -H 'Content-Type: application/json' -d '{"empNo":5,"empName":"adiii","empEmail":"adi@kumar"}' +``` +EMPLOYEE UPDATED SUCCESSFUL 1UPDATED EMPLOYEE DATA5 adiii adi@kumar +``` + +## To Delete employee +* curl -X DELETE http://localhost:8080/employee/5 +``` +{"empNo":5,"empName":"adik","empEmail":"adi@kumar"} +``` + +## To Delete employee using procedure +* curl -X DELETE http://localhost:8080/employee/pro/5 +``` +EMPLOYEE DELETED SUCCESSFUL 1 EMPLOYEE DELETED 5 adiii adi@kumar +``` + +## To fetch employee +* $ curl -X GET http://localhost:8080/employee/1 +``` + {"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +## To Fetch employee using procedure +* curl -X GET http://localhost:8080/employee/pro/1 +``` +{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"} +``` + +## To fetch employees +* $ curl -X GET http://localhost:8080/employees +``` +[{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"},{"empNo":2,"empName":"radha","empEmail":"radha@singh"},{"empNo":3,"empName":"sonu","empEmail":"sonu@singh"},{"empNo":4,"empName":"amit","empEmail":"amit@kumar"}] +``` + +## To Fetch employees using procedure +* $ curl -X GET http://localhost:8080/employees/pro +``` +[{"empNo":1,"empName":"adarsh","empEmail":"adarsh@kumar"},{"empNo":2,"empName":"radha","empEmail":"radha@singh"},{"empNo":3,"empName":"sonu","empEmail":"sonu@singh"},{"empNo":4,"empName":"amit","empEmail":"amit@kumar"}] +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/pom.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/pom.xml new file mode 100644 index 00000000..d22ddc50 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-jpa-liquidbase-oracle-db-stored-procedure + 0.0.1-SNAPSHOT + springboot-jpa-liquidbase-oracle-db-stored-procedure + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.oracle.database.jdbc + ojdbc10 + 19.3.0.0 + + + + org.projectlombok + lombok + + + + org.liquibase + liquibase-core + + + + com.zaxxer + HikariCP + 2.6.0 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/.DS_Store new file mode 100644 index 00000000..8813de11 Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/.DS_Store new file mode 100644 index 00000000..e8e05c2d Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/.DS_Store new file mode 100644 index 00000000..3705dc35 Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..08d27d3d Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/.DS_Store b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/.DS_Store new file mode 100644 index 00000000..35af2b5e Binary files /dev/null and b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/.DS_Store differ diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..9813300f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,62 @@ +package com.espark.adarsh.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +@JsonIgnoreProperties(ignoreUnknown = true) +public class Employee { + + @Id + @Column(name = "EMP_NO") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMP_SEQ") + @SequenceGenerator(sequenceName = "EMPLOYEE_SEQ", allocationSize = 1, name = "EMP_SEQ") + private Long empNo; + + @Column(name = "EMP_NAME") + private String empName; + + @Column(name = "EMP_EMAIL") + private String empEmail; + + public Employee() { + } + + public Employee(String firstName, String empEmail) { + this.empName = firstName; + this.empEmail = empEmail; + } + + public Employee(Long empNo, String firstName, String empEmail) { + this.empNo = empNo; + this.empName = firstName; + this.empEmail = empEmail; + } + + public Long getEmpNo() { + return empNo; + } + + public void setEmpNo(Long empNo) { + this.empNo = empNo; + } + + public String getEmpName() { + return empName; + } + + public void setEmpName(String empName) { + this.empName = empName; + } + + public String getEmpEmail() { + return empEmail; + } + + public void setEmpEmail(String empEmail) { + this.empEmail = empEmail; + } +} + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..b0cebd69 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + + +@Repository +public interface EmployeeRepository extends CrudRepository { + + @Procedure(procedureName = "GET_EMPLOYEE_INFO", outputParameterName = "V_EMP_MSG") + String getEmployeeStringByProcedure(@Param("V_EMP_NO") Long empNo); + + + @Procedure(procedureName = "insertEmpProcedure", outputParameterName = "V_EMP_INSERT_MSG") + String saveEmployeeByProcedure( + @Param("V_EMPNAME") String empName + , @Param("V_EMPEMAIL") String empEmail + ); + + @Procedure(procedureName = "updateEmpProcedure", outputParameterName = "V_EMP_UPDATE_MSG") + String updateEmployeeByProcedure(@Param("V_EMPNO") Long empNo + , @Param("V_EMPNAME") String empName + , @Param("V_EMPEMAIL") String empEmail + ); + + @Procedure(procedureName = "deleteEmpProcedure", outputParameterName = "V_EMP_DEL_MSG") + String deleteEmployeeByProcedure(@Param("V_EMP_NO") Long empNo); + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java new file mode 100644 index 00000000..1c234713 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/respository/EmployeeSpRepository.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.ParameterMode; +import javax.persistence.StoredProcedureQuery; +import java.util.List; + +@Repository +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class EmployeeSpRepository { + + private final EntityManager entityManager; + + public List getEmployeeByProcedure(Long empNo) { + StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getEmpProcedure", Employee.class); + storedProcedureQuery.registerStoredProcedureParameter("V_EMP_NO", Long.class, ParameterMode.IN); + storedProcedureQuery.registerStoredProcedureParameter("EMP_DATA_CURSOR", List.class, ParameterMode.REF_CURSOR); + storedProcedureQuery.registerStoredProcedureParameter("V_SELECT_ERROR_MSG", String.class, ParameterMode.OUT); + storedProcedureQuery.setParameter("V_EMP_NO", empNo); + storedProcedureQuery.execute(); + // storedProcedureQuery.getOutputParameterValue("EMP_DATA_CURSOR"); + // storedProcedureQuery.getOutputParameterValue("V_SELECT_ERROR_MSG"); + return storedProcedureQuery.getResultList(); + } + + public List getEmployeesByProcedure() { + StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("getAllEmpProcedure", Employee.class); + storedProcedureQuery.registerStoredProcedureParameter("EMP_ALL_DATA_CURSOR", List.class, ParameterMode.REF_CURSOR); + storedProcedureQuery.registerStoredProcedureParameter("V_SELECT_ERROR_MSG", String.class, ParameterMode.OUT); + storedProcedureQuery.execute(); + // storedProcedureQuery.getOutputParameterValue("EMP_DATA_CURSOR"); + // storedProcedureQuery.getOutputParameterValue("V_SELECT_ERROR_MSG"); + return storedProcedureQuery.getResultList(); + } +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..2f11e2b6 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,72 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import com.espark.adarsh.respository.EmployeeSpRepository; +import liquibase.pro.packaged.E; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.LinkedList; +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Autowired + EmployeeSpRepository employeeSpRepository; + + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + public List getEmployeesByProcedure() { + return this.employeeSpRepository.getEmployeesByProcedure(); + } + + + public Employee getEmployee(Long id) { + return employeeRepository.findById(id).get(); + } + + public Employee getEmployeeByProcedure(Long id) { + + return this.employeeSpRepository.getEmployeeByProcedure(id).get(0); + //this.employeeRepository.getEmployeeByProcedure(id); + } + + public String getEmployeeStringByProcedure(Long id) { + return employeeRepository.getEmployeeStringByProcedure(id); + } + + public Employee removeEmployee(Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + public String removeEmployeeByProcedure(Long id){ + return this.employeeRepository.deleteEmployeeByProcedure(id); + } + + public Employee saveEmployee(Employee employee) { + return this.employeeRepository.save(employee); + } + + public String saveEmployeeByProcedure(Employee employee) { + return this.employeeRepository.saveEmployeeByProcedure(employee.getEmpName(),employee.getEmpEmail()); + } + + public Employee updateEmployee(Long id, Employee employee) { + return this.employeeRepository.save(employee); + } + + public String updateEmployeeByProcedure(Long id, Employee employee) { + return this.employeeRepository.updateEmployeeByProcedure(id,employee.getEmpName(),employee.getEmpEmail()); + } +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..6b51a85c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,71 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @GetMapping("/employees") + public List getAllEmployee() { + return this.employeeService.getAllEmployee(); + } + + @GetMapping("/employees/pro") + public List getEmployeesByProcedure() { + return this.employeeService.getEmployeesByProcedure(); + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeService.getEmployee(id); + } + + @GetMapping("/employee/pro/{id}") + public Employee getEmployeeByProcedure(@PathVariable("id")Long id) { + return this.employeeService.getEmployeeByProcedure(id); + } + + @GetMapping("/employee/pro/str/{id}") + public String getEmployeeData(@PathVariable("id") Long id) { + return this.employeeService.getEmployeeStringByProcedure(id); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + return this.employeeService.removeEmployee(id); + } + + @DeleteMapping("/employee/pro/{id}") + public String removeEmployeeByProcedure(@PathVariable("id") Long id) { + return this.employeeService.removeEmployeeByProcedure(id); + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeService.saveEmployee(employee); + } + + @PostMapping("/employee/pro") + public String saveEmployeeByProcedure(@RequestBody Employee employee) { + return this.employeeService.saveEmployeeByProcedure(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployee(id, employee); + } + + @PutMapping("/employee/pro/{id}") + public String updateEmployeeByProcedure(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeService.updateEmployeeByProcedure(id, employee); + } + +} diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/application.properties b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/application.properties new file mode 100644 index 00000000..4a8b960c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/application.properties @@ -0,0 +1,29 @@ + + + + +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE +spring.datasource.username=SYSTEM +spring.datasource.password=12345 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.generate-ddl=false + + +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml +spring.liquibase.drop-first=true + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/create_schema.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/create_schema.xml new file mode 100644 index 00000000..0d985dd7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/create_schema.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/delete_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/delete_employee.xml new file mode 100644 index 00000000..5b0a5cd7 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/delete_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employee.xml new file mode 100644 index 00000000..32973eef --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employees.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employees.xml new file mode 100644 index 00000000..261ee668 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/get_employees.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_data.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_data.xml new file mode 100644 index 00000000..5465b722 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_employee.xml new file mode 100644 index 00000000..666b36f4 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/insert_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/select_data.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/select_data.xml new file mode 100644 index 00000000..233310b3 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/select_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql new file mode 100644 index 00000000..55fc3a79 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql @@ -0,0 +1,14 @@ +DROP TABLE SYSTEM.EMPLOYEE; +DROP SEQUENCE SYSTEM.EMPLOYEE_SEQ; + +CREATE TABLE SYSTEM.Employee ( + EMP_NO INTEGER PRIMARY KEY, + EMP_NAME VARCHAR(250) NOT NULL, + EMP_EMAIL VARCHAR(250) NOT NULL +); + +CREATE SEQUENCE SYSTEM.EMPLOYEE_SEQ + MINVALUE 1 + MAXVALUE 9999999999 + START WITH 1 + INCREMENT BY 1; \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/delete_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/delete_employee.sql new file mode 100644 index 00000000..afd64c80 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/delete_employee.sql @@ -0,0 +1,21 @@ + +CREATE OR REPLACE PROCEDURE deleteEmpProcedure(V_EMP_NO IN EMPLOYEE.EMP_NO%TYPE,V_EMP_DEL_MSG OUT VARCHAR) + IS + V_EMP_DEL_COUNT NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(200); + BEGIN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = V_EMP_NO; + DELETE FROM EMPLOYEE WHERE EMP_NO = V_EMP_NO; + V_EMP_DEL_COUNT := SQL%ROWCOUNT; + IF V_EMP_DEL_COUNT >0 THEN + V_EMP_DEL_MSG:='EMPLOYEE DELETED SUCCESSFUL '||V_EMP_DEL_COUNT||' EMPLOYEE DELETED '||V_EMP_MSG; + ELSE + V_EMP_DEL_MSG:='EMPLOYEE NOT DELETED '||V_EMP_DEL_COUNT; + END IF; + COMMIT; + + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR(-20001, V_EMP_NO || ':$:' || SQLERRM, TRUE); + END deleteEmpProcedure; +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employee.sql new file mode 100644 index 00000000..ab19fedc --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employee.sql @@ -0,0 +1,27 @@ +CREATE OR REPLACE PROCEDURE getEmpProcedure( +V_EMP_NO IN EMPLOYEE.EMP_NO%TYPE +,EMP_DATA_CURSOR OUT SYS_REFCURSOR, +V_SELECT_ERROR_MSG OUT VARCHAR) +IS +BEGIN + OPEN EMP_DATA_CURSOR FOR + SELECT EMP.EMP_NO,EMP.EMP_NAME,EMP.EMP_EMAIL FROM EMPLOYEE EMP WHERE EMP.EMP_NO = V_EMP_NO; + + IF EMP_DATA_CURSOR%NOTFOUND THEN + V_SELECT_ERROR_MSG :='NO EMPLOYEE FOUND FOR EMP_NO '||V_EMP_NO; + END IF; + + EXCEPTION + WHEN NO_DATA_FOUND THEN + BEGIN + RAISE_APPLICATION_ERROR(-20610,'NO EMPLOYEE FOUND'); + END; + WHEN TOO_MANY_ROWS THEN + BEGIN + RAISE_APPLICATION_ERROR(-20612,'MORE THEN ONE EMPLOYEE FOUND FOR EMP_NO '||V_EMP_NO); + END; + WHEN OTHERS THEN + RAISE_APPLICATION_ERROR(-20001, V_EMP_NO || ':$:' || SQLERRM, TRUE) ; +END getEmpProcedure; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employees.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employees.sql new file mode 100644 index 00000000..f16cd95b --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/get_employees.sql @@ -0,0 +1,21 @@ +CREATE OR REPLACE PROCEDURE getAllEmpProcedure(EMP_ALL_DATA_CURSOR OUT SYS_REFCURSOR,V_SELECT_ERROR_MSG OUT VARCHAR) +IS +BEGIN + OPEN EMP_ALL_DATA_CURSOR FOR + + SELECT EMP.EMP_NO,EMP.EMP_NAME,EMP.EMP_EMAIL FROM EMPLOYEE EMP; + + IF EMP_ALL_DATA_CURSOR%NOTFOUND THEN + V_SELECT_ERROR_MSG :='NO EMPLOYEE FOUND '; + END IF; + + EXCEPTION + WHEN NO_DATA_FOUND THEN + BEGIN + V_SELECT_ERROR_MSG:='NO EMPLOYEE FOUND'; + END; + WHEN OTHERS THEN + RAISE_APPLICATION_ERROR (-20001, 'EXCEPTION GENERATED :$:' || SQLERRM, TRUE) ; +END getAllEmpProcedure; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql new file mode 100644 index 00000000..e59b69c0 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql @@ -0,0 +1,4 @@ +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES (SYSTEM.EMPLOYEE_SEQ.nextval,'adarsh', 'adarsh@kumar'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES (SYSTEM.EMPLOYEE_SEQ.nextval,'radha', 'radha@singh'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,'sonu', 'sonu@singh'); +INSERT INTO SYSTEM.Employee (EMP_NO, EMP_NAME, EMP_EMAIL) VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,'amit', 'amit@kumar'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_employee.sql new file mode 100644 index 00000000..05de8341 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/insert_employee.sql @@ -0,0 +1,25 @@ +CREATE OR REPLACE PROCEDURE insertEmpProcedure( + V_EMPNAME IN EMPLOYEE.EMP_NAME%TYPE + ,V_EMPEMAIL IN EMPLOYEE.EMP_EMAIL%TYPE + ,V_EMP_INSERT_MSG OUT VARCHAR2) +IS + V_EMP_INSERT_COUNT NUMBER(10) DEFAULT 0; + ID_EMP NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(200); +BEGIN + INSERT INTO EMPLOYEE (EMP_NO,EMP_NAME,EMP_EMAIL) VALUES(SYSTEM.EMPLOYEE_SEQ.nextval,V_EMPNAME,V_EMPEMAIL) + RETURNING EMP_NO INTO ID_EMP; + V_EMP_INSERT_COUNT := SQL%ROWCOUNT; + IF V_EMP_INSERT_COUNT >0 THEN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = ID_EMP; + V_EMP_INSERT_MSG:='EMPLOYEE INSERT SUCCESSFUL '||V_EMP_INSERT_COUNT ||' EMPLOYEE DATA '|| V_EMP_MSG; + ELSE + V_EMP_INSERT_MSG:='EMPLOYEE NOT INSERT '||V_EMP_INSERT_COUNT; + END IF; + COMMIT; + + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20001, V_EMPNAME||':$:'||V_EMPEMAIL|| ':$:' ||SQLERRM, TRUE) ; +END insertEmpProcedure; +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql new file mode 100644 index 00000000..a40f977c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql @@ -0,0 +1,9 @@ +CREATE OR REPLACE PROCEDURE GET_EMPLOYEE_INFO +( V_EMP_NO IN EMPLOYEE.EmpNo%TYPE, V_EMP_MSG OUT VARCHAR ) +AS +BEGIN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = V_EMP_NO; +END; +// + diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/update_employee.sql b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/update_employee.sql new file mode 100644 index 00000000..41aa337c --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/sql/update_employee.sql @@ -0,0 +1,24 @@ +CREATE OR REPLACE PROCEDURE updateEmpProcedure( + V_EMPNO IN EMPLOYEE.EMP_NO%TYPE + ,V_EMPNAME IN EMPLOYEE.EMP_NAME%TYPE + ,V_EMPEMAIL IN EMPLOYEE.EMP_EMAIL%TYPE + ,V_EMP_UPDATE_MSG OUT VARCHAR) +IS + V_EMP_UPDATE_COUNT NUMBER(10) DEFAULT 0; + V_EMP_MSG VARCHAR2(200); +BEGIN + UPDATE EMPLOYEE SET EMP_NAME=V_EMPNAME, EMP_EMAIL=V_EMPEMAIL WHERE EMP_NO=V_EMPNO; + V_EMP_UPDATE_COUNT := SQL%ROWCOUNT; + IF V_EMP_UPDATE_COUNT >0 THEN + SELECT EMP_NO ||' '|| EMP_NAME ||' '|| EMP_EMAIL INTO V_EMP_MSG + FROM EMPLOYEE WHERE EMPLOYEE.EMP_NO = V_EMPNO; + V_EMP_UPDATE_MSG:='EMPLOYEE UPDATED SUCCESSFUL '||V_EMP_UPDATE_COUNT || 'UPDATED EMPLOYEE DATA' ||V_EMP_MSG; + ELSE + V_EMP_UPDATE_MSG:='EMPLOYEE NOT UPDATED '||V_EMP_UPDATE_COUNT; + END IF; + COMMIT; + EXCEPTION + WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20001, V_EMPNO || ':$:' || SQLERRM, TRUE); +COMMIT; +END updateEmpProcedure; +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/update_employee.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/update_employee.xml new file mode 100644 index 00000000..c6e5db16 --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/changes/update_employee.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/db.changelog-master.xml b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 00000000..48423a5f --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-jpa-liquidbase-oracle-db-stored-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-kafka-binder/.gitignore b/APPLICATIONS/springboot-kafka-binder/.gitignore new file mode 100644 index 00000000..1ebd35ad --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/.gitignore @@ -0,0 +1,37 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +.DS_Store +/.DS_Store +*.DS_Store +*/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-kafka-binder/README.md b/APPLICATIONS/springboot-kafka-binder/README.md new file mode 100644 index 00000000..1a55fa8f --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/README.md @@ -0,0 +1,26 @@ +# Getting Started + +### https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz + +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic +``` + +### Api url + +``` +curl -X POST http://localhost:8080/api/message -H 'Content-Type: application/json' -d '{"name":"adarsh", "data":"welcome to espark"}' +``` diff --git a/APPLICATIONS/springboot-kafka-binder/pom.xml b/APPLICATIONS/springboot-kafka-binder/pom.xml new file mode 100644 index 00000000..48517ab9 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.2 + + + com.espark.adarsh + springboot-kafka-binder + 0.0.1-SNAPSHOT + springboot-kafka-binder + Demo project for Spring Boot + + 17 + 2021.0.0 + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.kafka + kafka-streams + + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.cloud + spring-cloud-stream + test + test-binder + test-jar + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/SpringbootKafkaBinderApplication.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/SpringbootKafkaBinderApplication.java new file mode 100644 index 00000000..ed3d450c --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/SpringbootKafkaBinderApplication.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import com.espark.adarsh.config.ApplicationKafkaChannelConfig; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; + +@EnableBinding(ApplicationKafkaChannelConfig.class) +@SpringBootApplication +public class SpringbootKafkaBinderApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootKafkaBinderApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/bean/ApplicationMessage.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/bean/ApplicationMessage.java new file mode 100644 index 00000000..ea5407ef --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/bean/ApplicationMessage.java @@ -0,0 +1,6 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public record ApplicationMessage(String name, String data) implements Serializable { +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/config/ApplicationKafkaChannelConfig.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/config/ApplicationKafkaChannelConfig.java new file mode 100644 index 00000000..d876104f --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/config/ApplicationKafkaChannelConfig.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.config; + +import org.springframework.cloud.stream.annotation.Input; +import org.springframework.cloud.stream.annotation.Output; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.SubscribableChannel; + +public interface ApplicationKafkaChannelConfig { + + String INPUT_CHANNEL = "espark-in-channel"; + String OUTPUT_CHANNEL = "espark-out-channel"; + String ERROR_CHANNEL = "error-out-channel"; + + @Input(INPUT_CHANNEL) + SubscribableChannel applicationSubscriberStream(); + + @Output(OUTPUT_CHANNEL) + MessageChannel applicationPublisherStream(); + + @Output(ERROR_CHANNEL) + MessageChannel applicationERRORStream(); +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java new file mode 100644 index 00000000..01d02b5e --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.coverters; + +import com.espark.adarsh.bean.ApplicationMessage; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.errors.SerializationException; +import org.apache.kafka.common.serialization.Deserializer; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class MessageDeSerializer implements Deserializer { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public ApplicationMessage deserialize(String topic, byte[] data) { + try { + System.out.println("MessageDeSerializer"); + return objectMapper.readValue(new String(data), ApplicationMessage.class); + } catch (IOException e) { + throw new SerializationException(e); + } + } +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java new file mode 100644 index 00000000..c6a72e63 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.coverters; + +import com.espark.adarsh.bean.ApplicationMessage; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.errors.SerializationException; +import org.apache.kafka.common.serialization.Serializer; +import org.springframework.stereotype.Component; + +@Component +public class MessageSerializer implements Serializer { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public byte[] serialize(String topic, ApplicationMessage applicationMessage) { + try { + System.out.println("MessageSerializer"); + return objectMapper.writeValueAsBytes(applicationMessage); + } catch (JsonProcessingException e) { + throw new SerializationException(e); + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/exception/RetryableException.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/exception/RetryableException.java new file mode 100644 index 00000000..0d6eaab8 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/exception/RetryableException.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.exception; + +public class RetryableException extends RuntimeException{ + public RetryableException() { + } + + public RetryableException(String message) { + super(message); + } + + public RetryableException(String message, Throwable cause) { + super(message, cause); + } + + public RetryableException(Throwable cause) { + super(cause); + } + + public RetryableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/listner/ApplicationMessageListener.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/listner/ApplicationMessageListener.java new file mode 100644 index 00000000..108e692c --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/listner/ApplicationMessageListener.java @@ -0,0 +1,25 @@ +package com.espark.adarsh.listner; + +import com.espark.adarsh.bean.ApplicationMessage; +import com.espark.adarsh.config.ApplicationKafkaChannelConfig; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.Message; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class ApplicationMessageListener { + + @StreamListener(ApplicationKafkaChannelConfig.INPUT_CHANNEL) + public void process(Message message) { + Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class); + if (acknowledgment != null) { + log.info("Acknowledgment provided"); + acknowledgment.acknowledge(); + } + log.info(message.getPayload().toString()); + } +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java new file mode 100644 index 00000000..e831248f --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.util; + + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class TimeUtil { + + private static DateTimeFormatter dtfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + + public static String getTime() { + Instant now = Instant.now(); + ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.systemDefault()); + return dtfDateTime.format(zonedDateTime); + } +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/web/ApplicationMessagePublisherController.java b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/web/ApplicationMessagePublisherController.java new file mode 100644 index 00000000..5a69a80e --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/java/com/espark/adarsh/web/ApplicationMessagePublisherController.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.ApplicationMessage; +import com.espark.adarsh.config.ApplicationKafkaChannelConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +public class ApplicationMessagePublisherController { + + @Autowired + ApplicationKafkaChannelConfig applicationKafkaChannelConfig; + + @PostMapping("/api/message") + public Map postMessage(@RequestBody ApplicationMessage applicationMessage) { + + if (applicationKafkaChannelConfig.applicationPublisherStream().send(MessageBuilder.withPayload(applicationMessage) + .setHeader("content-type", "application/json") + .setErrorChannelName("espark-error-channel") + .build())) { + return new HashMap() { + { + put("message", "message posted on kafka is successful "); + } + }; + } else { + return new HashMap() { + { + put("message", "message posted on kafka is failed"); + } + }; + } + } +} diff --git a/APPLICATIONS/springboot-kafka-binder/src/main/resources/application.yml b/APPLICATIONS/springboot-kafka-binder/src/main/resources/application.yml new file mode 100644 index 00000000..93ab5338 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/main/resources/application.yml @@ -0,0 +1,50 @@ +spring: + cloud: + stream: + kafka: + binder: + auto-create-topics: true + auto-alter-topics: false + brokers: + - localhost:9092 + bindings: + espark-in-channel: + group: espark-group + destination: espark-topic + content-type: application/json + consumer: + maxAttempts: 5 + backOffInitialInterval: 100 + defaultRetryable: false + useNativeEncoding: true + retryableExceptions: + com.espark.adarsh.exception.RetryableException: true + configuration: + value.deserializer: com.espark.adarsh.coverters.MessageDeSerializer + value.serializer: com.espark.adarsh.coverters.MessageSerializer + concurrency: 10 + autoStartup: true + espark-out-channel: + group: espark-group + destination: espark-topic + content-type: application/json + producer: + configuration: + useNativeEncoding: true + value.deserializer: com.espark.adarsh.coverters.MessageDeSerializer + value.serializer: com.espark.adarsh.coverters.MessageSerializer + autoStartup: true + espark-error-channel: + group: espark-group + destination: espark-error-topic + contentType: application/json + consumer: + useNativeEncoding: true + maxAttempts: 5 + backOffInitialInterval: 100 + defaultRetryable: false + retryableExceptions: + com.espark.adarsh.exception.RetryableException: true + concurrency: 10 + autoStartup: true + diff --git a/APPLICATIONS/springboot-kafka-binder/src/test/java/com/espark/adarsh/SpringbootKafkaBinderApplicationTests.java b/APPLICATIONS/springboot-kafka-binder/src/test/java/com/espark/adarsh/SpringbootKafkaBinderApplicationTests.java new file mode 100644 index 00000000..d190811e --- /dev/null +++ b/APPLICATIONS/springboot-kafka-binder/src/test/java/com/espark/adarsh/SpringbootKafkaBinderApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootKafkaBinderApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/.gitignore b/APPLICATIONS/springboot-kafka-stream-binder/.gitignore new file mode 100644 index 00000000..52030ce1 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/.gitignore @@ -0,0 +1,37 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +*.DS_Store +/*.DS_Store +.DS_Store +/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-kafka-stream-binder/README.md b/APPLICATIONS/springboot-kafka-stream-binder/README.md new file mode 100644 index 00000000..81499377 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/README.md @@ -0,0 +1,19 @@ +# Getting Started + +### https://www.apache.org/dyn/closer.cgi?path=/kafka/2.5.0/kafka_2.12-2.5.0.tgz +``` +Start Zookeeper +bin/zookeeper-server-start.sh config/zookeeper.properties + +Start Kafka Server +bin/kafka-server-start.sh config/server.properties + +Create Kafka Topic +bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic espark-topic + +Consume from the Kafka Topic via Console +bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic espark-topic --from-beginning + +Deleting topic +bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic espark-topic +``` diff --git a/APPLICATIONS/springboot-kafka-stream-binder/pom.xml b/APPLICATIONS/springboot-kafka-stream-binder/pom.xml new file mode 100644 index 00000000..76af1f13 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.1 + + + com.espark.adarsh + springboot-kafka-stream-binder + 0.0.1-SNAPSHOT + springboot-kafka-stream-binder + Demo project for Spring Boot + + 17 + 2021.0.0 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.kafka + kafka-streams + + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.cloud + spring-cloud-stream + test + test-binder + test-jar + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplication.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplication.java new file mode 100644 index 00000000..a34958a9 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplication.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@EnableScheduling +@SpringBootApplication +public class SpringbootKafkaStreamBinderApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootKafkaStreamBinderApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/bean/Message.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/bean/Message.java new file mode 100644 index 00000000..31a16542 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/bean/Message.java @@ -0,0 +1,5 @@ +package com.espark.adarsh.bean; + +public record Message(String data) { +} + diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..3a745036 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.bean.Message; +import com.espark.adarsh.util.TimeUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +@Configuration +public class ApplicationConfig { + + public final static String OUT_CHANNEL = "kafkaApplicationMessageProducer-out-0"; + public final static String IN_CHANNEL = "kafkaApplicationMessageConsumer-out-0"; + + + @Bean + public Consumer kafkaApplicationMessageConsumer() { + return message -> System.out.println("received " + message); + } + + @Bean + public Supplier kafkaApplicationMessageProducer(TimeUtil timeUtil) { + return () -> new Message("SUPPLIER-> Welcome to the Espark " + timeUtil.getTime()); + } +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java new file mode 100644 index 00000000..0c81b4fb --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageDeSerializer.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.coverters; + +import com.espark.adarsh.bean.Message; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.errors.SerializationException; +import org.apache.kafka.common.serialization.Deserializer; +import java.io.IOException; + +public class MessageDeSerializer implements Deserializer { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public Message deserialize(String topic, byte[] data) { + try { + return objectMapper.readValue(new String(data), Message.class); + } catch (IOException e) { + throw new SerializationException(e); + } + } +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java new file mode 100644 index 00000000..e8ad58ed --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/coverters/MessageSerializer.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.coverters; + +import com.espark.adarsh.bean.Message; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.kafka.common.errors.SerializationException; +import org.apache.kafka.common.serialization.Serializer; + +public class MessageSerializer implements Serializer { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public byte[] serialize(String topic, Message data) { + try { + return objectMapper.writeValueAsBytes(data); + } catch (JsonProcessingException e) { + throw new SerializationException(e); + } + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/KafkaMessageProducer.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/KafkaMessageProducer.java new file mode 100644 index 00000000..c2c615ac --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/KafkaMessageProducer.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.bean.Message; +import com.espark.adarsh.config.ApplicationConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.function.StreamBridge; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + + +@Component +public class KafkaMessageProducer { + + @Autowired + private StreamBridge streamBridge; + + + @Autowired + TimeUtil timeUtil; + + + @Scheduled(cron = "*/2 * * * * *") + public void sendMessage() { + streamBridge.send(ApplicationConfig.OUT_CHANNEL, new Message("PUBLISHER:-> Welcome to the espark " + timeUtil.getTime())); + } +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java new file mode 100644 index 00000000..57af3ad9 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/java/com/espark/adarsh/util/TimeUtil.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.util; + +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +@Component +public class TimeUtil { + + private DateTimeFormatter dtfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + + public String getTime() { + Instant now = Instant.now(); + ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.systemDefault()); + return dtfDateTime.format(zonedDateTime); + } +} diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/main/resources/application.yml b/APPLICATIONS/springboot-kafka-stream-binder/src/main/resources/application.yml new file mode 100644 index 00000000..5dbda627 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/main/resources/application.yml @@ -0,0 +1,29 @@ +spring: + cloud: + function: + definition: kafkaApplicationMessageConsumer;kafkaApplicationMessageProducer + stream: + kafka: + bindings: + kafkaApplicationMessageProducer-out-0: + kafkaApplicationMessageProducer: + applicationId: KafkaApplicationMessageProducer + configuration: + value.serializer: com.espark.adarsh.coverters.MessageSerializer + kafkaApplicationMessageConsumer-in-0: + kafkaApplicationMessageConsumer: + applicationId: KafkaApplicationMessageConsumer + configuration: + value.deserializer: com.espark.adarsh.coverters.MessageDeSerializer + binder: + brokers: localhost:9092 + + bindings: + kafkaApplicationMessageProducer-out-0: + destination: espark-topic + kafkaApplicationMessageProducer: + useNativeEncoding: true # Enables using the custom serializer + kafkaApplicationMessageConsumer-in-0: + destination: espark-topic + kafkaApplicationMessageConsumer: + use-native-decoding: true # Enables using the custom deserializer diff --git a/APPLICATIONS/springboot-kafka-stream-binder/src/test/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplicationTests.java b/APPLICATIONS/springboot-kafka-stream-binder/src/test/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplicationTests.java new file mode 100644 index 00000000..05747634 --- /dev/null +++ b/APPLICATIONS/springboot-kafka-stream-binder/src/test/java/com/espark/adarsh/SpringbootKafkaStreamBinderApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootKafkaStreamBinderApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-kinesis/.gitignore b/APPLICATIONS/springboot-kinesis/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..9cc84ea9 Binary files /dev/null and b/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..b573bb50 --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/APPLICATIONS/springboot-kinesis/pom.xml b/APPLICATIONS/springboot-kinesis/pom.xml new file mode 100644 index 00000000..ddb6b73f --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-kinesis + 0.0.1-SNAPSHOT + jar + + springboot-kinesis + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + Fishtown.BUILD-SNAPSHOT + + + + + + org.springframework.cloud + spring-cloud-stream-dependencies + ${spring-cloud-stream.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.cloud + spring-cloud-starter-stream-kinesis + 1.0.0.BUILD-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-security + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..413e59db --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableBinding({ InputChannels.class, OutputChannels.class }) +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/InputChannels.java b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/InputChannels.java new file mode 100644 index 00000000..052da78f --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/InputChannels.java @@ -0,0 +1,7 @@ +package com.espark.adarsh; + + +public interface InputChannels { + @Input + SubscribableChannel rick(); +} diff --git a/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/OutputChannels.java b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/OutputChannels.java new file mode 100644 index 00000000..94dae2d4 --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/src/main/java/com/espark/adarsh/OutputChannels.java @@ -0,0 +1,6 @@ +package com.espark.adarsh; + +public interface OutputChannels { + @Output + MessageChannel microverse(); +} diff --git a/APPLICATIONS/springboot-kinesis/src/main/resources/application.properties b/APPLICATIONS/springboot-kinesis/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-kinesis/src/main/resources/application.yml b/APPLICATIONS/springboot-kinesis/src/main/resources/application.yml new file mode 100644 index 00000000..f89295c0 --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/src/main/resources/application.yml @@ -0,0 +1,38 @@ +originator: KinesisProducer +server: + port: 64398 +management: + port: 8082 + context-path: /manage +security: + user: + name: admin + password: 2c76788d-e661-49fd-baba-4b41e7c1dd47 + + +spring: + cloud: + stream: + bindings: + ordersOut: + destination: test_stream + content-type: application/json + producer: + partitionKeyExpression: "1" + ordersIn: + destination: test_stream + content-type: application/json + +cloud: + aws: + region: + static: eu-west-1 + + +logging: + level: + com: + amazonaws: INFO + org: + apache: + http: INFO \ No newline at end of file diff --git a/APPLICATIONS/springboot-kinesis/src/test/java/com/espark/adarsh/ApplicationTest.java b/APPLICATIONS/springboot-kinesis/src/test/java/com/espark/adarsh/ApplicationTest.java new file mode 100644 index 00000000..9d9484fc --- /dev/null +++ b/APPLICATIONS/springboot-kinesis/src/test/java/com/espark/adarsh/ApplicationTest.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/.gitignore b/APPLICATIONS/springboot-liquidbase-oracle-db/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/README.md b/APPLICATIONS/springboot-liquidbase-oracle-db/README.md new file mode 100644 index 00000000..990a9851 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/README.md @@ -0,0 +1,36 @@ +# SPRINGBOOT JPA ORACLE DB LIQUIDBASE + +--- + +### To Build Code +* mvn clean package + +### TO CHECK DATA INTO THE DB +* SELECT * FROM SYSTEM.EMPLOYEE; +* SELECT * FROM SYSTEM.DATABASECHANGELOG; + +## TO CHECK SQL SCRPT WORKED OR NOT +* SELECT * FROM SYSTEM.DATABASECHANGELOG; +* TRUNCATE TABLE SYSTEM.DATABASECHANGELOG; + +## TO DROP THE TABLES IN DB +* DROP PROCEDURE SYSTEM.GET_EMPLOYEE_INFO; +* DROP TABLE SYSTEM.EMPLOYEE; +* DROP TABLE SYSTEM.DATABASECHANGELOG; +* DROP TABLE SYSTEM.DATABASECHANGELOGLOCK; + + +## TO TEST THE STORED PROCEDURE +``` +SET SERVEROUTPUT ON; +DECLARE + V_EMP_MSG VARCHAR(50) ; +BEGIN + SYSTEM.GET_EMPLOYEE_INFO(&V_EMP_ID,V_EMP_MSG); + DBMS_OUTPUT.PUT_LINE(V_EMP_MSG); +END; +/ +``` + +### [step by step guide for oracle xe db docker image cration ](oracle-db-xe-docker-image-building-process.md) + diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/oracle-db-xe-docker-image-building-process.md b/APPLICATIONS/springboot-liquidbase-oracle-db/oracle-db-xe-docker-image-building-process.md new file mode 100644 index 00000000..51889c48 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/oracle-db-xe-docker-image-building-process.md @@ -0,0 +1,118 @@ + +## Clone the git hub from oracle +* git clone git@github.com:oracle/docker-images.git + +## move to the docker file directory +* $ cd docker-images/OracleDatabase/SingleInstance/dockerfiles + +# list the supported version +* $ ls +``` +11.2.0.2 12.2.0.1 18.4.0 21.3.0 +12.1.0.2 18.3.0 19.3.0 buildContainerImage.sh +``` + +## url to download the version of oracle zip +* https://www.oracle.com/database/technologies/xe18c-downloads.html +* copy into the same directory of the version in ls cmd + +## Build the docker image +* $ sh buildContainerImage.sh -v 18.4.0 -x + +``` +Oracle Database container image for 'xe' version 18.4.0 is ready to be extended: + + --> oracle/database:18.4.0-xe + + Build completed in 510 seconds. +``` + +## db client opensource +* https://dbeaver.io/download/ + +## launch the db +* $ docker run --name OracleXE \ +--shm-size=1g \ +-p 1521:1521 \ +-p 8081:8080 \ +-e ORACLE_PWD=12345 \ +-v oracle-data:/u01/app/oracle/oradata \ +oracle/database:18.4.0-xe + +``` +ORACLE PASSWORD FOR SYS AND SYSTEM: 12345 +Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts: +Confirm the password: +Configuring Oracle Listener. +Listener configuration succeeded. +Configuring Oracle Database XE. +Enter SYS user password: +****** +Enter SYSTEM user password: +***** +Enter PDBADMIN User Password: +***** +Prepare for db operation +7% complete +Copying database files +29% complete +Creating and starting Oracle instance +Completing Database Creation +47% complete +50% complete +Creating Pluggable Databases +54% complete +71% complete +Executing Post Configuration Actions +93% complete +Running Custom Scripts +100% complete +Database creation complete. For details check the logfiles at: + /opt/oracle/cfgtoollogs/dbca/XE. +Database Information: +Global Database Name:XE +System Identifier(SID):XE +Look at the log file "/opt/oracle/cfgtoollogs/dbca/XE/XE.log" for further details. + +Connect to Oracle Database using one of the connect strings: + Pluggable database: 2f7354fc4ee1/XEPDB1 + Multitenant container database: 2f7354fc4ee1 +Use https://localhost:5500/em to access Oracle Enterprise Manager for Oracle Database XE +The Oracle base remains unchanged with value /opt/oracle +######################### +DATABASE IS READY TO USE! +######################### +The following output is now a tail of the alert.log: +2021-10-05T23:03:43.054971+00:00 +XEPDB1(3):Resize operation completed for file# 10, old size 358400K, new size 368640K +2021-10-05T23:03:56.975470+00:00 +XEPDB1(3):CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):Completed: CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):ALTER DATABASE DEFAULT TABLESPACE "USERS" +XEPDB1(3):Completed: ALTER DATABASE DEFAULT TABLESPACE "USERS" +2021-10-05T23:04:03.318085+00:00 +ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE +Completed: ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE + +``` + +## Connect to db +``` +Host: localhost +Port: 1521 +Database: XE +Use SID +User name: SYS +Role: SYSDBA +Password: 12345 +``` + +## Clean up +* docker ps -a +* docker rm [OPTIONS] CONTAINER [CONTAINER...] +* docker rm -f [CONTAINER_ID] +* docker rm -f 2f7354fc4ee1 +* docker rm -f [CONTAINER_NAME] OracleXE +* docker rm -f OracleXE + +[HELP FROM BLOG](https://www.codesanook.com/setup-oracle-xe-database-on-docker-container-and-connect-with-dbeaver) \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/pom.xml b/APPLICATIONS/springboot-liquidbase-oracle-db/pom.xml new file mode 100644 index 00000000..c1c008ce --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-liquidbase-oracle-db + 0.0.1-SNAPSHOT + springboot-liquidbase-oracle-db + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.oracle.database.jdbc + ojdbc10 + 19.3.0.0 + + + + org.liquibase + liquibase-core + + + + com.zaxxer + HikariCP + 2.6.0 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/.DS_Store b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/.DS_Store new file mode 100644 index 00000000..e8e05c2d Binary files /dev/null and b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/.DS_Store differ diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/.DS_Store b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/.DS_Store new file mode 100644 index 00000000..3705dc35 Binary files /dev/null and b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/.DS_Store differ diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/.DS_Store b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/.DS_Store new file mode 100644 index 00000000..08d27d3d Binary files /dev/null and b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/.DS_Store differ diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/.DS_Store b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/.DS_Store new file mode 100644 index 00000000..35af2b5e Binary files /dev/null and b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/.DS_Store differ diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..bea6c6b4 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long empId; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long empId, String firstName, String lastName, String career) { + this.empId = empId; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getEmpId() { + return empId; + } + + public void setEmpId(Long empId) { + this.empId = empId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..bf900f31 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import javax.transaction.Transactional; + +@Repository +public interface EmployeeRepository extends CrudRepository { + + @Procedure(procedureName = "SYSTEM.GET_EMPLOYEE_INFO",outputParameterName = "V_EMP_MSG") + String getEmployeeData(@Param("V_EMP_ID") Long empId); +} diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..7b0635ce --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + + @GetMapping("/employee/data/{id}") + public String getEmployeeData(@PathVariable("id") Long id) { + return this.employeeRepository.getEmployeeData(id); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/application.properties b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/application.properties new file mode 100644 index 00000000..4a8b960c --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/application.properties @@ -0,0 +1,29 @@ + + + + +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE +spring.datasource.username=SYSTEM +spring.datasource.password=12345 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.generate-ddl=false + + +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml +spring.liquibase.drop-first=true + diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/create_schema.xml b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/create_schema.xml new file mode 100644 index 00000000..0d985dd7 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/create_schema.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/insert_data.xml b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/insert_data.xml new file mode 100644 index 00000000..5465b722 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/insert_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/select_data.xml b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/select_data.xml new file mode 100644 index 00000000..233310b3 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/select_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/create_schema.sql b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/create_schema.sql new file mode 100644 index 00000000..d5f1ce21 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/create_schema.sql @@ -0,0 +1,8 @@ +DROP TABLE SYSTEM.EMPLOYEE; + +CREATE TABLE SYSTEM.employee ( + emp_id INTEGER PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/insert_data.sql b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/insert_data.sql new file mode 100644 index 00000000..03e63803 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/insert_data.sql @@ -0,0 +1,4 @@ +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (100,'adarsh', 'kumar', 'It'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (200,'radha', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(300,'sonu', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(400,'amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/select_data.sql b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/select_data.sql new file mode 100644 index 00000000..fd417d50 --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/changes/sql/select_data.sql @@ -0,0 +1,10 @@ +CREATE OR REPLACE PROCEDURE SYSTEM.GET_EMPLOYEE_INFO +( V_EMP_ID IN EMPLOYEE.EMP_ID%TYPE, V_EMP_MSG OUT VARCHAR ) +AS +BEGIN + SELECT EMP_ID ||' '|| FIRST_NAME ||' '|| LAST_NAME ||' '|| CAREER INTO V_EMP_MSG + FROM SYSTEM.EMPLOYEE WHERE SYSTEM.EMPLOYEE.EMP_ID = V_EMP_ID; +END; + +// + diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/db.changelog-master.xml b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 00000000..2ac9eefc --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-liquidbase-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-liquidbase-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-liquidbase-oracle-db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-load-shedding/.gitignore b/APPLICATIONS/springboot-load-shedding/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-load-shedding/README.md b/APPLICATIONS/springboot-load-shedding/README.md new file mode 100644 index 00000000..e5d6e891 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/README.md @@ -0,0 +1,9 @@ +# Springboot Load Shedding + +---- + +### To build +* mvn clean package + +### To Test +* seq 1 10 | xargs -n1 -P5 curl -X GET "http://localhost:9090/api/wish/adarsh" diff --git a/APPLICATIONS/springboot-load-shedding/pom.xml b/APPLICATIONS/springboot-load-shedding/pom.xml new file mode 100644 index 00000000..f197261a --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.7-SNAPSHOT + + + com.espark.adarsh + springboot-load-shedding + 0.0.1-SNAPSHOT + springboot-load-shedding + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + diff --git a/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/SpringbootLoadSheddingApplication.java b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/SpringbootLoadSheddingApplication.java new file mode 100644 index 00000000..510b15f1 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/SpringbootLoadSheddingApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootLoadSheddingApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootLoadSheddingApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/filter/ApplicationFilter.java b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/filter/ApplicationFilter.java new file mode 100644 index 00000000..9d09f810 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/filter/ApplicationFilter.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.filter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; + +@Component +public class ApplicationFilter implements Filter { + + @Value("${spring.request.limit}") + private int maxRequests; + + @Value("${spring.request.message}") + private String message; + + private AtomicInteger currentRequests = new AtomicInteger(0); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + byte[] byteMessage = message.getBytes(StandardCharsets.UTF_8); + if (currentRequests.get() >= maxRequests) { + HttpServletResponse response = (HttpServletResponse) servletResponse; + response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + response.getOutputStream().write(byteMessage); + return; + } + currentRequests.incrementAndGet(); + try { + filterChain.doFilter(servletRequest, servletResponse); + } finally { + currentRequests.decrementAndGet(); + } + } +} diff --git a/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/service/WishService.java b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/service/WishService.java new file mode 100644 index 00000000..a2bd39b5 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/service/WishService.java @@ -0,0 +1,40 @@ +package com.espark.adarsh.service; + +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.Map; + +@Service +public class WishService { + + public Map wish(String name) { + int hour = LocalDateTime.now().getHour(); + if (hour > 0 && hour < 11) { + return new HashMap() { + { + { + put("message", " Good morning " + name); + } + } + }; + } else if (hour > 11 && hour < 16) { + return new HashMap() { + { + { + put("message", " Good After noon " + name); + } + } + }; + } else { + return new HashMap() { + { + { + put("message", " Good Evening " + name); + } + } + }; + } + } +} diff --git a/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/web/ApplicationController.java b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/web/ApplicationController.java new file mode 100644 index 00000000..68123581 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/main/java/com/espark/adarsh/web/ApplicationController.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.WishService; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class ApplicationController { + + @Autowired + WishService wishService; + + + @GetMapping("/wish/{name}") + public ResponseEntity> wish(@PathVariable("name") String name) { + return ResponseEntity.ok(wishService.wish(name)); + } + +} diff --git a/APPLICATIONS/springboot-load-shedding/src/main/resources/application.yml b/APPLICATIONS/springboot-load-shedding/src/main/resources/application.yml new file mode 100644 index 00000000..3e52e711 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/main/resources/application.yml @@ -0,0 +1,12 @@ + +server: + port: 9090 + +spring: + application: + name: springboot-load-shedding + request: + limit: 3 + message: "Server Unavailable. Please retry after sometime.." + + diff --git a/APPLICATIONS/springboot-load-shedding/src/test/java/com/espark/adarsh/SpringbootLoadSheddingApplicationTests.java b/APPLICATIONS/springboot-load-shedding/src/test/java/com/espark/adarsh/SpringbootLoadSheddingApplicationTests.java new file mode 100644 index 00000000..75ff57f5 --- /dev/null +++ b/APPLICATIONS/springboot-load-shedding/src/test/java/com/espark/adarsh/SpringbootLoadSheddingApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootLoadSheddingApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-logs/.gitignore b/APPLICATIONS/springboot-logs/.gitignore new file mode 100644 index 00000000..b1cc65d4 --- /dev/null +++ b/APPLICATIONS/springboot-logs/.gitignore @@ -0,0 +1,34 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +/log/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-logs/Dockerfile b/APPLICATIONS/springboot-logs/Dockerfile new file mode 100644 index 00000000..549a1543 --- /dev/null +++ b/APPLICATIONS/springboot-logs/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8 +MAINTAINER adarsh.kumar@gmail.com +COPY target/springboot-logs.jar springboot-logs.jar +ENTRYPOINT ["java","-jar","springboot-logs.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-logs/README.md b/APPLICATIONS/springboot-logs/README.md new file mode 100644 index 00000000..a3c986fd --- /dev/null +++ b/APPLICATIONS/springboot-logs/README.md @@ -0,0 +1,37 @@ +# SPRING BOOT LOG SAMPLE + +### build the code +* $ mvn clean packge +* $ mvn spring-boot:run +* $ java -jar target/springboot-logs.jar + + +### TO BUILD & RUN TFS API SERVER VIA DOCKER +* $ docker build -f Dockerfile -t springboot-logs . +* $ docker run -e "SPRING_PROFILES_ACTIVE=default" -p 9090:9090 -t springboot-logs + +### to debug the logs of the docker container +* $ docker ps -a +* $ docker exec -it cat /var/[docker-container-file-system-path]]/logs/application.log > $HOME/spring.log [host-machine-file-system ] +* $ docker exec -it friendly_boyd cat /var/logs/application.log > $HOME/spring.log + + +### FOR DIRECTLY PRODUCING LOGS TO HOST MACHINE RATHER THEN THE DOCKER CONTAINER +* $ docker run -v /path/on/host:/path/in/container +* $ docker container run -p 9090:9090 -v $HOME/log:/var/logs springboot-logs + +# + +### FOR TESTING +* http://localhost:8080/actuator/health +* http://localhost:8080/actuator/info +* http://localhost:8080/actuator/env +* http://localhost:8080/actuator/beans +* http://localhost:8080/actuator/metrics + + + + + + + diff --git a/APPLICATIONS/springboot-logs/pom.xml b/APPLICATIONS/springboot-logs/pom.xml new file mode 100644 index 00000000..d27e866e --- /dev/null +++ b/APPLICATIONS/springboot-logs/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.espark.adarsh + springboot-logs + 0.0.1-SNAPSHOT + springboot-logs + Demo project for Spring Boot + + + 1.8 + Hoxton.SR6 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-logs/src/main/java/com/espark/adarsh/LogsApplication.java b/APPLICATIONS/springboot-logs/src/main/java/com/espark/adarsh/LogsApplication.java new file mode 100644 index 00000000..8e066114 --- /dev/null +++ b/APPLICATIONS/springboot-logs/src/main/java/com/espark/adarsh/LogsApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LogsApplication { + + public static void main(String[] args) { + SpringApplication.run(LogsApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-logs/src/main/resources/application.properties b/APPLICATIONS/springboot-logs/src/main/resources/application.properties new file mode 100644 index 00000000..e69de29b diff --git a/APPLICATIONS/springboot-logs/src/main/resources/application.yaml b/APPLICATIONS/springboot-logs/src/main/resources/application.yaml new file mode 100644 index 00000000..d4f391bb --- /dev/null +++ b/APPLICATIONS/springboot-logs/src/main/resources/application.yaml @@ -0,0 +1,42 @@ +server: + port: 8080 + +spring: + application: + name: springboot-logs + +info: + app: + name: log-sample + description: log0sample + version: 1.0.0 + +management: + endpoints: + web: + exposure: + include: "*" + info: + enabled: true + health: + enabled: true + env: + enabled: true + security: + enabled: false + +logging: + level: + root: DEBUG + com.espark.adarsh: DEBUG + org.springframework.web: DEBUG + group: + com.espark.adarsh: DEBUG + org.springframework.web: DEBUG + file: + name: /var/logs/application.log + max-size: 1MB + max-history: 10 + pattern: + rolling-file-name: ${LOG_FILE}.%d{yyyy-MM-dd}.%i.zip + level: '${spring.application.name} - [%X{traceId}/%X{spanId}] %X{sessionId} %-5p [%t] %C{2} - %m%n' diff --git a/APPLICATIONS/springboot-logs/src/test/java/com/espark/adarsh/LogsApplicationTests.java b/APPLICATIONS/springboot-logs/src/test/java/com/espark/adarsh/LogsApplicationTests.java new file mode 100644 index 00000000..b1b15601 --- /dev/null +++ b/APPLICATIONS/springboot-logs/src/test/java/com/espark/adarsh/LogsApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class LogsApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-maven-profiling/.gitignore b/APPLICATIONS/springboot-maven-profiling/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-maven-profiling/docker-compose.yaml b/APPLICATIONS/springboot-maven-profiling/docker-compose.yaml new file mode 100644 index 00000000..f277db9f --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/docker-compose.yaml @@ -0,0 +1,15 @@ +version: "3.8" +services: + mysql: + container_name: mysql + image: mysql:5.7 + restart: always + environment: + - MYSQL_ROOT_PASSWORD=root + - MYSQL_DATABASE=espark + - MYSQL_USER=espark-root + - MYSQL_PASSWORD=espark-root + ports: + - 3306:3306 + volumes: + - /data/espark-mysql \ No newline at end of file diff --git a/APPLICATIONS/springboot-maven-profiling/document/hellp.txt b/APPLICATIONS/springboot-maven-profiling/document/hellp.txt new file mode 100644 index 00000000..828cb167 --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/document/hellp.txt @@ -0,0 +1,27 @@ +#To Build maven based on profile +$ mvn clean package -Plocal -Dspring.profiles.active=local -DprofileIdEnabled=true +$ mvn clean package -Pprod -Dspring.profiles.active=prod -DprofileIdEnabled=true + +##TO EXECUTE CODE +$ mvn spring-boot:run -Dspring-boot.run.profiles=local -Plocal +$ mvn spring-boot:run -Dspring-boot.run.profiles=prod -Pprod + +##To run via jar file +$ java -jar -Dspring.profiles.active=local target/springboot-maven-profiling.jar +$ java -jar -Dspring.profiles.active=prod target/springboot-maven-profiling.jar + +#Testing the api +$ curl -X POST -H "Content-Type: application/json" -d '{"id":1, "name":"adarsh kumar"}' http://localhost:9090/api/employee +$ curl -X POST -H "Content-Type: application/json" -d '{"id":2, "name":"radha singh"}' http://localhost:9090/api/employee +$ curl http://localhost:9090/api/employee/1 +$ curl http://localhost:9090/api/employee + +#TO START THE DOCKER CONTAINERS +$ docker-compose up +$ docker-compose down + +#TO DELETE ALL THE CONTAINERS WITH VOLUMES +$ docker rm -vf $(docker ps -a -q) + +#TO DELETE ALL THE IMAGES +$ docker rmi -f $(docker images -a -q) \ No newline at end of file diff --git a/APPLICATIONS/springboot-maven-profiling/pom.xml b/APPLICATIONS/springboot-maven-profiling/pom.xml new file mode 100644 index 00000000..3154396c --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.espark.adarsh + springboot-maven-profiling + 0.0.1-SNAPSHOT + springboot-maven-profiling + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + local + + + com.h2database + h2 + + + + + prod + + + mysql + mysql-connector-java + + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/MavenProfilingApplication.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/MavenProfilingApplication.java new file mode 100644 index 00000000..d2c90ce1 --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/MavenProfilingApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MavenProfilingApplication { + + public static void main(String[] args) { + SpringApplication.run(MavenProfilingApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..6d6ebd2f --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.entity; + +import lombok.Data; + +import javax.persistence.*; + +@Data +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + +} diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..c9c07552 --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends JpaRepository { + +} diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..c9f588be --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.service; + + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import com.espark.adarsh.service.exception.ResourceNotFoundException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Slf4j +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + + public List getAllEmployee() { + return employeeRepository.findAll(); + } + + + public Employee createEmployee(Employee employee) { + return employeeRepository.save(employee); + } + + + public Employee getEmployeeById(Long empId) { + return employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + } + + + public Employee updateEmployee(Long empId, Employee employeeDetails) { + Employee employee = employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + employee.setName(employeeDetails.getName()); + Employee updatedEmployee = employeeRepository.save(employee); + return updatedEmployee; + } + + + public Employee deleteEmployee(Long empId) { + Employee employee = employeeRepository.findById(empId) + .orElseThrow(() -> new ResourceNotFoundException("Employee", "id", empId)); + employeeRepository.delete(employee); + return employee; + } +} diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/exception/ResourceNotFoundException.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..6e6a7fc3 --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/service/exception/ResourceNotFoundException.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.service.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + private String resourceName; + private String fieldName; + private Object fieldValue; + + public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) { + super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); + this.resourceName = resourceName; + this.fieldName = fieldName; + this.fieldValue = fieldValue; + } + + public String getResourceName() { + return resourceName; + } + + public String getFieldName() { + return fieldName; + } + + public Object getFieldValue() { + return fieldValue; + } +} diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..14ba82c2 --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.sql.DataSource; +import java.util.List; + +@RestController +@RequestMapping("/api") +public class EmployeeController { + + + @Autowired + EmployeeService employeeService; + + // Get a all Employee + @GetMapping("/employee") + public List getAllEmployee() { + return employeeService.getAllEmployee(); + } + + // Create a new Employee + @PostMapping("/employee") + public Employee createEmployee(@RequestBody Employee employee) { + return employeeService.createEmployee(employee); + } + + + // Get a Single Employee + @GetMapping("/employee/{id}") + public Employee getEmployeeById(@PathVariable(value = "id") Long empId) { + return this.employeeService.getEmployeeById(empId); + } + + // Update a Employee + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable(value = "id") Long empId, + @RequestBody Employee employeeDetails) { + return this.employeeService.updateEmployee(empId, employeeDetails); + } + + // Delete a Employee + @DeleteMapping("/employee/{id}") + public ResponseEntity deleteEmployee(@PathVariable(value = "id") Long empId) { + Employee employee = this.employeeService.deleteEmployee(empId); + return ResponseEntity.ok().body(employee); + } + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-maven-profiling/src/main/resources/application.yaml b/APPLICATIONS/springboot-maven-profiling/src/main/resources/application.yaml new file mode 100644 index 00000000..d4dd972b --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/main/resources/application.yaml @@ -0,0 +1,63 @@ +server: + port: 9090 + +logging: + level: + root: DEBUG + org: + hibernate: + SQL: DEBUG + type: + descriptor: + sql: + BasicBinder: TRACE + +spring: + application: + name: springboot-maven-profiling + profiles: + - local + h2: + console: + enabled: true + datasource: + url: jdbc:h2:mem:esparkDB + driver-class-name: org.h2.Driver + username: root + password: root + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: update + show-sql: true + properties: + hibernate: + format_sql: true + +--- + +server: + port: 9090 + + +spring: + application: + name: springboot-maven-profiling + profiles: + - prod + datasource: + url: jdbc:mysql://localhost:3306/esparkdb?createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC + username: root + password: root + driver-class-name: com.mysql.cj.jdbc.Driver + #initialization-mode: always + testWhileIdle: true + validationQuery: SELECT 1 + jpa: + database-platform: org.hibernate.dialect.MySQL5Dialect + generate-ddl: true + hibernate: + #ddl-auto: validate + naming: + implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/APPLICATIONS/springboot-maven-profiling/src/test/java/com/espark/adarsh/MavenProfilingApplicationTests.java b/APPLICATIONS/springboot-maven-profiling/src/test/java/com/espark/adarsh/MavenProfilingApplicationTests.java new file mode 100644 index 00000000..0976f94f --- /dev/null +++ b/APPLICATIONS/springboot-maven-profiling/src/test/java/com/espark/adarsh/MavenProfilingApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MavenProfilingApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-mdc-logs/.gitignore b/APPLICATIONS/springboot-mdc-logs/.gitignore new file mode 100644 index 00000000..402a4516 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/.gitignore @@ -0,0 +1,25 @@ + +*.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +output/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-mdc-logs/README.md b/APPLICATIONS/springboot-mdc-logs/README.md new file mode 100644 index 00000000..41dd7ad2 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/README.md @@ -0,0 +1,15 @@ +### springboot-mdc-logs + +> mapping diagnostic context + +--- + +### To Build the Application +* mvn clean package + +### To Run the Application +* mvn spring-boot:run + + +### Application Url +* curl -i -H "Accept: application/json" -H "correlationId: x-espark-id" http://localhost:8080/api/employees \ No newline at end of file diff --git a/APPLICATIONS/springboot-mdc-logs/pom.xml b/APPLICATIONS/springboot-mdc-logs/pom.xml new file mode 100644 index 00000000..f0967dd7 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.5.1 + + + com.espark.adarsh + springboot-mdc-logs + 0.0.1-SNAPSHOT + springboot-mdc-logs + Demo project for Spring Boot and MDC logs + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/config/UniqueIdFilterConfiguration.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/config/UniqueIdFilterConfiguration.java new file mode 100644 index 00000000..4a2e9101 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/config/UniqueIdFilterConfiguration.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.filter.UniqueIdFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import lombok.Data; + +@Configuration +@Data +public class UniqueIdFilterConfiguration { + + public static final String DEFAULT_HEADER_TOKEN = "correlationId"; + public static final String DEFAULT_MDC_UUID_TOKEN_KEY = "correlationId"; + + private String responseHeader = DEFAULT_HEADER_TOKEN; + private String mdcKey = DEFAULT_MDC_UUID_TOKEN_KEY; + private String requestHeader = DEFAULT_HEADER_TOKEN; + + @Bean + public FilterRegistrationBean servletRegistrationBean() { + final FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + final UniqueIdFilter log4jMDCFilterFilter = new UniqueIdFilter(responseHeader, mdcKey, requestHeader); + registrationBean.setFilter(log4jMDCFilterFilter); + registrationBean.setOrder(2); + return registrationBean; + } + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/controller/EmployeeController.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/controller/EmployeeController.java new file mode 100644 index 00000000..ebe8326f --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/controller/EmployeeController.java @@ -0,0 +1,30 @@ +package com.espark.adarsh.controller; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; + +@RestController +@RequestMapping("/api") +public class EmployeeController { + + private static final Logger LOGGER =LoggerFactory.getLogger(EmployeeController.class); + + @Autowired + private EmployeeService service; + + @GetMapping("/employees") + public List getAllEmpployee(@RequestHeader("correlationId") String correlationId){ + LOGGER.info("Inside getAllEmpployee method of EmployeeController"); + return service.getAllEmployee(); + } +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..e9e186f5 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.ToString; + +@Data +@AllArgsConstructor +@ToString +public class Employee { + + private int id; + + private String name; + + private int salary; + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/filter/UniqueIdFilter.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/filter/UniqueIdFilter.java new file mode 100644 index 00000000..11720835 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/filter/UniqueIdFilter.java @@ -0,0 +1,76 @@ +package com.espark.adarsh.filter; + +import java.util.UUID; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import com.espark.adarsh.config.UniqueIdFilterConfiguration; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Component +@Data +@EqualsAndHashCode(callSuper = false) +public class UniqueIdFilter extends OncePerRequestFilter { + + private final String responseHeader; + private final String mdcKey; + private final String requestHeader; + + public UniqueIdFilter() { + responseHeader = UniqueIdFilterConfiguration.DEFAULT_HEADER_TOKEN; + mdcKey = UniqueIdFilterConfiguration.DEFAULT_MDC_UUID_TOKEN_KEY; + requestHeader = UniqueIdFilterConfiguration.DEFAULT_HEADER_TOKEN; + } + + public UniqueIdFilter(final String responseHeader, final String mdcTokenKey, final String requestHeader) { + this.responseHeader = responseHeader; + this.mdcKey = mdcTokenKey; + this.requestHeader = requestHeader; + } + + @Override + protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) + throws java.io.IOException, ServletException { + try { + final String token = extractToken(request); + MDC.put(mdcKey, token); + if (StringUtils.hasText(responseHeader)) { + response.addHeader(responseHeader, token); + } + chain.doFilter(request, response); + } finally { + MDC.remove(mdcKey); + } + } + + private String extractToken(final HttpServletRequest request) { + final String token; + if (StringUtils.hasText(requestHeader) && StringUtils.hasText(request.getHeader(requestHeader))) { + token = request.getHeader(requestHeader); + } else { + token = UUID.randomUUID().toString().toUpperCase().replace("-", ""); + } + return token; + } + + @Override + protected boolean isAsyncDispatch(final HttpServletRequest request) { + return false; + } + + @Override + protected boolean shouldNotFilterErrorDispatch() { + return false; + } + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..3225b245 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.service; + +import java.util.List; + +import com.espark.adarsh.entity.Employee; + +public interface EmployeeService { + + List getAllEmployee(); + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/impl/EmployeeServiceImpl.java b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/impl/EmployeeServiceImpl.java new file mode 100644 index 00000000..c8316337 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/java/com/espark/adarsh/service/impl/EmployeeServiceImpl.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import com.espark.adarsh.controller.EmployeeController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.service.EmployeeService; + +@Service +public class EmployeeServiceImpl implements EmployeeService { + + private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeController.class); + + @Override + public List getAllEmployee() { + LOGGER.info("Inside getAllEmployee method of EmployeeServiceImpl"); + List employees = new ArrayList(); + Employee employee1 = new Employee(1, "Adarsh kumar", 1000); + Employee employee2 = new Employee(2, "Radha Singh", 1000); + Employee employee3 = new Employee(3, "Amit Kumar", 1000); + employees.add(employee1); + employees.add(employee2); + employees.add(employee3); + LOGGER.info("list of employees : {} ", employees); + return employees; + } + +} diff --git a/APPLICATIONS/springboot-mdc-logs/src/main/resources/application.properties b/APPLICATIONS/springboot-mdc-logs/src/main/resources/application.properties new file mode 100644 index 00000000..0acf56e2 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/main/resources/application.properties @@ -0,0 +1,2 @@ +# Logging pattern for the console +logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%X{correlationId}] - %msg%n \ No newline at end of file diff --git a/APPLICATIONS/springboot-mdc-logs/src/test/java/com/espark/adarsh/ApplicationMainTests.java b/APPLICATIONS/springboot-mdc-logs/src/test/java/com/espark/adarsh/ApplicationMainTests.java new file mode 100644 index 00000000..83533d04 --- /dev/null +++ b/APPLICATIONS/springboot-mdc-logs/src/test/java/com/espark/adarsh/ApplicationMainTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationMainTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-messges/.gitignore b/APPLICATIONS/springboot-messges/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-messges/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-messges/document/help.txt b/APPLICATIONS/springboot-messges/document/help.txt new file mode 100644 index 00000000..513a56ed --- /dev/null +++ b/APPLICATIONS/springboot-messges/document/help.txt @@ -0,0 +1,6 @@ +http://localhost:8080/employee + +{ + "id":"100", + "name":"adarsh kumar" +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-messges/pom.xml b/APPLICATIONS/springboot-messges/pom.xml new file mode 100644 index 00000000..4a59ae2f --- /dev/null +++ b/APPLICATIONS/springboot-messges/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.espark.adarsh + springboot-messges + 0.0.1-SNAPSHOT + jar + + springboot-messges + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/bean/Employee.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/bean/Employee.java new file mode 100644 index 00000000..ce50ca04 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/bean/Employee.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.bean; + +import java.io.Serializable; + +public class Employee implements Serializable { + private String id; + private String name; + + 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; + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java new file mode 100644 index 00000000..ce91e37c --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/configuration/ApplicationConfiguration.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; + +@Configuration +public class ApplicationConfiguration { + + @Bean + public ReloadableResourceBundleMessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:messages"); + messageSource.setCacheSeconds(10); //reload messages every 10 seconds + return messageSource; + } + +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..99243ebf --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + @Autowired + private EmployeeService employeeService; + + @RequestMapping(value = "/employee",method = RequestMethod.POST) + public Employee saveEmployee(@RequestBody Employee employee){ + return this.employeeService.saveEmployee(employee); + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationException.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationException.java new file mode 100644 index 00000000..9ad5889d --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationException.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.exception; + +public class ApplicationException { + + String message; + String cause; + + public ApplicationException(Exception e) { + this.message = e.getMessage(); + this.cause=e.getCause().toString(); + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java new file mode 100644 index 00000000..04be6385 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.nio.file.AccessDeniedException; +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice +public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler({ AccessDeniedException.class }) + public ResponseEntity handleAccessDeniedException(AccessDeniedException ex, WebRequest request) { + return new ResponseEntity( + "Access denied message here", new HttpHeaders(), HttpStatus.FORBIDDEN); + } + + @ExceptionHandler({ ValidationException.class }) + public ResponseEntity handleValidationException(ValidationException ex, WebRequest request) { + Map map=new HashMap<>(); + map.put("VALIDATION FAILED ",ex.toString()); + return new ResponseEntity( + map, HttpStatus.BAD_REQUEST); + } + +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/DefaultApplicationExceptionHandler.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/DefaultApplicationExceptionHandler.java new file mode 100644 index 00000000..c73f5e11 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/DefaultApplicationExceptionHandler.java @@ -0,0 +1,17 @@ +package com.espark.adarsh.exception; + + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.request.WebRequest; + +@ControllerAdvice +public class DefaultApplicationExceptionHandler{ + + @ExceptionHandler({ Exception.class }) + public @ResponseBody ApplicationException handleException(Exception ex, WebRequest request) { + return new ApplicationException(ex); + } + +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ValidationException.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ValidationException.java new file mode 100644 index 00000000..bfc91d80 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/exception/ValidationException.java @@ -0,0 +1,21 @@ +package com.espark.adarsh.exception; + + +public class ValidationException extends RuntimeException { + + private String code; + private String message; + + public ValidationException(String code, String message) { + this.code = code; + this.message = message; + } + + @Override + public String toString() { + return "{" + + "code='" + code + '\'' + + ", message='" + message + '\'' + + '}'; + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..7db192e9 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.Employee; +import com.espark.adarsh.exception.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import java.util.HashMap; +import java.util.Map; + +@Service +public class EmployeeService { + + Map employeeStore=new HashMap<>(); + + @Autowired + private MessageService messageService; + + public Employee saveEmployee(Employee employee){ + + if(employee==null){ + throw new ValidationException("null.emp",messageService.get("null.emp")); + } + + if(StringUtils.isEmpty(employee.getId())){ + throw new ValidationException("id.empty",messageService.get("id.empty")); + } + + if(StringUtils.isEmpty(employee.getName())){ + throw new ValidationException("name.empty",messageService.get("name.empty")); + } + employeeStore.put(employee.getId(),employee); + return employee; + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/MessageService.java b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/MessageService.java new file mode 100644 index 00000000..75cbe097 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/java/com/espark/adarsh/service/MessageService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.support.MessageSourceAccessor; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Locale; + +@Service +public class MessageService { + + @Autowired + private MessageSource messageSource; + + private MessageSourceAccessor accessor; + + @PostConstruct + private void init() { + accessor = new MessageSourceAccessor(messageSource, Locale.ENGLISH); + } + + public String get(String code) { + return accessor.getMessage(code); + } +} diff --git a/APPLICATIONS/springboot-messges/src/main/resources/application.properties b/APPLICATIONS/springboot-messges/src/main/resources/application.properties new file mode 100644 index 00000000..4fff5674 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.port=8080 +spring.messages.basename=messages \ No newline at end of file diff --git a/APPLICATIONS/springboot-messges/src/main/resources/messag_en_1.properties b/APPLICATIONS/springboot-messges/src/main/resources/messag_en_1.properties new file mode 100644 index 00000000..15a18c0e --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/resources/messag_en_1.properties @@ -0,0 +1 @@ +welcome=welcome to espark \ No newline at end of file diff --git a/APPLICATIONS/springboot-messges/src/main/resources/messages_en.properties b/APPLICATIONS/springboot-messges/src/main/resources/messages_en.properties new file mode 100644 index 00000000..c7210c80 --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/main/resources/messages_en.properties @@ -0,0 +1,3 @@ +null.emp=Employee cannot be null +id.empty=Id cannot be empty +name.empty=name cannot be empty \ No newline at end of file diff --git a/APPLICATIONS/springboot-messges/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-messges/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-messges/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-mock-test/.gitignore b/APPLICATIONS/springboot-mock-test/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..71793467 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/APPLICATIONS/springboot-mock-test/doc/help.txt b/APPLICATIONS/springboot-mock-test/doc/help.txt new file mode 100644 index 00000000..8d434cbf --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/doc/help.txt @@ -0,0 +1,46 @@ +$ mvn clean package +$ mvn spring-boot:run + +url for get method service call +http://localhost:9090/data/50 + +http://localhost:9090/odd/50 + +http://localhost:9090/even/50 + +-------------------------------------------------------------------------------------------------------- +SpringBootMockTest +Notes + +@RunWith(MockitoJUnitRunner.class) public class SpringBootMockTest +- The JUnit Runner which causes all the initialization magic + with @Mock and @InjectMocks to happen before the tests are run. + +@Mock DataRepositoryImpl dataRepository +- Create a mock for dataRepository + +@InjectMocks DataServiceImpl dataService +- Inject the mocks as dependencies into dataService + +-------------------------------------------------------------------------------------------------------- +SpringApplicationTests + +Notes +@RunWith(SpringRunner.class) +- Spring Runner is used to launch up a spring context in unit tests. + +@SpringBootTest +- This annotation indicates that the context under test is a @SpringBootApplication. + The complete springboot-mock-test is launched up during the unit test. + +@MockBean DataRepositoryImpl dataRepository +- @MockBean annotation creates a mock for DataService. + This mock is used in the Spring Context instead of the real DataService. + +@Autowired DataServiceImpl dataService +- Pick the Business Service from the Spring Context and autowire it in. + + +-------------------------------------------------------------------------------------------------------- + +http://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit \ No newline at end of file diff --git a/APPLICATIONS/springboot-mock-test/pom.xml b/APPLICATIONS/springboot-mock-test/pom.xml new file mode 100644 index 00000000..a45c27ed --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.espark.adarsh + springboot-mock-test + 0.0.1-SNAPSHOT + springboot-mock-test + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..b1aed80f --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,14 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} + diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepository.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepository.java new file mode 100644 index 00000000..36a5d70d --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.repository; + + + +import java.util.List; + +public interface DataRepository { + + public List retrieveAllData(int range) ; + +} diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepositoryImpl.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepositoryImpl.java new file mode 100644 index 00000000..539c283a --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/repository/DataRepositoryImpl.java @@ -0,0 +1,20 @@ +package com.espark.adarsh.repository; + +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +@Repository +public class DataRepositoryImpl implements DataRepository { + + @Override + public List retrieveAllData(int range) { + if (range <= 0) { + throw new IllegalArgumentException(range+""); + } else { + return IntStream.range(0, range).boxed().collect(Collectors.toList()); + } + } +} diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataService.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataService.java new file mode 100644 index 00000000..d3d24afb --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataService.java @@ -0,0 +1,13 @@ +package com.espark.adarsh.service; + + +import java.util.List; + +public interface DataService { + + public List retrieveAllData(int range); + + List findEvenNumber(int range); + + List findOddNumber(int range); +} diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataServiceImpl.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataServiceImpl.java new file mode 100644 index 00000000..74df43f4 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/service/DataServiceImpl.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.repository.DataRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class DataServiceImpl implements DataService { + + @Autowired + DataRepository dataRepository; + + @Override + public List retrieveAllData(int range){ + return this.dataRepository.retrieveAllData(range); + } + + @Override + public List findEvenNumber(int range){ + return this.dataRepository.retrieveAllData(range) + .stream() + .filter(element -> element % 2 == 0) + .collect(Collectors.toList()); + } + + @Override + public List findOddNumber(int range){ + return this.dataRepository.retrieveAllData(range) + .stream() + .filter(element -> element % 2 != 0) + .collect(Collectors.toList()); + } + +} diff --git a/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/web/DataController.java b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/web/DataController.java new file mode 100644 index 00000000..f1f2ebd7 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/java/com/espark/adarsh/web/DataController.java @@ -0,0 +1,32 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.service.DataService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class DataController { + + @Autowired + private DataService dataService; + + @RequestMapping(value = "/data/{range}", method = RequestMethod.GET) + public List retrieveAllData(@PathVariable("range") int range) { + return this.dataService.retrieveAllData(range); + } + + @RequestMapping(value = "/even/{range}", method = RequestMethod.GET) + public List retrieveEvenData(@PathVariable("range") int range) { + return this.dataService.findEvenNumber(range); + } + + @RequestMapping(value = "/odd/{range}", method = RequestMethod.GET) + public List retrieveOddData(@PathVariable("range") int range) { + return this.dataService.findOddNumber(range); + } +} diff --git a/APPLICATIONS/springboot-mock-test/src/main/resources/application.properties b/APPLICATIONS/springboot-mock-test/src/main/resources/application.properties new file mode 100644 index 00000000..5ff02851 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=9090 \ No newline at end of file diff --git a/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringApplicationTests.java b/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringApplicationTests.java new file mode 100644 index 00000000..118bb697 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringApplicationTests.java @@ -0,0 +1,78 @@ +package com.espark.adarsh; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.espark.adarsh.repository.DataRepository; +import com.espark.adarsh.repository.DataRepositoryImpl; +import com.espark.adarsh.service.DataService; +import com.espark.adarsh.service.DataServiceImpl; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringApplicationTests { + + @Autowired + DataRepository dataRepository; + + @Autowired + private DataService dataService; + + @Test + public void testForOneToFive() { + Integer range = 5; + List dataList = IntStream.range(0, range) + .boxed() + .collect(Collectors.toList()); + when(dataRepository.retrieveAllData(range)).thenReturn(dataList); + assertEquals(dataList, dataService.retrieveAllData(range)); + } + + @Test(expected = IllegalArgumentException.class) + public void testForException(){ + Integer range = 0; + dataRepository.retrieveAllData(range); + } + + + @Test + public void testForEven() { + Integer range = 5; + List evenList = IntStream.range(0, range) + .boxed() + .filter(element -> element % 2 == 0) + .collect(Collectors.toList()); + + when(dataRepository.retrieveAllData(range)).thenReturn(evenList); + assertEquals(evenList, dataService.retrieveAllData(range)); + } + + + @Test + public void testForOdd() { + Integer range = 5; + List oddList = IntStream.range(0, range) + .boxed() + .filter(element -> element % 2 != 0) + .collect(Collectors.toList()); + + when(dataRepository.retrieveAllData(range)).thenReturn(oddList); + assertEquals(oddList, dataService.retrieveAllData(range)); + } + +} + diff --git a/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringBootMockTest.java b/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringBootMockTest.java new file mode 100644 index 00000000..cd678e38 --- /dev/null +++ b/APPLICATIONS/springboot-mock-test/src/test/java/com/espark/adarsh/SpringBootMockTest.java @@ -0,0 +1,75 @@ +package com.espark.adarsh; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.espark.adarsh.repository.DataRepositoryImpl; +import com.espark.adarsh.service.DataServiceImpl; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +@RunWith(MockitoJUnitRunner.class) +public class SpringBootMockTest { + + + @Mock + private DataRepositoryImpl dataRepository ; + + @InjectMocks + private DataServiceImpl dataService; + + + @Test + public void testForOneToFive() { + Integer range = 5; + List dataList = IntStream.range(0, range) + .boxed() + .collect(Collectors.toList()); + when(dataRepository.retrieveAllData(range)).thenReturn(dataList); + assertEquals(dataList, dataService.retrieveAllData(range)); + } + + @Test(expected = IllegalArgumentException.class) + public void testForException() { + Mockito.when(this.dataRepository.retrieveAllData(0)) + .thenThrow(new IllegalArgumentException()); + dataRepository.retrieveAllData(0); + verify(dataRepository, times(1)) + .retrieveAllData(0); + } + + @Test + public void testForEven() { + Integer range = 5; + List evenList = IntStream.range(0, range) + .boxed() + .filter(element -> element % 2 == 0) + .collect(Collectors.toList()); + + when(dataRepository.retrieveAllData(range)).thenReturn(evenList); + assertEquals(evenList, dataService.retrieveAllData(range)); + } + + + @Test + public void testForOdd() { + Integer range = 5; + List oddList = IntStream.range(0, range) + .boxed() + .filter(element -> element % 2 != 0) + .collect(Collectors.toList()); + + when(dataRepository.retrieveAllData(range)).thenReturn(oddList); + assertEquals(oddList, dataService.retrieveAllData(range)); + } +} diff --git a/APPLICATIONS/springboot-mocketo/.gitignore b/APPLICATIONS/springboot-mocketo/.gitignore new file mode 100644 index 00000000..153c9335 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-mocketo/.mvn/wrapper/MavenWrapperDownloader.java b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..72308aa4 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/APPLICATIONS/springboot-mocketo/doc/help.txt b/APPLICATIONS/springboot-mocketo/doc/help.txt new file mode 100644 index 00000000..6de93153 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/doc/help.txt @@ -0,0 +1,28 @@ + +#################POSTGRACE USER AND DB CREATIONS################ + +akumar38=# create database espark; +CREATE DATABASE + +akumar38=# create user root with encrypted password 'root'; +CREATE ROLE + +akumar38=# grant all privileges on database espark to root; +GRANT +akumar38=# \l + +akumar38=# \c espark +You are now connected to database "espark" as user "akumar38". + +espark-# \dt + List of relations + Schema | Name | Type | Owner +--------+-----------+-------+------- + public | answers | table | root + public | questions | table | root + + +################################################################# + +$ mvn clean package +$ mvn spring-boot:run diff --git a/APPLICATIONS/springboot-mocketo/doc/rest.json b/APPLICATIONS/springboot-mocketo/doc/rest.json new file mode 100644 index 00000000..8859be5c --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/doc/rest.json @@ -0,0 +1,86 @@ +#creating question +POST +http: //localhost:8080/questions +{ +"title": "how r u ", +"description": "want to know how r u" +} +#response +{ +"createdAt": "2019-04-17T19:03:09.103+0000", +"updatedAt": "2019-04-17T19:03:09.103+0000", +"id": 1000, +"title": "how r u ", +"description": "want to know how r u" +} + + +#Get paginated Questions +GET +http: //localhost:8080/questions?page=0&size=2&sort=createdAt,desc +#response +{ +"content": [ +{ +"createdAt": "2019-04-17T19:03:09.103+0000", +"updatedAt": "2019-04-17T19:03:09.103+0000", +"id": 1000, +"title": "how r u ", +"description": "want to know how r u" +} +], +"pageable": { +"sort": { +"sorted": true, +"unsorted": false, +"empty": false +}, +"offset": 0, +"pageSize": 2, +"pageNumber": 0, +"paged": true, +"unpaged": false +}, +"last": true, +"totalPages": 1, +"totalElements": 1, +"size": 2, +"number": 0, +"first": true, +"numberOfElements": 1, +"sort": { +"sorted": true, +"unsorted": false, +"empty": false +}, +"empty": false +} + +#creating answer +POST +http://localhost:8080/questions/{questionId}/answers +http://localhost:8080/questions/1000/answers +{ +"text": "i am good how about u " +} +#response +{ +"createdAt": "2019-04-17T19:05:24.055+0000", +"updatedAt": "2019-04-17T19:05:24.055+0000", +"id": 1000, +"text": "i am good how about u " +} + +#Get all answers of a Question +GET +http: //localhost:8080/questions/{questionId}/answers +http: //localhost:8080/questions/1000/answers +##response +[ +{ +"createdAt": "2019-04-17T19:05:24.055+0000", +"updatedAt": "2019-04-17T19:05:24.055+0000", +"id": 1000, +"text": "i am good how about u " +} +] \ No newline at end of file diff --git a/APPLICATIONS/springboot-mocketo/pom.xml b/APPLICATIONS/springboot-mocketo/pom.xml new file mode 100644 index 00000000..faff5f08 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.2.RELEASE + + + com.espark.adarsh + springboot-mocketo + 0.0.1-SNAPSHOT + springboot-mocketo + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + 1.18.4 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..df42feb0 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/AnswerController.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/AnswerController.java new file mode 100644 index 00000000..6566bea6 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/AnswerController.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.entity.Answer; +import com.espark.adarsh.exception.ResourceNotFoundException; +import com.espark.adarsh.repository.AnswerRepository; +import com.espark.adarsh.repository.QuestionRepository; +import com.espark.adarsh.services.QuestionAnswerManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +import java.util.List; + +@RestController +public class AnswerController { + + @Autowired + private QuestionAnswerManager questionAnswerManager; + + @Autowired + private AnswerRepository answerRepository; + + @Autowired + private QuestionRepository questionRepository; + + @GetMapping("/questions/{questionId}/answers") + public List getAnswersByQuestionId(@PathVariable Long questionId) { + return questionAnswerManager.getAnswersByQuestionId(questionId); + } + + @PostMapping("/questions/{questionId}/answers") + public Answer addAnswer( + @PathVariable Long questionId, + @Valid @RequestBody Answer answer) { + return this.questionAnswerManager.addAnswer(questionId, answer); + } + + @PutMapping("/questions/{questionId}/answers/{answerId}") + public Answer updateAnswer( + @PathVariable Long questionId, + @PathVariable Long answerId, + @Valid @RequestBody Answer answerRequest) { + if (!questionAnswerManager.questionExistsById(questionId)) { + throw new ResourceNotFoundException("Question not found with id " + questionId); + } + return questionAnswerManager.updateAnswer(questionId, answerId, answerRequest); + } + + @DeleteMapping("/questions/{questionId}/answers/{answerId}") + public ResponseEntity deleteAnswer( + @PathVariable Long questionId, + @PathVariable Long answerId) { + if (!questionAnswerManager.questionExistsById(questionId)) { + throw new ResourceNotFoundException("Question not found with id " + questionId); + } + return questionAnswerManager.deleteAnswer(questionId, answerId); + + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/QuestionController.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/QuestionController.java new file mode 100644 index 00000000..99f54830 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/controller/QuestionController.java @@ -0,0 +1,47 @@ +package com.espark.adarsh.controller; + +import com.espark.adarsh.entity.Question; +import com.espark.adarsh.exception.ResourceNotFoundException; +import com.espark.adarsh.repository.QuestionRepository; +import com.espark.adarsh.services.QuestionAnswerManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +@RestController +public class QuestionController { + + + @Autowired + private QuestionAnswerManager questionAnswerManager; + + @Autowired + private QuestionRepository questionRepository; + + @GetMapping("/questions") + public Page getQuestions(Pageable pageable) { + return questionAnswerManager.getQuestions(pageable); + } + + + @PostMapping("/questions") + public Question createQuestion(@Valid @RequestBody Question question) { + return questionAnswerManager.createQuestion(question); + } + + @PutMapping("/questions/{questionId}") + public Question updateQuestion( + @PathVariable Long questionId, + @Valid @RequestBody Question questionRequest) { + return questionAnswerManager.updateQuestion(questionId, questionRequest); + } + + @DeleteMapping("/questions/{questionId}") + public ResponseEntity deleteQuestion(@PathVariable Long questionId) { + return questionAnswerManager.deleteQuestion(questionId); + } +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Answer.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Answer.java new file mode 100644 index 00000000..5fce88f4 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Answer.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import javax.persistence.*; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.annotations.OnDelete; +import org.hibernate.annotations.OnDeleteAction; + +@Entity +@Table(name = "answers") +@Data +@EqualsAndHashCode(callSuper = false) +public class Answer extends AuditModel { + @Id + @GeneratedValue(generator = "answer_generator") + @SequenceGenerator( + name = "answer_generator", + sequenceName = "answer_sequence", + initialValue = 1000 + ) + private Long id; + + @Column(columnDefinition = "text") + private String text; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "question_id", nullable = false) + @OnDelete(action = OnDeleteAction.CASCADE) + @JsonIgnore + private Question question; + +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/AuditModel.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/AuditModel.java new file mode 100644 index 00000000..f3585e06 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/AuditModel.java @@ -0,0 +1,35 @@ +package com.espark.adarsh.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; + +import java.io.Serializable; +import java.util.Date; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@JsonIgnoreProperties( + value = {"createdAt", "updatedAt"}, + allowGetters = true +) +@Data +public abstract class AuditModel implements Serializable { + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_at", nullable = false, updatable = false) + @CreatedDate + private Date createdAt; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "updated_at", nullable = false) + @LastModifiedDate + private Date updatedAt; + + +} + diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Question.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Question.java new file mode 100644 index 00000000..1a5659f4 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/entity/Question.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.entity; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Entity +@Table(name = "questions") +@Data +@EqualsAndHashCode(callSuper = false) +public class Question extends AuditModel { + + @Id + @GeneratedValue(generator = "question_generator") + @SequenceGenerator( + name = "question_generator", + sequenceName = "question_sequence", + initialValue = 1000 + ) + private Long id; + + @NotBlank + @Size(min = 3, max = 100) + private String title; + + @Column(columnDefinition = "text") + private String description; + + +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java new file mode 100644 index 00000000..821987b9 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/exception/ResourceNotFoundException.java @@ -0,0 +1,15 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String message) { + super(message); + } + + public ResourceNotFoundException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/AnswerRepository.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/AnswerRepository.java new file mode 100644 index 00000000..c2272543 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/AnswerRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.entity.Answer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import java.util.List; + +@Repository +public interface AnswerRepository extends JpaRepository { + List findByQuestionId(Long questionId); +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/QuestionRepository.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/QuestionRepository.java new file mode 100644 index 00000000..211efa9b --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/repository/QuestionRepository.java @@ -0,0 +1,11 @@ +package com.espark.adarsh.repository; + + +import com.espark.adarsh.entity.Question; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface QuestionRepository extends JpaRepository { +} + diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerService.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerService.java new file mode 100644 index 00000000..ae26f835 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerService.java @@ -0,0 +1,23 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Answer; +import org.springframework.http.ResponseEntity; + +import java.util.List; + +import javax.validation.Valid; + +public interface AnswerService { + + List getAnswersByQuestionId(Long questionId); + + Answer saveAnswer(@Valid Answer answerRequest); + + Answer updateAnswer( + Long questionId, + Long answerId, + @Valid Answer answerRequest); + + ResponseEntity deleteAnswer( + Long questionId, Long answerId); +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerServiceImpl.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerServiceImpl.java new file mode 100644 index 00000000..ccbfb493 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/AnswerServiceImpl.java @@ -0,0 +1,61 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Answer; +import com.espark.adarsh.exception.ResourceNotFoundException; +import com.espark.adarsh.repository.AnswerRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.List; + +import javax.validation.Valid; + + +@Service +public class AnswerServiceImpl implements AnswerService { + + @Autowired + private AnswerRepository answerRepository; + + + @Override + public List getAnswersByQuestionId(@PathVariable Long questionId) { + return answerRepository.findByQuestionId(questionId); + } + + @Override + public Answer saveAnswer(@Valid Answer answerRequest) { + return this.answerRepository.save(answerRequest); + } + + @Override + public Answer updateAnswer( + Long questionId, Long answerId, + @Valid Answer answerRequest) { + + return answerRepository.findById(answerId) + .map(answer -> { + answer.setText(answerRequest.getText()); + return answerRepository.save(answer); + }).orElseThrow(() -> new ResourceNotFoundException("Answer not found with id " + answerId)); + } + + @Override + public ResponseEntity deleteAnswer( + Long questionId, Long answerId) { + + return answerRepository.findById(answerId) + .map(answer -> { + answerRepository.delete(answer); + return ResponseEntity.ok().build(); + }).orElseThrow(() -> new ResourceNotFoundException("Answer not found with id " + answerId)); + + } + + public void setAnswerRepository(AnswerRepository answerRepository) { + this.answerRepository = answerRepository; + } +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManager.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManager.java new file mode 100644 index 00000000..67e92881 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManager.java @@ -0,0 +1,33 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Answer; +import com.espark.adarsh.entity.Question; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; + +import java.util.List; + +import javax.validation.Valid; + +public interface QuestionAnswerManager { + + Answer addAnswer(Long questionId, @Valid Answer answer); + + List getAnswersByQuestionId(Long questionId); + + Answer updateAnswer(Long questionId, Long answerId, + @Valid Answer answerRequest); + + ResponseEntity deleteAnswer(Long questionId, Long answerId); + + Page getQuestions(Pageable pageable); + + Question createQuestion(@Valid Question question); + + boolean questionExistsById(Long questionId); + + Question updateQuestion(Long questionId, Question questionRequest); + + ResponseEntity deleteQuestion(Long questionId); +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManagerImpl.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManagerImpl.java new file mode 100644 index 00000000..758c7e56 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionAnswerManagerImpl.java @@ -0,0 +1,84 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Answer; +import com.espark.adarsh.entity.Question; +import com.espark.adarsh.exception.ResourceNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import java.util.List; + +import javax.validation.Valid; + +@Service +public class QuestionAnswerManagerImpl implements QuestionAnswerManager { + + @Autowired + private QuestionService questionService; + + @Autowired + private AnswerService answerService; + + + @Override + public Answer addAnswer(Long questionId, @Valid Answer answer) { + return this.questionService.findbyId(questionId) + .map(question -> { + answer.setQuestion(question); + return answerService.saveAnswer(answer); + }).orElseThrow(() -> new ResourceNotFoundException("Question not found with id " + questionId)); + } + + @Override + public List getAnswersByQuestionId(Long questionId) { + return this.answerService.getAnswersByQuestionId(questionId); + } + + @Override + public Answer updateAnswer( + Long questionId, Long answerId, @Valid Answer answerRequest) { + return this.answerService.updateAnswer(questionId, answerId, answerRequest); + } + + @Override + public ResponseEntity deleteAnswer(Long questionId, Long answerId) { + return this.answerService.deleteAnswer(questionId, answerId); + } + + @Override + public Page getQuestions(Pageable pageable) { + return this.questionService.getQuestions(pageable); + } + + @Override + public Question createQuestion(@Valid Question question) { + return this.questionService.createQuestion(question); + } + + @Override + public boolean questionExistsById(Long questionId) { + return this.questionService.questionExistsById(questionId); + } + + @Override + public Question updateQuestion(Long questionId, Question questionRequest) { + return this.questionService.updateQuestion(questionId, questionRequest); + } + + @Override + public ResponseEntity deleteQuestion(Long questionId) { + return this.questionService.deleteQuestion(questionId); + } + + + public void setQuestionService(QuestionService questionService) { + this.questionService = questionService; + } + + public void setAnswerService(AnswerService answerService) { + this.answerService = answerService; + } +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionService.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionService.java new file mode 100644 index 00000000..3bbb3c7c --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionService.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Question; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; + +import java.util.Optional; + +import javax.validation.Valid; + +public interface QuestionService { + + Page getQuestions(Pageable pageable); + + Question createQuestion(@Valid Question question); + + boolean questionExistsById(Long questionId); + + Question updateQuestion( + Long questionId, Question questionRequest); + + Optional findbyId(Long questionId); + + ResponseEntity deleteQuestion(Long questionId); +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionServiceImpl.java b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionServiceImpl.java new file mode 100644 index 00000000..070a8134 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/java/com/espark/adarsh/services/QuestionServiceImpl.java @@ -0,0 +1,67 @@ +package com.espark.adarsh.services; + +import com.espark.adarsh.entity.Question; +import com.espark.adarsh.exception.ResourceNotFoundException; +import com.espark.adarsh.repository.QuestionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.Optional; + +import javax.validation.Valid; + +@Service +public class QuestionServiceImpl implements QuestionService { + + @Autowired + private QuestionRepository questionRepository; + + @Override + public Page getQuestions(Pageable pageable) { + return questionRepository.findAll(pageable); + } + + @Override + public Question createQuestion(@Valid Question question) { + return questionRepository.save(question); + } + + @Override + public boolean questionExistsById(Long questionId) { + return questionRepository.existsById(questionId); + } + + @Override + public Question updateQuestion( + Long questionId, Question questionRequest) { + return questionRepository.findById(questionId) + .map(question -> { + question.setTitle(questionRequest.getTitle()); + question.setDescription(questionRequest.getDescription()); + return questionRepository.save(question); + }).orElseThrow(() -> new ResourceNotFoundException("Question not found with id " + questionId)); + } + + @Override + public Optional findbyId(Long questionId){ + return questionRepository.findById(questionId); + } + + @Override + public ResponseEntity deleteQuestion(Long questionId) { + return questionRepository.findById(questionId) + .map(question -> { + questionRepository.delete(question); + return ResponseEntity.ok().build(); + }).orElseThrow(() -> new ResourceNotFoundException("Question not found with id " + questionId)); + } + + public void setQuestionRepository(QuestionRepository questionRepository) { + this.questionRepository = questionRepository; + } +} diff --git a/APPLICATIONS/springboot-mocketo/src/main/resources/application.properties b/APPLICATIONS/springboot-mocketo/src/main/resources/application.properties new file mode 100644 index 00000000..6bc95471 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/main/resources/application.properties @@ -0,0 +1,10 @@ +## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) +spring.datasource.url=jdbc:postgresql://localhost:5432/espark +spring.datasource.username=root +spring.datasource.password=root + +# The SQL dialect makes Hibernate generate better SQL for the chosen database +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect + +# Hibernate ddl auto (create, create-drop, validate, update) +spring.jpa.hibernate.ddl-auto = update diff --git a/APPLICATIONS/springboot-mocketo/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-mocketo/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..b73739e5 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,69 @@ +package com.espark.adarsh; + +import com.espark.adarsh.entity.Question; +import com.espark.adarsh.repository.AnswerRepository; +import com.espark.adarsh.repository.QuestionRepository; +import com.espark.adarsh.services.AnswerService; +import com.espark.adarsh.services.AnswerServiceImpl; +import com.espark.adarsh.services.QuestionAnswerManager; +import com.espark.adarsh.services.QuestionAnswerManagerImpl; +import com.espark.adarsh.services.QuestionService; +import com.espark.adarsh.services.QuestionServiceImpl; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.io.File; +import java.util.Optional; + +@lombok.extern.slf4j.Slf4j +@RunWith(MockitoJUnitRunner.class) +public class ApplicationTests { + + + @InjectMocks + private QuestionAnswerManagerImpl questionAnswerManager; + + @Mock + private QuestionServiceImpl questionService; + + @Mock + private AnswerServiceImpl answerService; + + @Mock + private QuestionRepository questionRepository; + + @Mock + private AnswerRepository answerRepository; + + + @Before + public void init() { + + questionService.setQuestionRepository(questionRepository); + answerService.setAnswerRepository(answerRepository); + questionAnswerManager.setAnswerService(answerService); + questionAnswerManager.setQuestionService(questionService); + + } + + @Test + public void testQuestionCreation() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + Question question = + mapper.readValue(new File("src/test/resources/json/question.json"), Question.class); + Question questionResponse = + mapper.readValue(new File("src/test/resources/json/question-response.json"), Question.class); + //Mockito.when(questionRepository.save(question)).thenReturn(questionResponse); + + Question response = this.questionService.createQuestion(question); + System.out.println(response); + + } + +} diff --git a/APPLICATIONS/springboot-mocketo/src/test/resources/json/question-response.json b/APPLICATIONS/springboot-mocketo/src/test/resources/json/question-response.json new file mode 100644 index 00000000..0e10e465 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/test/resources/json/question-response.json @@ -0,0 +1,7 @@ +{ + "createdAt": "2019-04-17T19:03:09.103+0000", + "updatedAt": "2019-04-17T19:03:09.103+0000", + "id": 1000, + "title": "how r u ", + "description": "want to know how r u" +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-mocketo/src/test/resources/json/question.json b/APPLICATIONS/springboot-mocketo/src/test/resources/json/question.json new file mode 100644 index 00000000..125936e4 --- /dev/null +++ b/APPLICATIONS/springboot-mocketo/src/test/resources/json/question.json @@ -0,0 +1,4 @@ +{ + "title": "how r u ", + "description": "want to know how r u" +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-module-gradle/.gitignore b/APPLICATIONS/springboot-module-gradle/.gitignore new file mode 100644 index 00000000..078cdcf7 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/.gitignore @@ -0,0 +1,27 @@ +HELP.md +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/APPLICATIONS/springboot-module-gradle/application-core/build.gradle b/APPLICATIONS/springboot-module-gradle/application-core/build.gradle new file mode 100644 index 00000000..995d5745 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/build.gradle @@ -0,0 +1,33 @@ +buildscript { + repositories { mavenCentral() } + + dependencies{ + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" + } +} + +ext { springBootVersion = '2.0.5.RELEASE' } + +apply plugin: 'java' +apply plugin: 'groovy' +apply plugin: 'eclipse' +apply plugin: 'idea' + +jar { + baseName = 'gs-multi-module-library' + version = '0.0.1-SNAPSHOT' +} +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" + +repositories { mavenCentral() } + +dependencies { + compile('org.springframework.boot:spring-boot-starter') + compile 'org.codehaus.groovy:groovy-all:${groovyVersion}' + testCompile('org.springframework.boot:spring-boot-starter-test') +} + +dependencyManagement { + imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") } +} diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/main/groovy/com/espark/adarsh/ServiceProperties.groovy b/APPLICATIONS/springboot-module-gradle/application-core/src/main/groovy/com/espark/adarsh/ServiceProperties.groovy new file mode 100644 index 00000000..e07bdb7a --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/main/groovy/com/espark/adarsh/ServiceProperties.groovy @@ -0,0 +1,20 @@ +package com.espark.adarsh; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties("service") +public class ServiceProperties { + + /** + * A message for the service. + */ + private String message; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyService.java b/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyService.java new file mode 100644 index 00000000..68e7f220 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyService.java @@ -0,0 +1,4 @@ +package com.espark.adarsh; + +public interface MyService { +} diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyServiceImpl.java b/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyServiceImpl.java new file mode 100644 index 00000000..b95acb08 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/main/java/com/espark/adarsh/MyServiceImpl.java @@ -0,0 +1,20 @@ +package com.espark.adarsh; + + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.stereotype.Service; + +@Service +@EnableConfigurationProperties(ServiceProperties.class) +public class MyServiceImpl implements MyService { + + private final ServiceProperties serviceProperties; + + public MyServiceImpl(ServiceProperties serviceProperties) { + this.serviceProperties = serviceProperties; + } + + public String message() { + return this.serviceProperties.getMessage(); + } +} diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/main/resources/application.properties b/APPLICATIONS/springboot-module-gradle/application-core/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/test/groovy/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-module-gradle/application-core/src/test/groovy/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..4949ed2c --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/test/groovy/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,31 @@ +package com.espark.adarsh; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest("service.message=welcome") +public class ApplicationTests { + + @Autowired + private MyService myService; + + @Test + public void contextLoads() { + } + + @Test + public void contextLoads() { + assertThat(myService.message()).isNotNull(); + } + + @SpringBootApplication + static class TestConfiguration { + } +} diff --git a/APPLICATIONS/springboot-module-gradle/application-core/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-module-gradle/application-core/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..57e14036 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-core/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh.springbootmodulegradle; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-module-gradle/application-web/build.gradle b/APPLICATIONS/springboot-module-gradle/application-web/build.gradle new file mode 100644 index 00000000..161a048c --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/build.gradle @@ -0,0 +1,36 @@ +buildscript { + repositories { mavenCentral() } + dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } +} + + +apply plugin: 'groovy' +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'org.springframework.boot' +apply plugin: 'io.spring.dependency-management' + +bootJar { + baseName = 'application-web' + version = '0.0.1-SNAPSHOT' +} + +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" + +repositories { + mavenCentral() +} + +bootRun { + attributes 'Start-Class' : 'com.espark.adarsh.ApplicationMain' +} + +dependencies { + compile 'org.codehaus.groovy:groovy-all:${groovyVersion}' + compile('org.springframework.boot:spring-boot-starter-actuator') + compile('org.springframework.boot:spring-boot-starter-web') + compile project(':application-core') + testCompile('org.springframework.boot:spring-boot-starter-test') +} + diff --git a/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..746a8f85 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.controller; + + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ApplicationController { + + private final MyService myService; + + public ApplicationController(MyService myService) { + this.myService = myService; + } + + @GetMapping("/") + public String home() { + return myService.message(); + } + + +} diff --git a/APPLICATIONS/springboot-module-gradle/application-web/src/main/resources/application.properties b/APPLICATIONS/springboot-module-gradle/application-web/src/main/resources/application.properties new file mode 100644 index 00000000..ec5af03c --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/src/main/resources/application.properties @@ -0,0 +1 @@ +service.message=Hello World diff --git a/APPLICATIONS/springboot-module-gradle/application-web/src/test/groovy/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-module-gradle/application-web/src/test/groovy/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/src/test/groovy/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-module-gradle/application-web/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-module-gradle/application-web/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/application-web/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-module-gradle/build.gradle b/APPLICATIONS/springboot-module-gradle/build.gradle new file mode 100644 index 00000000..953dd5ee --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'org.springframework.boot' + id 'java' + id 'groovy' +} + +buildscript { + + repositories { mavenCentral() } + + dependencies{ + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" + } +} + +subprojects{ + apply plugin: 'io.spring.dependency-management' + apply plugin: 'org.springframework.boot' + + dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + } +} + + +group = 'com.espark.adarsh' +version = '0.0.1-SNAPSHOT' + +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" + + + + diff --git a/APPLICATIONS/springboot-module-gradle/gradle.properties b/APPLICATIONS/springboot-module-gradle/gradle.properties new file mode 100644 index 00000000..25426eba --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/gradle.properties @@ -0,0 +1,14 @@ +javaVersion=1.8 +groovyVersion=2.4.6 +gradleSpringBootPluginVersion= 2.4.0.RELEASE + +springVersion=4.3.8.RELEASE +jacksonVersion=2.8.5 +jacksonJsr310Version=2.8.6 + +slf4jVersion=1.7.21 +log4jVersion=2.5 + +springBootVersion=2.1.0.RELEASE +spockVersion=1.0-groovy-2.4 + diff --git a/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.jar b/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..87b738cb Binary files /dev/null and b/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.properties b/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..411ba0ca --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Mar 04 15:49:02 CST 2019 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip diff --git a/APPLICATIONS/springboot-module-gradle/gradlew b/APPLICATIONS/springboot-module-gradle/gradlew new file mode 100644 index 00000000..af6708ff --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/APPLICATIONS/springboot-module-gradle/gradlew.bat b/APPLICATIONS/springboot-module-gradle/gradlew.bat new file mode 100644 index 00000000..6d57edc7 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/APPLICATIONS/springboot-module-gradle/settings.gradle b/APPLICATIONS/springboot-module-gradle/settings.gradle new file mode 100644 index 00000000..64e72b27 --- /dev/null +++ b/APPLICATIONS/springboot-module-gradle/settings.gradle @@ -0,0 +1,11 @@ + +pluginManagement { + repositories { + gradlePluginPortal() + } +} + +rootProject.name = 'springboot-module-gradle' +include 'application-core' +include 'application-web' + diff --git a/APPLICATIONS/springboot-multimodule-gradle/.gitignore b/APPLICATIONS/springboot-multimodule-gradle/.gitignore new file mode 100644 index 00000000..078cdcf7 --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/.gitignore @@ -0,0 +1,27 @@ +HELP.md +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/APPLICATIONS/springboot-multimodule-gradle/build.gradle b/APPLICATIONS/springboot-multimodule-gradle/build.gradle new file mode 100644 index 00000000..8a61cc5c --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'org.springframework.boot' version '2.0.1.RELEASE' + id 'java' +} + +apply plugin: 'io.spring.dependency-management' + +group = 'com.espark.adarsh' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '1.8' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} diff --git a/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.jar b/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..87b738cb Binary files /dev/null and b/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.properties b/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..44e7c4d1 --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/APPLICATIONS/springboot-multimodule-gradle/gradlew b/APPLICATIONS/springboot-multimodule-gradle/gradlew new file mode 100644 index 00000000..af6708ff --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/APPLICATIONS/springboot-multimodule-gradle/gradlew.bat b/APPLICATIONS/springboot-multimodule-gradle/gradlew.bat new file mode 100644 index 00000000..6d57edc7 --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/APPLICATIONS/springboot-multimodule-gradle/settings.gradle b/APPLICATIONS/springboot-multimodule-gradle/settings.gradle new file mode 100644 index 00000000..734c6f7c --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/settings.gradle @@ -0,0 +1,6 @@ +pluginManagement { + repositories { + gradlePluginPortal() + } +} +rootProject.name = 'springboot-multimodule-gradle' diff --git a/APPLICATIONS/springboot-multimodule-gradle/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-multimodule-gradle/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-multimodule-gradle/src/main/resources/application.properties b/APPLICATIONS/springboot-multimodule-gradle/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-multimodule-gradle/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-multimodule-gradle/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-multimodule-gradle/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/.gitignore b/APPLICATIONS/springboot-neo4j-docker/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-neo4j-docker/Dockerfile b/APPLICATIONS/springboot-neo4j-docker/Dockerfile new file mode 100644 index 00000000..bd8c923c --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8 +ADD target/springboot-neo4j-docker.jar springboot-neo4j-docker.jar +EXPOSE 9090 +ENTRYPOINT ["java","-jar","springboot-neo4j-docker.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-neo4j-docker/docker-compose.yaml b/APPLICATIONS/springboot-neo4j-docker/docker-compose.yaml new file mode 100644 index 00000000..4b03fca4 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/docker-compose.yaml @@ -0,0 +1,35 @@ +version: '3.7' +services: + neo4j: + container_name: neo4j + image: neo4j:4.0.3 + restart: always + ports: + - "7474:7474" + - "7687:7687" + volumes: + - ./neo4j/plugins:/plugins + environment: + NEO4J_AUTH: neo4j/secret + NEO4J_dbms_logs_debug_level: DEBUG +# networks: +# - spring-ms + +# springboot-neo4j-docker: +# container_name: springboot-neo4j-docker +# build: +# context: ./ +# dockerfile: Dockerfile +# restart: on-failure:5 +# ports: +# - 9090:9090 +# links: +# - neo4j +# depends_on: +# - neo4j +# environment: +# - SPRING_PROFILES_ACTIVE=docker +# networks: +# - spring-ms +#networks: +# spring-ms: \ No newline at end of file diff --git a/APPLICATIONS/springboot-neo4j-docker/document/help.txt b/APPLICATIONS/springboot-neo4j-docker/document/help.txt new file mode 100644 index 00000000..41acdb5b --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/document/help.txt @@ -0,0 +1,34 @@ + +$ mvn clean package + +$ docker-compose up +$ docker-compose down + +#To log into the console of the neo4j +http://localhost:7474/browser/ +user/pwd => neo4j/secret + + +@post +curl -X POST http://localhost:9090/api/employee -d '{"id":"100","name":"adarsh kumar"}' -H "Content-Type: application/json" +curl -X POST http://localhost:9090/api/department -d '{"id":"1","name":"it"}' -H "Content-Type: application/json" + +curl http://localhost:9090/api/graph/10 +curl http://localhost:9090/api/departments/it + + +@get +curl -X GET http://localhost:9090/api/employee/100 + + +#TO LIST DOWN ALL THE IMAGES +$ docker images + +#TO LIST ALL THE PROCESS +$ docker ps -a + +# TO DELETE ALL THE CONTAINERS WITH VOLUMES +$ docker rm -vf $(docker ps -a -q) + +# TO DELETE ALL THE IMAGES +$ docker rmi -f $(docker images -a -q) diff --git a/APPLICATIONS/springboot-neo4j-docker/pom.xml b/APPLICATIONS/springboot-neo4j-docker/pom.xml new file mode 100644 index 00000000..bf7577ba --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.0.RELEASE + + + com.espark.adarsh + springboot-neo4j-docker + 0.0.1-SNAPSHOT + springboot-neo4j-docker + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-neo4j + + + + org.neo4j + neo4j-ogm-bolt-driver + ${neo4j-ogm.version} + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + ${project.name} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/Neo4jDockerApplication.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/Neo4jDockerApplication.java new file mode 100644 index 00000000..d7b49bde --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/Neo4jDockerApplication.java @@ -0,0 +1,15 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; + +@SpringBootApplication +@EnableNeo4jRepositories("com.espark.adarsh.repository") +public class Neo4jDockerApplication { + + public static void main(String[] args) { + SpringApplication.run(Neo4jDockerApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Department.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Department.java new file mode 100644 index 00000000..9657dd17 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Department.java @@ -0,0 +1,28 @@ +package com.espark.adarsh.enitity; + + + +import lombok.Data; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + +import java.util.LinkedList; +import java.util.List; + +@Data +@NodeEntity +public class Department { + + @Id + @GeneratedValue + private Long id; + private String name; + + @Relationship(type = "WORKS", direction = Relationship.INCOMING) + private List works = new LinkedList<>(); + + + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Employee.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Employee.java new file mode 100644 index 00000000..471891fd --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/enitity/Employee.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.enitity; + + +import lombok.Data; +import org.neo4j.ogm.annotation.GeneratedValue; +import org.neo4j.ogm.annotation.Id; +import org.neo4j.ogm.annotation.NodeEntity; + +@Data +@NodeEntity +public class Employee { + + @Id + @GeneratedValue + private Long id; + private String name; + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/DepartmentRepository.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/DepartmentRepository.java new file mode 100644 index 00000000..f717a59f --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/DepartmentRepository.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.repository; + + +import com.espark.adarsh.enitity.Department; +import org.springframework.data.neo4j.annotation.Query; +import org.springframework.data.neo4j.repository.Neo4jRepository; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface DepartmentRepository extends Neo4jRepository { + + List findByNameLike(@Param("name") String name); + + + @Query("MATCH (d:Department)<-[w:WORKS]-(e:Employee) RETURN d,w,e LIMIT $limit") + List graph(@Param("limit") int limit); +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java new file mode 100644 index 00000000..0941cbe5 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/repository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.repository; + +import com.espark.adarsh.enitity.Employee; +import org.springframework.data.neo4j.repository.Neo4jRepository; + +public interface EmployeeRepository extends Neo4jRepository { + + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/DepartmentService.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/DepartmentService.java new file mode 100644 index 00000000..73788702 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/DepartmentService.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.enitity.Department; +import com.espark.adarsh.repository.DepartmentRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class DepartmentService { + + @Autowired + DepartmentRepository departmentRepository; + + + @Transactional(readOnly = false) + public Department save(Department department) { + log.info("label=DepartmentService save()"); + return this.departmentRepository.save(department); + } + + @Transactional(readOnly = false) + public Department delete(Long departmentId) { + log.info("label=DepartmentService delete()"); + Department department = this.departmentRepository.findById(departmentId).get(); + this.departmentRepository.delete(department); + return department; + } + + @Transactional(readOnly = true) + public Department get(Long departmentId) { + log.info("label=DepartmentService get()"); + return this.departmentRepository.findById(departmentId).get(); + } + + + @Transactional(readOnly = true) + public List findByNameLike(String name) { + log.info("label=DepartmentService findByName()"); + return this.departmentRepository.findByNameLike(name); + } + + @Transactional(readOnly = true) + public List graph(int limit){ + log.info("label=DepartmentService graph()"); + return this.departmentRepository.graph(limit); + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/EmployeeService.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/EmployeeService.java new file mode 100644 index 00000000..6e01c8d9 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/service/EmployeeService.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.enitity.Employee; +import com.espark.adarsh.repository.EmployeeRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; + +@Slf4j +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + @Transactional(readOnly = false) + public Employee save(Employee employee) { + log.info("label=EmployeeService save()"); + return this.employeeRepository.save(employee); + } + + @Transactional(readOnly = false) + public Employee delete(Long employeeId) { + log.info("label=EmployeeService delete()"); + Employee employee = this.employeeRepository.findById(employeeId).get(); + this.employeeRepository.delete(employee); + return employee; + } + + @Transactional(readOnly = true) + public Employee get(Long employeeId) { + log.info("label=EmployeeService get()"); + return this.employeeRepository.findById(employeeId).get(); + } + + @Transactional(readOnly = true) + public List getAll() { + log.info("label=EmployeeService getAll()"); + List departments = new LinkedList<>(); + this.employeeRepository + .findAll() + .forEach(employee -> departments.add(employee)); + return departments; + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/util/DataUtilService.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/util/DataUtilService.java new file mode 100644 index 00000000..8a6551cb --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/util/DataUtilService.java @@ -0,0 +1,55 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.enitity.Department; +import com.espark.adarsh.enitity.Employee; +import com.espark.adarsh.repository.DepartmentRepository; +import com.espark.adarsh.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Arrays; + +@Service +public class DataUtilService { + + @Autowired + DepartmentRepository departmentRepository; + + @Autowired + EmployeeRepository employeeRepository; + + @PostConstruct + public void init() { + + Employee adarsh = new Employee(); + adarsh.setName("Adarsh kumar"); + adarsh = this.employeeRepository.save(adarsh); + + Employee radha = new Employee(); + radha.setName("Radha Singh"); + radha = this.employeeRepository.save(radha); + + Department itdept = new Department(); + itdept.setName("IT DEPT"); + itdept.getWorks().add(radha); + itdept.getWorks().add(adarsh); + this.departmentRepository.save(itdept); + + + Employee amit = new Employee(); + amit.setName("Amit Kumar"); + amit = this.employeeRepository.save(amit); + + Employee geeta = new Employee(); + geeta.setName("Geeta Singh"); + geeta = this.employeeRepository.save(geeta); + + Department accountDept = new Department(); + accountDept.setName("ACCOUNT DEPT"); + accountDept.getWorks().add(amit); + accountDept.getWorks().add(geeta); + this.departmentRepository.save(accountDept); + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/DepartmentController.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/DepartmentController.java new file mode 100644 index 00000000..5b48f069 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/DepartmentController.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.enitity.Department; +import com.espark.adarsh.service.DepartmentService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.websocket.server.PathParam; +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/api") +public class DepartmentController { + + @Autowired + DepartmentService departmentService; + + + @PostMapping("/department") + public Department save(@RequestBody Department department) { + log.info("label=DepartmentController save()"); + return this.departmentService.save(department); + } + + @DeleteMapping("/department/{departmentId}") + public Department delete(@PathVariable("departmentId") Long departmentId) { + log.info("label=DepartmentController delete()"); + return this.departmentService.delete(departmentId); + } + + @GetMapping("/department/{departmentId}") + public Department get(@PathVariable("departmentId") Long departmentId) { + log.info("label=DepartmentController get()"); + return this.departmentService.get(departmentId); + } + + @GetMapping("/departments/{name}") + public List getByNameLike(@PathVariable("name") String name) { + log.info("label=DepartmentController getByName()"); + return this.departmentService.findByNameLike(name); + } + + @GetMapping("/graph/{limit}") + public List graph(@PathVariable("limit") Integer limit) { + log.info("label=DepartmentController graph()"); + return this.departmentService.graph(limit); + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..5d4cf6b2 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,43 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.enitity.Employee; +import com.espark.adarsh.service.EmployeeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.List; + +@Slf4j +@RestController +@RequestMapping("/api") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + + @PostMapping("/employee") + public Employee save(@RequestBody Employee employee) { + log.info("label=EmployeeController save()"); + return this.employeeService.save(employee); + } + + @DeleteMapping("/employee/{employeeId}") + public Employee delete(@PathVariable("employeeId") Long employeeId) { + log.info("label=EmployeeController delete()"); + return this.employeeService.delete(employeeId); + } + + @GetMapping("/employee/{employeeId}") + public Employee get(@PathVariable("employeeId") Long employeeId) { + log.info("label=EmployeeController get()"); + return this.employeeService.get(employeeId); + } + + @GetMapping("/employees") + public List getAll() { + log.info("label=EmployeeController getAll()"); + return this.employeeService.getAll(); + } + +} diff --git a/APPLICATIONS/springboot-neo4j-docker/src/main/resources/application.yaml b/APPLICATIONS/springboot-neo4j-docker/src/main/resources/application.yaml new file mode 100644 index 00000000..7aded43d --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/main/resources/application.yaml @@ -0,0 +1,25 @@ +server: + port: 9090 + +spring: + application: + name: springboot-neo4j-docker + data: + neo4j: + uri: bolt://localhost:7687 + username: neo4j + password: secret + + +--- + +spring: + application: + name: springboot-neo4j-docker + profiles: + - docker + data: + neo4j: + uri: bolt://neo4j:7687 + username: neo4j + password: secret \ No newline at end of file diff --git a/APPLICATIONS/springboot-neo4j-docker/src/test/java/com/espark/adarsh/Neo4JDockerApplicationTests.java b/APPLICATIONS/springboot-neo4j-docker/src/test/java/com/espark/adarsh/Neo4JDockerApplicationTests.java new file mode 100644 index 00000000..da4ca3b4 --- /dev/null +++ b/APPLICATIONS/springboot-neo4j-docker/src/test/java/com/espark/adarsh/Neo4JDockerApplicationTests.java @@ -0,0 +1,8 @@ +package com.espark.adarsh; + +class Neo4JDockerApplicationTests { + + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-nginx-docker/.gitignore b/APPLICATIONS/springboot-nginx-docker/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-nginx-docker/app/Dockerfile b/APPLICATIONS/springboot-nginx-docker/app/Dockerfile new file mode 100644 index 00000000..13777183 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/Dockerfile @@ -0,0 +1 @@ +FROM maven:3.5 \ No newline at end of file diff --git a/APPLICATIONS/springboot-nginx-docker/app/pom.xml b/APPLICATIONS/springboot-nginx-docker/app/pom.xml new file mode 100644 index 00000000..d3722388 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/pom.xml @@ -0,0 +1,44 @@ + + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + 4.0.0 + + app + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + app + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/controller/ApplicationController.java b/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/controller/ApplicationController.java new file mode 100644 index 00000000..ea4fe238 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/src/main/java/com/espark/adarsh/controller/ApplicationController.java @@ -0,0 +1,10 @@ +package com.espark.adarsh.controller; + +@org.springframework.web.bind.annotation.RestController +public class ApplicationController { + + @org.springframework.web.bind.annotation.GetMapping(value = "/message/{name}") + public String message(@org.springframework.web.bind.annotation.PathVariable("name")String name){ + return "Welcome to Esaprk "+name; + } +} diff --git a/APPLICATIONS/springboot-nginx-docker/app/src/main/resources/application.properties b/APPLICATIONS/springboot-nginx-docker/app/src/main/resources/application.properties new file mode 100644 index 00000000..5ff02851 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=9090 \ No newline at end of file diff --git a/APPLICATIONS/springboot-nginx-docker/app/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-nginx-docker/app/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/app/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-nginx-docker/docker-compose.yaml b/APPLICATIONS/springboot-nginx-docker/docker-compose.yaml new file mode 100644 index 00000000..f7bf9bc9 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/docker-compose.yaml @@ -0,0 +1,22 @@ +version: '2' +services: + nginx: + container_name: espark-nginx + image: nginx:1.13 + restart: always + ports: + - 80:80 + - 443:443 + volumes: + - ./nginx/conf.d:/etc/nginx/conf.d + app: + restart: always + build: ./app + working_dir: /app + volumes: + - ./app:/app + expose: + - "8080" + command: mvn clean spring-boot:run + depends_on: + - nginx diff --git a/APPLICATIONS/springboot-nginx-docker/nginx/conf.d/app.conf b/APPLICATIONS/springboot-nginx-docker/nginx/conf.d/app.conf new file mode 100644 index 00000000..e752cbf3 --- /dev/null +++ b/APPLICATIONS/springboot-nginx-docker/nginx/conf.d/app.conf @@ -0,0 +1,20 @@ +server { + listen 80; + charset utf-8; + access_log off; + + location / { + proxy_pass http://app:9090; + proxy_set_header Host $host:$server_port; + proxy_set_header X-Forwarded-Host $server_name; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + location /static { + access_log off; + expires 30d; + + alias /app/static; + } +} \ No newline at end of file diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/.gitignore b/APPLICATIONS/springboot-openapi-annotation-h2db/.gitignore new file mode 100644 index 00000000..e91d115f --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/.gitignore @@ -0,0 +1,34 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +.DS_Store +*.DS_Store +*/.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/README.md b/APPLICATIONS/springboot-openapi-annotation-h2db/README.md new file mode 100644 index 00000000..02047cf5 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/README.md @@ -0,0 +1,26 @@ + +# springboot-openapi-annotation-h2db + +--- + + +### to build the application +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +### log into the homepage of db +* http://localhost:8080/h2-console +``` +username, pwd , dburl and db driver class is mentioned in application.properties file +``` + +### To get the open api json config +* http://localhost:8080/api-docs/ + +### To get the open api yaml config +* http://localhost:8080/api-docs.yaml + +## swagger ui url +* http://localhost:8080/swagger-ui-custom.html diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/pom.xml b/APPLICATIONS/springboot-openapi-annotation-h2db/pom.xml new file mode 100644 index 00000000..dd46d278 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-openapi-annotation-h2db + 0.0.1-SNAPSHOT + springboot-openapi-annotation-h2db + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springdoc + springdoc-openapi-ui + 1.6.4 + + + io.swagger.core.v3 + swagger-annotations + 2.1.4 + + + + com.h2database + h2 + runtime + 1.4.199 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..23b0eef1 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,14 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..87b3dfd8 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,31 @@ +package com.espark.adarsh.config; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import io.swagger.v3.oas.annotations.security.SecuritySchemes; +import io.swagger.v3.oas.models.parameters.Parameter; +import org.springdoc.core.customizers.OperationCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@OpenAPIDefinition(info = @Info(title = "Employees API", version = "2.0", description = "Employees Information")) +//@SecurityScheme(name = "Authentication", scheme = "basic", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER) +@SecuritySchemes(@SecurityScheme(name = "Token", paramName ="Authorization", type = SecuritySchemeType.APIKEY,in = SecuritySchemeIn.HEADER)) +public class ApplicationConfig { + + @Bean + public OperationCustomizer customize() { + return (operation, handlerMethod) -> operation.addParametersItem( + new Parameter() + .in("header") + .required(false) + .description("Authorization") + .name("x-token")); + } + +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..57a3e3de --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long id, String firstName, String lastName, String career) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java new file mode 100644 index 00000000..5a452947 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/exception/EmployeeNotFoundException.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.exception; + +public class EmployeeNotFoundException extends RuntimeException{ + public EmployeeNotFoundException() { + } + + public EmployeeNotFoundException(String message) { + super(message); + } + + public EmployeeNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public EmployeeNotFoundException(Throwable cause) { + super(cause); + } + + public EmployeeNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..e37cce1a --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends CrudRepository { +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java new file mode 100644 index 00000000..db7ba9c3 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/service/DataInitService.java @@ -0,0 +1,27 @@ +package com.espark.adarsh.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +@Service +public class DataInitService { + + + @Autowired + DataSource dataSource; + + @PostConstruct + public void init() { + Resource initSchema = new ClassPathResource("data.sql"); + DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema); + DatabasePopulatorUtils.execute(databasePopulator, dataSource); + } +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..5ed57b2c --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.exception.EmployeeNotFoundException; +import com.espark.adarsh.respository.EmployeeRepository; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +@RestController +@SecurityRequirement(name = "Authentication") +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employee/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + } + + @DeleteMapping("/employee/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id) + .orElseThrow(()-> new EmployeeNotFoundException("employee not found")); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PutMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/application.properties b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/application.properties new file mode 100644 index 00000000..755c11ab --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/application.properties @@ -0,0 +1,16 @@ + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true + + + +springdoc.api-docs.path=/api-docs +springdoc.swagger-ui.path=/swagger-ui-custom.html diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/data.sql b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/data.sql new file mode 100644 index 00000000..d29927be --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/main/resources/data.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS employee; + +CREATE TABLE employee ( + id INT AUTO_INCREMENT PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); + +INSERT INTO employee (first_name, last_name, career) VALUES + ('adarsh', 'kumar', 'It'), + ('radha', 'singh', 'IT'), + ('sonu', 'singh', 'IT'), + ('amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-openapi-annotation-h2db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-openapi-annotation-h2db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-openapi-annotation-h2db/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-openapi-generator/.gitignore b/APPLICATIONS/springboot-openapi-generator/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-openapi-generator/README.md b/APPLICATIONS/springboot-openapi-generator/README.md new file mode 100644 index 00000000..ad911f64 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/README.md @@ -0,0 +1,16 @@ +# spring boot openapi generator +--- +> this project generated a bean controller specification based on the open api yml file +> declaration of bean and other component + + +## Generated Source via open api yml +* target/generated-sources/openapi/src/main/java + +## add the location in the source in the intellj ide to avoid the compilation at ide level +* target/generated-sources/openapi/src/main/java + + +implement the controller service and other classes based on the generated sourcecode + + diff --git a/APPLICATIONS/springboot-openapi-generator/pom.xml b/APPLICATIONS/springboot-openapi-generator/pom.xml new file mode 100644 index 00000000..1bf374bc --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/pom.xml @@ -0,0 +1,147 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.2 + + + com.espark.adarsh + springboot-openapi-generator + 0.0.1-SNAPSHOT + springboot-openapi-generator + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.data + spring-data-jpa + + + + org.openapitools + jackson-databind-nullable + 0.2.6 + + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + + + org.springdoc + springdoc-openapi-ui + 1.7.0 + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + jakarta.validation + jakarta.validation-api + 2.0.2 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + javax.validation + validation-api + 1.1.0.Final + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.openapitools + openapi-generator-maven-plugin + 7.1.0 + + + + generate + + + + ${project.basedir}/src/main/resources/application-api.yml + + spring + ${project.basedir}/target/generated-sources/openapi/ + com.espark.adarsh.openapi.api + com.espark.adarsh.openapi.model + + ApiUtil.java + + + true + + + + + + + + + diff --git a/APPLICATIONS/springboot-openapi-generator/src/main/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplication.java b/APPLICATIONS/springboot-openapi-generator/src/main/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplication.java new file mode 100644 index 00000000..1c1e97d6 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/src/main/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootOpenapiGeneratorApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootOpenapiGeneratorApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-openapi-generator/src/main/resources/application-api.yml b/APPLICATIONS/springboot-openapi-generator/src/main/resources/application-api.yml new file mode 100644 index 00000000..a7f795fa --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/src/main/resources/application-api.yml @@ -0,0 +1,146 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Swagger Employee + license: + name: MIT +servers: + - url: http://localhost:8080/ +paths: + /employees: + get: + summary: List all Employees + operationId: listEmployees + tags: + - employee + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: A paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Employee" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /employee: + post: + summary: Create a pet + operationId: createEmployee + tags: + - employee + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /employee/{employeeId}: + get: + summary: Info for a specific pet + operationId: getEmployeeById + tags: + - employee + parameters: + - name: employeeId + in: path + required: true + description: The id of the employee to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Employee" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" +components: + schemas: + Employee: + type: object + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Sample: + type: object + properties: + employee: + description: General Employee + $ref: '#/components/schemas/Employee' + list: + type: array + items: + $ref: '#/components/schemas/Employee' + mapOfEmployee: + additionalProperties: + type: array + items: + $ref: '#/components/schemas/Employee' + listOfMapOfEmployee: + type: array + items: + additionalProperties: + type: array + items: + $ref: '#/components/schemas/Employee' + + EmployeeEntity: + type: object + x-java-jpa-entity: true + x-class-extra-annotation: "@lombok.Data @jakarta.persistence.Entity @jakarta.persistence.Table(name=\"employee\")" + properties: + id: + x-field-extra-annotation: "@jakarta.persistence.Id @jakarta.persistence.GeneratedValue(strategy = jakarta.persistence.GenerationType.AUTO) @jakarta.persistence.Column(name=\"id\")" + type: long + name: + x-field-extra-annotation: "@jakarta.persistence.Column(name=\"name\")" + type: string + dob: + x-field-extra-annotation: "@jakarta.persistence.Column(name=\"dob\")" + type: string + format: data-time + Error: + type: object + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string \ No newline at end of file diff --git a/APPLICATIONS/springboot-openapi-generator/src/main/resources/application.properties b/APPLICATIONS/springboot-openapi-generator/src/main/resources/application.properties new file mode 100644 index 00000000..d987b372 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/src/main/resources/application.properties @@ -0,0 +1,11 @@ +spring.application.name=springboot-openapi-generator +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=root +spring.datasource.password=root +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + + + +#spring.datasource.url=jdbc:h2:file:/data/demo +spring.h2.console.enabled=true \ No newline at end of file diff --git a/APPLICATIONS/springboot-openapi-generator/src/test/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplicationTests.java b/APPLICATIONS/springboot-openapi-generator/src/test/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplicationTests.java new file mode 100644 index 00000000..2ffbc4e7 --- /dev/null +++ b/APPLICATIONS/springboot-openapi-generator/src/test/java/com/espark/adarsh/SpringbootOpenapiGeneratorApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootOpenapiGeneratorApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/.gitignore b/APPLICATIONS/springboot-oracle-multivalue-procedure/.gitignore new file mode 100644 index 00000000..517bbfb1 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/.gitignore @@ -0,0 +1,35 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + + +*.DS_Store +/*.DS_Store +.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/README.md b/APPLICATIONS/springboot-oracle-multivalue-procedure/README.md new file mode 100644 index 00000000..c33f0b63 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/README.md @@ -0,0 +1,39 @@ +# SPRINGBOOT JPA ORACLE DB LIQUIDBASE + +--- + +### To Build Code +* mvn clean package + +### TO CHECK DATA INTO THE DB +* SELECT * FROM SYSTEM.EMPLOYEE; +* SELECT * FROM SYSTEM.DATABASECHANGELOG; + +## TO CHECK SQL SCRPT WORKED OR NOT +* SELECT * FROM SYSTEM.DATABASECHANGELOG; +* TRUNCATE TABLE SYSTEM.DATABASECHANGELOG; + +## TO DROP THE TABLES IN DB +* DROP PROCEDURE SYSTEM.GET_EMPLOYEE_INFO; +* DROP TABLE SYSTEM.EMPLOYEE; +* DROP TABLE SYSTEM.DATABASECHANGELOG; +* DROP TABLE SYSTEM.DATABASECHANGELOGLOCK; + + +## TO TEST THE STORED PROCEDURE +``` +SET SERVEROUTPUT ON; +DECLARE + V_EMP_MSG VARCHAR(50) ; +BEGIN + SYSTEM.GET_EMPLOYEE_INFO(&V_EMP_ID,V_EMP_MSG); + DBMS_OUTPUT.PUT_LINE(V_EMP_MSG); +END; +/ +``` + +### [step by step guide for oracle xe db docker image cration ](oracle-db-xe-docker-image-building-process.md) + + +### To Test the api +* curl -X GET http://localhost:9090/employee/data/adarsh,radha,sonu diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/oracle-db-xe-docker-image-building-process.md b/APPLICATIONS/springboot-oracle-multivalue-procedure/oracle-db-xe-docker-image-building-process.md new file mode 100644 index 00000000..698b916b --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/oracle-db-xe-docker-image-building-process.md @@ -0,0 +1,118 @@ + +## Clone the git hub from oracle +* git clone git@github.com:oracle/docker-images.git + +## move to the docker file directory +* $ cd docker-images/OracleDatabase/SingleInstance/dockerfiles + +# list the supported version +* $ ls +``` +11.2.0.2 12.2.0.1 18.4.0 21.3.0 +12.1.0.2 18.3.0 19.3.0 buildContainerImage.sh +``` + +## url to download the verion of oracle zip +* https://www.oracle.com/database/technologies/xe18c-downloads.html +* copy into the same directtoy of the version in ls cmd + +## Build the docker iamge +* $ sh buildContainerImage.sh -v 18.4.0 -x + +``` +Oracle Database container image for 'xe' version 18.4.0 is ready to be extended: + + --> oracle/database:18.4.0-xe + + Build completed in 510 seconds. +``` + +## db client opernsource +* https://dbeaver.io/download/ + +## launch the db +* $ docker run --name OracleXE \ +--shm-size=1g \ +-p 1521:1521 \ +-p 8081:8080 \ +-e ORACLE_PWD=12345 \ +-v oracle-data:/u01/app/oracle/oradata \ +oracle/database:18.4.0-xe + +``` +ORACLE PASSWORD FOR SYS AND SYSTEM: 12345 +Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts: +Confirm the password: +Configuring Oracle Listener. +Listener configuration succeeded. +Configuring Oracle Database XE. +Enter SYS user password: +****** +Enter SYSTEM user password: +***** +Enter PDBADMIN User Password: +***** +Prepare for db operation +7% complete +Copying database files +29% complete +Creating and starting Oracle instance +Completing Database Creation +47% complete +50% complete +Creating Pluggable Databases +54% complete +71% complete +Executing Post Configuration Actions +93% complete +Running Custom Scripts +100% complete +Database creation complete. For details check the logfiles at: + /opt/oracle/cfgtoollogs/dbca/XE. +Database Information: +Global Database Name:XE +System Identifier(SID):XE +Look at the log file "/opt/oracle/cfgtoollogs/dbca/XE/XE.log" for further details. + +Connect to Oracle Database using one of the connect strings: + Pluggable database: 2f7354fc4ee1/XEPDB1 + Multitenant container database: 2f7354fc4ee1 +Use https://localhost:5500/em to access Oracle Enterprise Manager for Oracle Database XE +The Oracle base remains unchanged with value /opt/oracle +######################### +DATABASE IS READY TO USE! +######################### +The following output is now a tail of the alert.log: +2021-10-05T23:03:43.054971+00:00 +XEPDB1(3):Resize operation completed for file# 10, old size 358400K, new size 368640K +2021-10-05T23:03:56.975470+00:00 +XEPDB1(3):CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):Completed: CREATE SMALLFILE TABLESPACE "USERS" LOGGING DATAFILE '/opt/oracle/oradata/XE/XEPDB1/users01.dbf' SIZE 5M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO +XEPDB1(3):ALTER DATABASE DEFAULT TABLESPACE "USERS" +XEPDB1(3):Completed: ALTER DATABASE DEFAULT TABLESPACE "USERS" +2021-10-05T23:04:03.318085+00:00 +ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE +Completed: ALTER PLUGGABLE DATABASE XEPDB1 SAVE STATE + +``` + +## Connect to db +``` +Host: localhost +Port: 1521 +Database: XE +Use SID +User name: SYS +Role: SYSDBA +Password: 12345 +``` + +## Clean up +* docker ps -a +* docker rm [OPTIONS] CONTAINER [CONTAINER...] +* docker rm -f [CONTAINER_ID] +* docker rm -f 2f7354fc4ee1 +* docker rm -f [CONTAINER_NAME] OracleXE +* docker rm -f OracleXE + +[HELP FROM BLOG](https://www.codesanook.com/setup-oracle-xe-database-on-docker-container-and-connect-with-dbeaver) \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/pom.xml b/APPLICATIONS/springboot-oracle-multivalue-procedure/pom.xml new file mode 100644 index 00000000..bacafc46 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.espark.adarsh + springboot-oracle-multivalue-procedure + 0.0.1-SNAPSHOT + springboot-oracle-multivalue-procedure + Demo project for Spring Boot + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-web + + + + com.oracle.database.jdbc + ojdbc10 + 19.3.0.0 + + + + org.liquibase + liquibase-core + + + + com.zaxxer + HikariCP + 2.6.0 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..1c7b85d8 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + +} diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/entity/Employee.java b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/entity/Employee.java new file mode 100644 index 00000000..bea6c6b4 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/entity/Employee.java @@ -0,0 +1,64 @@ +package com.espark.adarsh.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long empId; + private String firstName; + private String lastName; + private String career; + + public Employee() { + } + + public Employee(String firstName, String lastName, String career) { + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Employee(Long empId, String firstName, String lastName, String career) { + this.empId = empId; + this.firstName = firstName; + this.lastName = lastName; + this.career = career; + } + + public Long getEmpId() { + return empId; + } + + public void setEmpId(Long empId) { + this.empId = empId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCareer() { + return career; + } + + public void setCareer(String career) { + this.career = career; + } +} + diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java new file mode 100644 index 00000000..4a318725 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/respository/EmployeeRepository.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.respository; + +import com.espark.adarsh.entity.Employee; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import javax.transaction.Transactional; +import java.util.List; + +@Repository +public interface EmployeeRepository extends CrudRepository { + + @Procedure(procedureName = "SYSTEM.GET_EMPLOYEE_INFO",outputParameterName = "V_EMP_MSG") + String getEmployeeData(@Param("V_EMP_NAMES") String empNames); +} diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java new file mode 100644 index 00000000..2502a6b4 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/java/com/espark/adarsh/web/EmployeeController.java @@ -0,0 +1,53 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.entity.Employee; +import com.espark.adarsh.respository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +@RestController +public class EmployeeController { + + @Autowired + EmployeeRepository employeeRepository; + + @GetMapping("/employees") + public List getAllEmployee() { + List employeeList = new LinkedList<>(); + this.employeeRepository.findAll().forEach(employee -> employeeList.add(employee)); + return employeeList; + } + + @GetMapping("/employees/{id}") + public Employee getEmployee(@PathVariable("id") Long id) { + return this.employeeRepository.findById(id).get(); + } + + + @GetMapping("/employee/data/{id}") + public String getEmployeeData(@PathVariable("id") String id) { + return this.employeeRepository.getEmployeeData(id); + } + + @DeleteMapping("/employees/{id}") + public Employee removeEmployee(@PathVariable("id") Long id) { + Employee employee = this.employeeRepository.findById(id).get(); + this.employeeRepository.deleteById(id); + return employee; + } + + @PostMapping("/employee") + public Employee saveEmployee(@RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + + @PostMapping("/employee/{id}") + public Employee updateEmployee(@PathVariable("id") Long id, @RequestBody Employee employee) { + return this.employeeRepository.save(employee); + } + +} diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/application.properties b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/application.properties new file mode 100644 index 00000000..d5e902b8 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/application.properties @@ -0,0 +1,29 @@ +server.port=9090 + + + +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XE +spring.datasource.username=SYSTEM +spring.datasource.password=12345 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.generate-ddl=false + + +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml +spring.liquibase.drop-first=true + diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/create_schema.xml b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/create_schema.xml new file mode 100644 index 00000000..0d985dd7 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/create_schema.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/insert_data.xml b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/insert_data.xml new file mode 100644 index 00000000..5465b722 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/insert_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/select_data.xml b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/select_data.xml new file mode 100644 index 00000000..233310b3 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/select_data.xml @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql new file mode 100644 index 00000000..d5f1ce21 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/create_schema.sql @@ -0,0 +1,8 @@ +DROP TABLE SYSTEM.EMPLOYEE; + +CREATE TABLE SYSTEM.employee ( + emp_id INTEGER PRIMARY KEY, + first_name VARCHAR(250) NOT NULL, + last_name VARCHAR(250) NOT NULL, + career VARCHAR(250) DEFAULT NULL +); \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql new file mode 100644 index 00000000..03e63803 --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/insert_data.sql @@ -0,0 +1,4 @@ +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (100,'adarsh', 'kumar', 'It'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES (200,'radha', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(300,'sonu', 'singh', 'IT'); +INSERT INTO employee (emp_id, first_name, last_name, career) VALUES(400,'amit', 'kumar', 'Finance'); \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql new file mode 100644 index 00000000..ce36410d --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/changes/sql/select_data.sql @@ -0,0 +1,19 @@ +CREATE OR REPLACE PROCEDURE + SYSTEM.GET_EMPLOYEE_INFO( V_EMP_NAMES IN VARCHAR2, V_EMP_MSG OUT VARCHAR2 ) +AS + CURSOR EMP_CURSOR + IS + SELECT EMP_ID, FIRST_NAME, LAST_NAME, CAREER FROM SYSTEM.EMPLOYEE + WHERE SYSTEM.EMPLOYEE.FIRST_NAME + IN ( + SELECT REGEXP_SUBSTR(V_EMP_NAMES,'[^,]+', 1, level) FROM DUAL + CONNECT BY REGEXP_SUBSTR(V_EMP_NAMES, '[^,]+', 1, level) + IS NOT NULL ); +BEGIN + FOR EMP IN EMP_CURSOR + LOOP + V_EMP_MSG := V_EMP_MSG ||' : '|| EMP.EMP_ID ||' '|| EMP.FIRST_NAME ||' '|| EMP.LAST_NAME ||' '|| EMP.CAREER; + END LOOP; +END GET_EMPLOYEE_INFO; + +// \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/db.changelog-master.xml b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 00000000..2ac9eefc --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/APPLICATIONS/springboot-oracle-multivalue-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java new file mode 100644 index 00000000..a946a93b --- /dev/null +++ b/APPLICATIONS/springboot-oracle-multivalue-procedure/src/test/java/com/espark/adarsh/SpringbootH2DbApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class) +class SpringbootH2DbApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-programatic-validation/.gitignore b/APPLICATIONS/springboot-programatic-validation/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-programatic-validation/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-programatic-validation/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..d58dfb70 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/APPLICATIONS/springboot-programatic-validation/README.md b/APPLICATIONS/springboot-programatic-validation/README.md new file mode 100644 index 00000000..3380ac66 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/README.md @@ -0,0 +1,37 @@ + + +``` +@AssertTrue validates that the annotated property value is true. +@Size validates that the annotated property value has a size between the attributes min and max. We can apply it to String, Collection, Map, and array properties. +@Min validates that the annotated property has a value no smaller than the value attribute. +@Max validates that the annotated property has a value no larger than the value attribute. +@Email validates that the annotated property is a valid email address. +Some annotations accept additional attributes, but the message attribute is common to all of them. This is the message that will usually be rendered when the value of the respective property fails validation. + +Here are some additional annotations we can find in the JSR: + +@NotEmpty validates that the property isn’t null or empty. We can apply it to String, Collection, Map or Array values. +@NotBlank can be applied only to text values, and validates that the property isn’t null or whitespace. +@Positive and @PositiveOrZero apply to numeric values, and validate that they’re strictly positive, or positive including 0. +@Negative and @NegativeOrZero apply to numeric values, and validate that they’re strictly negative, or negative including 0. +@Past and @PastOrPresent validate that a date value is in the past, or the past including the present. We can apply it to date types, including those added in Java 8. +@Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present. +``` + +``` +curl --location 'http://localhost:8080/user' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "adarsh", + "email": "adarsh@kumar", + "mobile": "+18877665544", + "age": 50, + "working": true, + "aboutMe": "intelligent", + "dateOfBirth": 13091983, + "preference": [ + "java", + "iot" + ] +}' +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-programatic-validation/pom.xml b/APPLICATIONS/springboot-programatic-validation/pom.xml new file mode 100644 index 00000000..1a1fe7bf --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + com.espark.adarsh + springboot-programatic-validation + 0.0.1-SNAPSHOT + springboot-programatic-validation + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java new file mode 100644 index 00000000..1365e5ac --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/SpringbootValidationBasicApplication.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootValidationBasicApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootValidationBasicApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/bean/User.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/bean/User.java new file mode 100644 index 00000000..c9c87d00 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/bean/User.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.bean; + +import jakarta.validation.constraints.*; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.time.LocalDate; +import java.util.List; + + +@Data +@Setter +@Getter +@ToString +public class User { + + @NotBlank(message = "Invalid Name: Empty name") + @NotNull(message = "Invalid Name: Name is NULL") + @Size(min = 3, max = 30, message = "Invalid Name: Must be of 3 - 30 characters") + String name; + + @Email(message = "Invalid email") + String email; + + @NotBlank(message = "Invalid Phone number: Empty number") + @NotNull(message = "Invalid Phone number: Number is NULL") + @Pattern(regexp = "^\\d{10}$", message = "Invalid phone number") + String mobile; + + @Min(value = 1, message = "Invalid Age: Equals to zero or Less than zero") + @Max(value = 100, message = "Invalid Age: Exceeds 100 years") + Integer age; + + @AssertTrue(message = "Working must be true") + private boolean working; + + @Size(min = 10, max = 200, message + = "About Me must be between 10 and 200 characters") + private String aboutMe; + + + @Past + private LocalDate dateOfBirth; + + private List<@NotBlank String> preference; + + +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/config/ApplicationConfig.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/config/ApplicationConfig.java new file mode 100644 index 00000000..a183978e --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/config/ApplicationConfig.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.config; + +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ApplicationConfig { + + @Bean + public Validator validator(){ + try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { + return factory.getValidator(); + } + } +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java new file mode 100644 index 00000000..0a17fc1b --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java @@ -0,0 +1,52 @@ +package com.espark.adarsh.exception; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.validation.FieldError; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class ApplicationExceptionHandler { + + /*@ExceptionHandler(UserNotFoundException.class) + public ResponseEntity>> handleNotFoundException(UserNotFoundException ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.NOT_FOUND); + }*/ + + + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidationErrors(MethodArgumentNotValidException ex) { + List errors = ex.getBindingResult().getFieldErrors() + .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + private Map> getErrorsMap(List errors) { + Map> errorResponse = new HashMap<>(); + errorResponse.put("errors", errors); + return errorResponse; + } + + @ExceptionHandler(Exception.class) + public final ResponseEntity>> handleGeneralExceptions(Exception ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(RuntimeException.class) + public final ResponseEntity>> handleRuntimeExceptions(RuntimeException ex) { + List errors = Collections.singletonList(ex.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/service/UserService.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/service/UserService.java new file mode 100644 index 00000000..9cb80794 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/service/UserService.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validator; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class UserService { + + @Autowired + Validator validator; + + public String inputUser(User user){ + Set> violations = validator.validate(user); + String result = violations.stream().map(ConstraintViolation::getMessage) + .collect(Collectors.joining(", ")); + return result.isEmpty() ? user.toString() : result; + } +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/web/UserController.java b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/web/UserController.java new file mode 100644 index 00000000..e85faac5 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/java/com/espark/adarsh/web/UserController.java @@ -0,0 +1,22 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.bean.User; +import com.espark.adarsh.service.UserService; +import jakarta.validation.Valid; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + + @Autowired + UserService userService; + + @PostMapping("/user") + public String inputUser(@RequestBody User user){ + return this.userService.inputUser(user); + } +} diff --git a/APPLICATIONS/springboot-programatic-validation/src/main/resources/application.properties b/APPLICATIONS/springboot-programatic-validation/src/main/resources/application.properties new file mode 100644 index 00000000..d53156d5 --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=springboot-validation-basic diff --git a/APPLICATIONS/springboot-programatic-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java b/APPLICATIONS/springboot-programatic-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java new file mode 100644 index 00000000..4df451bb --- /dev/null +++ b/APPLICATIONS/springboot-programatic-validation/src/test/java/com/espark/adarsh/SpringbootValidationBasicApplicationTests.java @@ -0,0 +1,52 @@ +package com.espark.adarsh; + +import com.espark.adarsh.bean.User; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Slf4j +@SpringBootTest +class SpringbootValidationBasicApplicationTests { + + + private Validator validator; + + @BeforeEach + void setUp() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + void contextLoads() { + } + + @Test + void test1(){ + User user = new User(); + user.setName("test-name"); + user.setWorking(true); + user.setAboutMe("test-about-me"); + user.setAge(24); + user.setEmail("adarsh@kumar.ut"); + + Set> violations = validator.validate(user); + display(violations); + assertTrue(violations.isEmpty()); + } + + + void display(Set> violations){ + for (ConstraintViolation violation : violations) { + log.error(violation.getMessage()); + } + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/.gitignore b/APPLICATIONS/springboot-rabbit-mqtt/.gitignore new file mode 100644 index 00000000..4a2eca51 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/.gitignore @@ -0,0 +1,36 @@ + +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +espark-adarsh-* +.DS_Store +/*.DS_Store +*.DS_Store +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/APPLICATIONS/springboot-rabbit-mqtt/README.md b/APPLICATIONS/springboot-rabbit-mqtt/README.md new file mode 100644 index 00000000..d335c8d0 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/README.md @@ -0,0 +1,74 @@ +# Springboot rabbitmq mqtt + +---- + +### To Build the code +* $ mvn clean package + +### To Run the application +* $ mvn spring-boot:run + +---- + +### To Start the docker rabbitmq with mqtt + + + +### To Create a mqtt plugin enabled file + +* $ cat >> /Users/us-guest/rabbitmq/enabled_plugins +``` +[rabbitmq_management,rabbitmq_mqtt]. + +``` +* crt+c + + +### To View the file content +* $ cat /Users/us-guest/rabbitmq/enabled_plugins + +### To give permission to the file +* $ sudo chmod -R 777 /Users/us-guest/rabbitmq/enabled_plugins + + +### To check the permisson +* $ sudo ls -ll /Users/us-guest/rabbitmq/enabled_plugins + +### To run the docker image +``` +$ docker run --restart always \ +-p 1883:1883 -p 15672:15672 -p 5672:5672 \ +-e RABBITMQ_DEFAULT_USER=adarsh \ +-e RABBITMQ_DEFAULT_PASS=password \ +-v /Users/us-guest/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins \ +-v /Users/us-guest/rabbitmq/:/var/lib/rabbitmq \ +--name espark-rabbit \ +rabbitmq:3-management +``` + + +### To check the docker container +* $ docker ps -a + +### To check the docker logs +$ docker log espark-rabbitmq + +### To log into the management console +* http://localhost:15672/#/ +* username/pwd + +### To Test the publishing using jmosquitto pub util +$ mosquitto_pub -t /espark/adarsh/data -h localhost -u adarsh -P password -p 1883 -m "welcome from epsark" + +### To Test the subscribing using jmosquitto sub util +$ mosquitto_sub -t /espark/adarsh/data -h localhost -u adarsh -P password -p 1883 + + +### To Test the application hit the api +``` +curl -X POST \ +http://localhost:8080/espark/mqtt \ +-H 'cache-control: no-cache' \ +-H 'content-type: application/json' \ +-d '{"topic":"/espark/adarsh/data" ,"data":"welcome to the epsark adarsh "}' +``` \ No newline at end of file diff --git a/APPLICATIONS/springboot-rabbit-mqtt/pom.xml b/APPLICATIONS/springboot-rabbit-mqtt/pom.xml new file mode 100644 index 00000000..0c7f6be4 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.1 + + + com.espark.adarsh + springboot-rabbit-mqtt + 0.0.1-SNAPSHOT + springboot-rabbit-mqtt + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + + + org.springframework.boot + spring-boot-starter-integration + + + org.springframework.integration + spring-integration-stream + + + org.springframework.integration + spring-integration-mqtt + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/SpringbootRabbitMqttApplication.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/SpringbootRabbitMqttApplication.java new file mode 100644 index 00000000..a8cc27d5 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/SpringbootRabbitMqttApplication.java @@ -0,0 +1,17 @@ +package com.espark.adarsh; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.integration.annotation.IntegrationComponentScan; + +@Slf4j +@IntegrationComponentScan +@SpringBootApplication +public class SpringbootRabbitMqttApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootRabbitMqttApplication.class, args); + } + +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/MqttProperties.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/MqttProperties.java new file mode 100644 index 00000000..95ae0412 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/MqttProperties.java @@ -0,0 +1,50 @@ +package com.espark.adarsh.beans; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ + +@Data +@Primary +@Validated +@Configuration +@ConfigurationProperties(prefix = "mqtt-properties") +public class MqttProperties { + + @NotBlank(message = "mqtt host url is mandatory properties in configuration ") + @NotNull(message = "mqtt host url is mandatory properties in configuration ") + private String host; + @NotBlank(message = "clientId is mandatory properties in configuration ") + @NotNull(message = "clientId is mandatory properties in configuration ") + private String clientId; + @NotBlank(message = "mqtt username is mandatory properties in configuration ") + @NotNull(message = "mqtt username is mandatory properties in configuration ") + private String username; + @NotBlank(message = "mqtt password is mandatory properties in configuration ") + @NotNull(message = "mqtt password is mandatory properties in configuration ") + private String password; + @NotBlank(message = "mqtt jmri subscribe topic is mandatory properties in configuration ") + @NotNull(message = "mqtt jmri subscribe topic is mandatory properties in configuration ") + private String topicSub; + @NotBlank(message = "mqtt jmri publish topic is mandatory properties in configuration ") + @NotNull(message = "mqtt jmri publish topic is mandatory properties in configuration ") + private String topicPublish; + + private String errorTopic; + private Boolean cleanSession; + private Integer connectionTimeout; + private Integer keepAliveInterval; + private Boolean automaticReconnect; + +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/RequestBean.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/RequestBean.java new file mode 100644 index 00000000..ba7c3891 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/beans/RequestBean.java @@ -0,0 +1,26 @@ +package com.espark.adarsh.beans; + +import lombok.Data; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ +@Data +@Validated +public class RequestBean implements Serializable { + + @NotBlank(message = "mqtt topic is mandatory properties in configuration ") + @NotNull(message = "mqtt topic is mandatory properties in configuration ") + String topic; + + @NotBlank(message = "mqtt topic value is mandatory properties in configuration ") + @NotNull(message = "mqtt topic value is mandatory properties in configuration ") + String data; +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/config/MQTTConfiguration.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/config/MQTTConfiguration.java new file mode 100644 index 00000000..858d737f --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/config/MQTTConfiguration.java @@ -0,0 +1,74 @@ +package com.espark.adarsh.config; + +import com.espark.adarsh.beans.MqttProperties; +import com.espark.adarsh.handler.MQTTMessageHandler; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.integration.dsl.IntegrationFlow; +import org.springframework.integration.dsl.IntegrationFlows; +import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory; +import org.springframework.integration.mqtt.core.MqttPahoClientFactory; +import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter; +import org.springframework.scheduling.annotation.EnableScheduling; + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ + +@EnableScheduling +@Configuration +@EnableConfigurationProperties({ + MqttProperties.class +}) +public class MQTTConfiguration { + + @Autowired + MqttProperties properties; + + @Bean + public MqttConnectOptions mqttConnectOptions(MqttProperties mqttProperties) { + MqttConnectOptions options = new MqttConnectOptions(); + options.setServerURIs(new String[]{mqttProperties.getHost()}); + options.setCleanSession(mqttProperties.getCleanSession()); + options.setUserName(mqttProperties.getUsername()); + options.setPassword(mqttProperties.getPassword().toCharArray()); + options.setConnectionTimeout(mqttProperties.getConnectionTimeout()); + options.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); + options.setAutomaticReconnect(mqttProperties.getAutomaticReconnect()); + options.setWill(properties.getErrorTopic(), "ServerOffline".getBytes(), 2, true); + return options; + } + + @Bean + public MqttPahoClientFactory mqttClientFactory(MqttConnectOptions options) { + DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); + factory.setConnectionOptions(options); + return factory; + } + + + @Bean + public MqttClient mqttClient(MqttProperties mqttProperties, MqttConnectOptions options) throws MqttException { + MqttClient mqttClient = new MqttClient(mqttProperties.getHost(), mqttProperties.getClientId() + System.currentTimeMillis()); + mqttClient.connect(options); + return mqttClient; + } + + @Bean + public IntegrationFlow mqttInbound(MqttProperties settings, + MqttPahoClientFactory mqttClientFactory, + MQTTMessageHandler mqttMessageHandler) { + return IntegrationFlows.from( + new MqttPahoMessageDrivenChannelAdapter(settings.getClientId() + System.currentTimeMillis(), mqttClientFactory, settings.getTopicSub())) + .handle(mqttMessageHandler) + .get(); + } + +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/exception/ApplicationException.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/exception/ApplicationException.java new file mode 100644 index 00000000..cd65e28d --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/exception/ApplicationException.java @@ -0,0 +1,18 @@ +package com.espark.adarsh.exception; + +public class ApplicationException extends Exception { + String message; + + public ApplicationException() { + } + + public ApplicationException(String message) { + super(message); + this.message = message; + } + + public ApplicationException(String message, Throwable cause) { + super(message, cause); + this.message = message; + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/MQTTMessageHandler.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/MQTTMessageHandler.java new file mode 100644 index 00000000..877a131b --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/MQTTMessageHandler.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.handler; + +import com.espark.adarsh.service.ApplicationMqttService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.MessagingException; +import org.springframework.stereotype.Component; + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ + +@Slf4j +@Component +public class MQTTMessageHandler implements MessageHandler { + + private final static String TOPIC_HEADER_NAME = "mqtt_receivedTopic"; + + @Autowired + ApplicationMqttService applicationMqttService; + + @Override + public void handleMessage(Message message) throws MessagingException { + try { + String topic = message.getHeaders().get(TOPIC_HEADER_NAME) + ""; + String data = message.getPayload().toString(); + log.info("=>>>> Message Received on Mqtt topic={} with Data={} ", topic, data); + this.applicationMqttService.transformData(topic, data); + } catch (Exception e) { + log.error("Exception while handle message in Mqtt Handler ", e.getMessage()); + } + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/TransformerExceptionHandler.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/TransformerExceptionHandler.java new file mode 100644 index 00000000..081d2fde --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/handler/TransformerExceptionHandler.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.handler; + +import com.espark.adarsh.exception.ApplicationException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@ControllerAdvice +public class TransformerExceptionHandler { + + @ExceptionHandler(ApplicationException.class) + public @ResponseBody + Map respondApplicationException(ApplicationException applicationException) { + log.error("TransformerExceptionHandler::respondApplicationException() {}", applicationException.getMessage()); + return new HashMap() { + { + put("message", applicationException.getMessage()); + } + }; + } + + @ExceptionHandler(Exception.class) + public @ResponseBody + Map respondException(Exception exception) { + log.error("TransformerExceptionHandler::respondException() {}", exception.getMessage()); + return new HashMap() { + { + put("message", exception.getMessage()); + } + }; + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/service/ApplicationMqttService.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/service/ApplicationMqttService.java new file mode 100644 index 00000000..508ba278 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/service/ApplicationMqttService.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.beans.MqttProperties; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.text.SimpleDateFormat; +import java.util.Date; + + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ + +@Slf4j +@Service +public class ApplicationMqttService { + + @Autowired + MqttClient mqttClient; + + @Autowired + MqttProperties properties; + + public void transformData(String mqttTopic, String message) throws Exception { + log.debug("Mqtt transformData mqttTopic = {} with message = {} ", mqttTopic, message); + Thread.currentThread().sleep(1000); + message = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()); + this.publish(properties.getTopicPublish(), message, 1, false); + } + + + public void publish(final String topic, final String payload, int qos, boolean retained) + throws MqttException { + log.info("<<<= Publishing to Mqtt Topic = {} payload = {}", topic, payload); + MqttMessage mqttMessage = new MqttMessage(); + mqttMessage.setPayload(payload.getBytes()); + mqttMessage.setQos(qos); + mqttMessage.setRetained(retained); + mqttClient.publish(topic, mqttMessage); + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/web/ApplicationMqttController.java b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/web/ApplicationMqttController.java new file mode 100644 index 00000000..8cc9a195 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/java/com/espark/adarsh/web/ApplicationMqttController.java @@ -0,0 +1,37 @@ +package com.espark.adarsh.web; + +import com.espark.adarsh.beans.RequestBean; +import com.espark.adarsh.service.ApplicationMqttService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/* + * @author Adarsh + * @author $LastChangedBy: adarsh $ + * @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ + */ + +@Slf4j +@RestController +public class ApplicationMqttController { + + private static final String PROCESSED_FAILED = "PROCESSED-FAILED"; + private static final String PROCESSED_SUCCESS = "PROCESSED-SUCCESS"; + + @Autowired + ApplicationMqttService applicationMqttService; + + @PostMapping("/mqtt") + public String postNodeData(@Valid @RequestBody RequestBean data) throws Exception { + try { + this.applicationMqttService.publish(data.getTopic(), data.getData(), 1, false); + } catch (Exception e) { + log.error("Exception e={}", e.getMessage()); + return PROCESSED_FAILED; + } + return PROCESSED_SUCCESS; + } +} diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.properties b/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.properties new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.yaml b/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.yaml new file mode 100644 index 00000000..af22d20e --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/main/resources/application.yaml @@ -0,0 +1,27 @@ +## +## @author Adarsh +## @author $LastChangedBy: adarsh $ +## @version $Revision: 0001 $, $Date:: 15/6/20 10:12 AM#$ +## + +spring: + profiles: default + +server: + servlet: + context-path: /espark #context path for the rest services + port: 8080 + +# Custom property mqtt configuration +mqtt-properties: + host: tcp://localhost:1883 # mqtt host with port + clientId: espark-adarsh- # client id for mqtt + username: adarsh # username for the mqtt + password: password # user password for the mqtt + topicSub: /espark/adarsh/# # top level topic name with regex + topicPublish: /espark/adarsh/data # top level topic name with regex + errorTopic: /amt/errors # jrmi error message topic name + cleanSession: true + connectionTimeout: 300 + keepAliveInterval: 60 + automaticReconnect: true \ No newline at end of file diff --git a/APPLICATIONS/springboot-rabbit-mqtt/src/test/java/com/espark/adarsh/SpringbootRabbitMqttApplicationTests.java b/APPLICATIONS/springboot-rabbit-mqtt/src/test/java/com/espark/adarsh/SpringbootRabbitMqttApplicationTests.java new file mode 100644 index 00000000..9aee85e8 --- /dev/null +++ b/APPLICATIONS/springboot-rabbit-mqtt/src/test/java/com/espark/adarsh/SpringbootRabbitMqttApplicationTests.java @@ -0,0 +1,13 @@ +package com.espark.adarsh; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootRabbitMqttApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-react-restcall/.gitignore b/APPLICATIONS/springboot-react-restcall/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..9cc84ea9 Binary files /dev/null and b/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..6c8c0e08 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/APPLICATIONS/springboot-react-restcall/Dockerfile b/APPLICATIONS/springboot-react-restcall/Dockerfile new file mode 100644 index 00000000..ec2ce55e --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8 +ADD target/springboot-react-restcall.jar springboot-react-restcall.jar +EXPOSE 9090 +ENTRYPOINT ["java","-jar","springboot-react-restcall.jar"] \ No newline at end of file diff --git a/APPLICATIONS/springboot-react-restcall/docker-compose.yaml b/APPLICATIONS/springboot-react-restcall/docker-compose.yaml new file mode 100644 index 00000000..2e2d8fc7 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/docker-compose.yaml @@ -0,0 +1,29 @@ +version: "3.2" +services: + espark-mysql: + image: mysql:5.7 + container_name: espark-mysql + restart: always + environment: + - MYSQL_ROOT_PASSWORD=root + - MYSQL_DATABASE=espark + - MYSQL_USER=root + - MYSQL_PASSWORD=root + ports: + - 3306:3306 + + springboot-jpa-mysql-docker: + image: springboot-react-restcall + depends_on: + - espark-mysql + links: + - espark-mysql + ports: + - 9090:9090 + environment: + - DATABASE_HOST=espark-mysql + - DATABASE_USER=root + - DATABASE_PASSWORD=root + - DATABASE_NAME=espark + - DATABASE_PORT=3306 + diff --git a/APPLICATIONS/springboot-react-restcall/document/docker build process.txt b/APPLICATIONS/springboot-react-restcall/document/docker build process.txt new file mode 100644 index 00000000..5b6ca522 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/document/docker build process.txt @@ -0,0 +1,73 @@ +https://hub.docker.com/_/mysql/ +mysql + +#to list the local docker images +$ docker images + +#to pull the mysql image to the local +$ docker pull mysql + +#to run the mysql docker image +$ docker run --name -e MYSQL_ROOT_PASSWORD= -e MYSQL_DATABASE= -d mysql:<5.6]> +$ docker run --name espark-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=espark -d mysql:5.6 + +#docker container listing +$ docker container ls + +------------------------------------------------------ +#chagne in the configuraiton file of spring data source + +spring.datasource.url = jdbc:mysql://espark-mysql:3306/espark +spring.datasource.username = root +spring.datasource.password = root +------------------------------------------------------ +#create a docker file in the application +$ vi Dockerfile + +FROM openjdk:8 +ADD target/product-information-system.jar product-information-system.jar +EXPOSE 9090 +ENTRYPOINT ["java","-jar","product-information-system.jar"] +------------------------------------------------------ +#to build the spring boot jar file +$ mvn clean package -Dmaven.test.skip=true + +#to build the docker image of the spring mysql application +$ docker build . -t product-information-system + +#list the images +$ docker images + +#to run the docker container +$ docker run -p 9090:9090 --name spring-boot-docker-mysql --link espark-mysql:mysql -d product-information-system + + +#to list the container +$ docker container ls + +#to check the log of the mysql +$ docker logs espark-mysql + +#to check the log of the spring boot application +$ docker logs spring-boot-docker-mysql + +#to stop the docker container of application +$ docker stop spring-boot-docker-mysql + +#to stp the docker container of the mysql +$ docker stop espark-mysql + +#To remove the docker iamge +$ docker image rm product-information-system +$ docker image rm mysql + + +#To remove the docker container +$ docker container rm spring-boot-docker-mysql +$ docker container rm espark-mysql + +----------------------------------------------------------------------------- +NOTE : CONFIGURATION WILL BE READ FROM .env FILE +#to run from docker compose +$ docker-compose up +----------------------------------------------------------------------------- \ No newline at end of file diff --git a/APPLICATIONS/springboot-react-restcall/document/help.txt b/APPLICATIONS/springboot-react-restcall/document/help.txt new file mode 100644 index 00000000..e7877faa --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/document/help.txt @@ -0,0 +1,38 @@ +#to find the pid on the port +$ sudo lsof -i : +$ sudo kill -9 +-------------------------------------------------------------------- +$ create database espark; +$ sudo /usr/local/mysql/support-files/mysql.server start +$ sudo /usr/local/mysql/support-files/mysql.server stop +-------------------------------------------------------------------- + +$ mvn clean package -Dmaven.test.skip=true +$ docker build . -t springboot-react-restcall +$ docker-compose up + + +======================================================= +EXECUTION PROCESS +======================================================= +1.Steps +to start the process for ui build first +------------------------------------------ +#to install the ui application dependency +$ sudo npm install + +#to build the ui application +$ sudo npm run build + +#to start only ui application +$ npm start + +2.Step +build the application backend and ui app +------------------------------------------ +#build using maven cmd +$ mvn clean package + +#execute the applications +$ java -jar target/springboot-react-restcall.jar +======================================================= diff --git a/APPLICATIONS/springboot-react-restcall/document/jpa method for repository .png b/APPLICATIONS/springboot-react-restcall/document/jpa method for repository .png new file mode 100644 index 00000000..4a844fe0 Binary files /dev/null and b/APPLICATIONS/springboot-react-restcall/document/jpa method for repository .png differ diff --git a/APPLICATIONS/springboot-react-restcall/package-lock.json b/APPLICATIONS/springboot-react-restcall/package-lock.json new file mode 100644 index 00000000..48e341a0 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/package-lock.json @@ -0,0 +1,3 @@ +{ + "lockfileVersion": 1 +} diff --git a/APPLICATIONS/springboot-react-restcall/pom.xml b/APPLICATIONS/springboot-react-restcall/pom.xml new file mode 100644 index 00000000..ea95a324 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/pom.xml @@ -0,0 +1,120 @@ + + + + 4.0.0 + + springboot-react-restcall + springboot-react-restcall + 0.0.1-SNAPSHOT + jar + + springboot-react-restcall + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + 8.0.12 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + springboot-react-restcall + + + org.springframework.boot + spring-boot-maven-plugin + + + com.github.eirslett + frontend-maven-plugin + 1.6 + + react-webapp + target + + + + install node and npm + + install-node-and-npm + + + v8.9.4 + 5.6.0 + + + + npm install + + npm + + + install + + + + npm run build + + npm + + + run build + + + + + + + maven-antrun-plugin + + + generate-resources + + + + + + + + + run + + + + + + + + diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/.gitignore b/APPLICATIONS/springboot-react-restcall/react-webapp/.gitignore new file mode 100644 index 00000000..f4917854 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/.gitignore @@ -0,0 +1,21 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/README.md b/APPLICATIONS/springboot-react-restcall/react-webapp/README.md new file mode 100644 index 00000000..2dab1ec2 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/README.md @@ -0,0 +1,2510 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +Below you will find some information on how to perform common tasks.
+You can find the most recent version of this guide [here](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md). + +## Table of Contents + +- [Updating to New Releases](#updating-to-new-releases) +- [Sending Feedback](#sending-feedback) +- [Folder Structure](#folder-structure) +- [Available Scripts](#available-scripts) + - [npm start](#npm-start) + - [npm test](#npm-test) + - [npm run build](#npm-run-build) + - [npm run eject](#npm-run-eject) +- [Supported Browsers](#supported-browsers) +- [Supported Language Features](#supported-language-features) +- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) +- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) +- [Debugging in the Editor](#debugging-in-the-editor) +- [Formatting Code Automatically](#formatting-code-automatically) +- [Changing the Page ``](#changing-the-page-title) +- [Installing a Dependency](#installing-a-dependency) +- [Importing a Component](#importing-a-component) +- [Code Splitting](#code-splitting) +- [Adding a Stylesheet](#adding-a-stylesheet) +- [Adding a CSS Modules Stylesheet](#adding-a-css-modules-stylesheet) +- [Adding a Sass Stylesheet](#adding-a-sass-stylesheet) +- [Post-Processing CSS](#post-processing-css) +- [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) +- [Adding SVGs](#adding-svgs) +- [Using the `public` Folder](#using-the-public-folder) + - [Changing the HTML](#changing-the-html) + - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + - [When to Use the `public` Folder](#when-to-use-the-public-folder) +- [Using Global Variables](#using-global-variables) +- [Adding Bootstrap](#adding-bootstrap) + - [Using a Custom Theme](#using-a-custom-theme) +- [Adding Flow](#adding-flow) +- [Adding Relay](#adding-relay) +- [Adding a Router](#adding-a-router) +- [Adding Custom Environment Variables](#adding-custom-environment-variables) + - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) + - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) + - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) +- [Can I Use Decorators?](#can-i-use-decorators) +- [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) +- [Integrating with an API Backend](#integrating-with-an-api-backend) + - [Node](#node) + - [Ruby on Rails](#ruby-on-rails) +- [Proxying API Requests in Development](#proxying-api-requests-in-development) + - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) + - [Configuring the Proxy Manually](#configuring-the-proxy-manually) +- [Using HTTPS in Development](#using-https-in-development) +- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) +- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) +- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) +- [Running Tests](#running-tests) + - [Filename Conventions](#filename-conventions) + - [Command Line Interface](#command-line-interface) + - [Version Control Integration](#version-control-integration) + - [Writing Tests](#writing-tests) + - [Testing Components](#testing-components) + - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) + - [Initializing Test Environment](#initializing-test-environment) + - [Focusing and Excluding Tests](#focusing-and-excluding-tests) + - [Coverage Reporting](#coverage-reporting) + - [Continuous Integration](#continuous-integration) + - [Disabling jsdom](#disabling-jsdom) + - [Snapshot Testing](#snapshot-testing) + - [Editor Integration](#editor-integration) +- [Debugging Tests](#debugging-tests) + - [Debugging Tests in Chrome](#debugging-tests-in-chrome) + - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) +- [Developing Components in Isolation](#developing-components-in-isolation) + - [Getting Started with Storybook](#getting-started-with-storybook) + - [Getting Started with Styleguidist](#getting-started-with-styleguidist) +- [Publishing Components to npm](#publishing-components-to-npm) +- [Making a Progressive Web App](#making-a-progressive-web-app) + - [Why Opt-in?](#why-opt-in) + - [Offline-First Considerations](#offline-first-considerations) + - [Progressive Web App Metadata](#progressive-web-app-metadata) +- [Analyzing the Bundle Size](#analyzing-the-bundle-size) +- [Deployment](#deployment) + - [Static Server](#static-server) + - [Other Solutions](#other-solutions) + - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) + - [Building for Relative Paths](#building-for-relative-paths) + - [Customizing Environment Variables for Arbitrary Build Environments](#customizing-environment-variables-for-arbitrary-build-environments) + - [Azure](#azure) + - [Firebase](#firebase) + - [GitHub Pages](#github-pages) + - [Heroku](#heroku) + - [Netlify](#netlify) + - [Now](#now) + - [S3 and CloudFront](#s3-and-cloudfront) + - [Surge](#surge) +- [Advanced Configuration](#advanced-configuration) +- [Troubleshooting](#troubleshooting) + - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) + - [`npm test` hangs or crashes on macOS Sierra](#npm-test-hangs-or-crashes-on-macos-sierra) + - [`npm run build` exits too early](#npm-run-build-exits-too-early) + - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) + - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) + - [Moment.js locales are missing](#momentjs-locales-are-missing) +- [Alternatives to Ejecting](#alternatives-to-ejecting) +- [Something Missing?](#something-missing) + +## Updating to New Releases + +Create React App is divided into two packages: + +- `create-react-app` is a global command-line utility that you use to create new projects. +- `react-scripts` is a development dependency in the generated projects (including this one). + +You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. + +When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. + +To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. + +In most cases bumping the `react-scripts` version in `package.json` and running `npm install` (or `yarn install`) in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. + +We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. + +## Sending Feedback + +We are always open to [your feedback](https://github.com/facebook/create-react-app/issues). + +## Folder Structure + +After creation, your project should look like this: + +``` +my-app/ + README.md + node_modules/ + package.json + public/ + index.html + favicon.ico + src/ + App.css + App.js + App.test.js + index.css + index.js + logo.svg +``` + +For the project to build, **these files must exist with exact filenames**: + +- `public/index.html` is the page template; +- `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> +You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. + +Only files inside `public` can be used from `public/index.html`.<br> +Read instructions below for using assets from JavaScript and HTML. + +You can, however, create more top-level directories.<br> +They will not be included in the production build so you can use them for things like documentation. + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.<br> +See the section about [running tests](#running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.<br> +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.<br> +Your app is ready to be deployed! + +See the section about [deployment](#deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Supported Browsers + +By default, the generated project supports all modern browsers.<br> +Support for Internet Explorer 9, 10, and 11 requires [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). + +### Supported Language Features + +This project supports a superset of the latest JavaScript standard.<br> +In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: + +- [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). +- [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). +- [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018). +- [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) +- [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). +- [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flow.org/) syntax. + +Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). + +While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. + +Note that **this project includes no [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)** by default. + +If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are [including the appropriate polyfills manually](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md), or that the browsers you are targeting already support them. + +## Syntax Highlighting in the Editor + +To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. + +## Displaying Lint Output in the Editor + +> Note: this feature is available with `react-scripts@0.2.0` and higher.<br> +> It also only works with npm 3 or higher. + +Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. + +They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. + +You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: + +```js +{ + "extends": "react-app" +} +``` + +Now your editor should report the linting warnings. + +Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. + +If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. + +## Debugging in the Editor + +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** + +Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. + +### Visual Studio Code + +You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. + +Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceRoot}/src", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + } + ] +} +``` + +> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. + +Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). + +### WebStorm + +You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. + +In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration. + +> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm. + +The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. + +## Formatting Code Automatically + +Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). + +To format our code whenever we make a commit in git, we need to install the following dependencies: + +```sh +npm install --save husky lint-staged prettier +``` + +Alternatively you may use `yarn`: + +```sh +yarn add husky lint-staged prettier +``` + +- `husky` makes it easy to use githooks as if they are npm scripts. +- `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). +- `prettier` is the JavaScript formatter we will run before commits. + +Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. + +Add the following field to the `package.json` section: + +```diff ++ "husky": { ++ "hooks": { ++ "pre-commit": "lint-staged" ++ } ++ } +``` + +Next we add a 'lint-staged' field to the `package.json`, for example: + +```diff + "dependencies": { + // ... + }, ++ "lint-staged": { ++ "src/**/*.{js,jsx,json,css}": [ ++ "prettier --single-quote --write", ++ "git add" ++ ] ++ }, + "scripts": { +``` + +Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. + +Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App†to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. + +If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). + +## Installing a Dependency + +The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +This works for any library, not just `react-router-dom`. + +## Importing a Component + +This project setup supports ES6 modules thanks to Webpack.<br> +While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. + +For example: + +### `Button.js` + +```js +import React, { Component } from 'react'; + +class Button extends Component { + render() { + // ... + } +} + +export default Button; // Don’t forget to use export default! +``` + +### `DangerButton.js` + +```js +import React, { Component } from 'react'; +import Button from './Button'; // Import a component from another file + +class DangerButton extends Component { + render() { + return <Button color="red" />; + } +} + +export default DangerButton; +``` + +Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. + +We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. + +Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. + +Learn more about ES6 modules: + +- [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) +- [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) +- [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) + +## Code Splitting + +Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. + +This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. + +Here is an example: + +### `moduleA.js` + +```js +const moduleA = 'Hello'; + +export { moduleA }; +``` + +### `App.js` + +```js +import React, { Component } from 'react'; + +class App extends Component { + handleClick = () => { + import('./moduleA') + .then(({ moduleA }) => { + // Use moduleA + }) + .catch(err => { + // Handle failure + }); + }; + + render() { + return ( + <div> + <button onClick={this.handleClick}>Load</button> + </div> + ); + } +} + +export default App; +``` + +This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. + +You can also use it with `async` / `await` syntax if you prefer it. + +### With React Router + +If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). + +Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending†the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `Button.css` + +```css +.Button { + padding: 20px; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import './Button.css'; // Tell Webpack that Button.js uses these styles + +class Button extends Component { + render() { + // You can use them as regular CSS styles + return <div className="Button" />; + } +} +``` + +**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-blog/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Adding a CSS Modules Stylesheet + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +This project supports [CSS Modules](https://github.com/css-modules/css-modules) alongside regular stylesheets using the `[name].module.css` file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format `[filename]\_[classname]\_\_[hash]`. + +> **Tip:** Should you want to preprocess a stylesheet with Sass then make sure to [follow the installation instructions](#adding-a-sass-stylesheet) and then change the stylesheet file extension as follows: `[name].module.scss` or `[name].module.sass`. + +CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules [here](https://css-tricks.com/css-modules-part-1-need/). + +### `Button.module.css` + +```css +.error { + background-color: red; +} +``` + +### `another-stylesheet.css` + +```css +.error { + color: red; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import styles from './Button.module.css'; // Import css modules stylesheet as styles +import './another-stylesheet.css'; // Import regular stylesheet + +class Button extends Component { + render() { + // reference as a js object + return <button className={styles.error}>Error Button</button>; + } +} +``` + +### Result + +No clashes from other `.error` class names + +```html +<!-- This button has red background but not red text --> +<button class="Button_error_ax7yz"></div> +``` + +**This is an optional feature.** Regular `<link>` stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the `.module.css` extension. + +## Adding a Sass Stylesheet + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). + +Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. + +To use Sass, first install `node-sass`: + +```bash +$ npm install node-sass --save +$ # or +$ yarn add node-sass +``` + +Now you can rename `src/App.css` to `src/App.scss` and update `src/App.js` to import `src/App.scss`. +This file and any other file will be automatically compiled if imported with the extension `.scss` or `.sass`. + +To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +This will allow you to do imports like + +```scss +@import 'styles/_colors.scss'; // assuming a styles directory under src/ +@import '~nprogress/nprogress'; // importing a css file from the nprogress node module +``` + +> **Tip:** You can opt into using this feature with [CSS modules](#adding-a-css-modules-stylesheet) too! + +> **Note:** You must prefix imports from `node_modules` with `~` as displayed above. + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. + +Support for new CSS features like the [`all` property](https://developer.mozilla.org/en-US/docs/Web/CSS/all), [`break` properties](https://www.w3.org/TR/css-break-3/#breaking-controls), [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), and [media query ranges](https://www.w3.org/TR/mediaqueries-4/#range-context) are automatically polyfilled to add support for older browsers. + +You can customize your target support browsers by adjusting the `browserslist` key in `package.json` accoring to the [Browserslist specification](https://github.com/browserslist/browserslist#readme). + +For example, this: + +```css +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +becomes this: + +```css +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). + +[CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) prefixing is disabled by default, but it will **not** strip manual prefixing. +If you'd like to opt-in to CSS Grid prefixing, [first familiarize yourself about its limitations](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie).<br> +To enable CSS Grid prefixing, add `/* autoprefixer grid: on */` to the top of your CSS file. + +## Adding Images, Fonts, and Files + +With Webpack, using static assets like images and fonts works similarly to CSS. + +You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. + +To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebook/create-react-app/issues/1153). + +Here is an example: + +```js +import React from 'react'; +import logo from './logo.png'; // Tell Webpack this JS file uses this image + +console.log(logo); // /logo.84287d09.png + +function Header() { + // Import result is the URL of your image + return <img src={logo} alt="Logo" />; +} + +export default Header; +``` + +This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. + +This works in CSS too: + +```css +.Logo { + background-image: url(./logo.png); +} +``` + +Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. + +Please be advised that this is also a custom feature of Webpack. + +**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> +An alternative way of handling static assets is described in the next section. + +### Adding SVGs + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this: + +```js +import { ReactComponent as Logo } from './logo.svg'; +const App = () => ( + <div> + {/* Logo is an actual React component */} + <Logo /> + </div> +); +``` + +This is handy if you don't want to load SVG as a separate file. Don't forget the curly braces in the import! The `ReactComponent` import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename. + +## Using the `public` Folder + +> Note: this feature is available with `react-scripts@0.5.0` and higher. + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). +This mechanism provides a number of benefits: + +- Scripts and stylesheets get minified and bundled together to avoid extra network requests. +- Missing files cause compilation errors instead of 404 errors for your users. +- Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. + +However there is an **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally we recommend using `import` for getting asset URLs + // as described in “Adding Images and Fonts†above this section. + return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; +} +``` + +Keep in mind the downsides of this approach: + +- None of the files in `public` folder get post-processed or minified. +- Missing files will not be called at compilation time, and will cause 404 errors for your users. +- Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. +The `public` folder is useful as a workaround for a number of less common cases: + +- You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +- You have thousands of images and need to dynamically reference their paths. +- You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +- Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using Global Variables + +When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. + +You can avoid this by reading the global variable explicitly from the `window` object, for example: + +```js +const $ = window.$; +``` + +This makes it obvious you are using a global variable intentionally rather than because of a typo. + +Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. + +## Adding Bootstrap + +You don’t have to use [reactstrap](https://reactstrap.github.io/) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: + +Install reactstrap and Bootstrap from npm. reactstrap does not include Bootstrap CSS so this needs to be installed as well: + +```sh +npm install --save reactstrap bootstrap@4 +``` + +Alternatively you may use `yarn`: + +```sh +yarn add bootstrap@4 reactstrap +``` + +Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file: + +```js +import 'bootstrap/dist/css/bootstrap.css'; +// Put any other imports below so that CSS from your +// components takes precedence over default styles. +``` + +Import required reactstrap components within `src/App.js` file or your custom component files: + +```js +import { Button } from 'reactstrap'; +``` + +Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/zx6658/d9f128cd57ca69e583ea2b5fea074238/raw/a56701c142d0c622eb6c20a457fbc01d708cb485/App.js) redone using reactstrap. + +### Using a Custom Theme + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> +As of `react-scripts@2.0.0` you can import `.scss` files. This makes it possible to use a package's built-in Sass variables for global style preferences. + +To customize Bootstrap, create a file called `src/custom.scss` (or similar) and import the Bootstrap source stylesheet. Add any overrides _before_ the imported file(s). You can reference [Bootstrap's documentation](http://getbootstrap.com/docs/4.1/getting-started/theming/#css-variables) for the names of the available variables. + +```scss +// Override default variables before the import +$body-bg: #000; + +// Import Bootstrap and its default variables +@import '~bootstrap/scss/bootstrap.scss'; +``` + +> **Note:** You must prefix imports from `node_modules` with `~` as displayed above. + +Finally, import the newly created `.scss` file instead of the default Bootstrap `.css` in the beginning of your `src/index.js` file, for example: + +```javascript +import './custom.scss'; +``` + +## Adding Flow + +Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. + +Recent versions of [Flow](https://flow.org/) work with Create React App projects out of the box. + +To add Flow to a Create React App project, follow these steps: + +1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). +2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. +3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flow.org/en/docs/config/) in the root directory. +4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). + +Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. +You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. +In the future we plan to integrate it into Create React App even more closely. + +To learn more about Flow, check out [its documentation](https://flow.org/). + +## Adding Relay + +Relay is a framework for building data-driven React applications powered by GraphQL. The current release candidate of Relay works with Create React App projects out of the box using Babel Macros. Simply set up your project as laid out in the [Relay documentation](https://facebook.github.io/relay/), then make sure you have a version of the babel plugin providing the macro. + +To add it, run: + +```sh +npm install --save --dev babel-plugin-relay@dev +``` + +Alternatively you may use `yarn`: + +```sh +yarn upgrade babel-plugin-relay@dev +``` + +Then, wherever you use the `graphql` template tag, import the macro: + +```js +import graphql from 'babel-plugin-relay/macro'; +// instead of: +// import { graphql } from "babel-plugin-relay" + +graphql` + query UserQuery { + viewer { + id + } + } +`; +``` + +To learn more about Relay, check out [its documentation](https://facebook.github.io/relay/). + +## Adding a Router + +Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/web/) is the most popular one. + +To add it, run: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. + +Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. + +## Adding Custom Environment Variables + +> Note: this feature is available with `react-scripts@0.2.3` and higher. + +Your project can consume variables declared in your environment as if they were declared locally in your JS files. By +default you will have `NODE_ENV` defined for you, and any other environment variables starting with +`REACT_APP_`. + +**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. + +> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +These environment variables will be defined for you on `process.env`. For example, having an environment +variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. + +There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. + +These environment variables can be useful for displaying information conditionally based on where the project is +deployed or consuming sensitive data that lives outside of version control. + +First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined +in the environment inside a `<form>`: + +```jsx +render() { + return ( + <div> + <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> + <form> + <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> + </form> + </div> + ); +} +``` + +During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. + +When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: + +```html +<div> + <small>You are running this application in <b>development</b> mode.</small> + <form> + <input type="hidden" value="abcdef" /> + </form> +</div> +``` + +The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this +value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in +a `.env` file. Both of these ways are described in the next few sections. + +Having access to the `NODE_ENV` is also useful for performing actions conditionally: + +```js +if (process.env.NODE_ENV !== 'production') { + analytics.disable(); +} +``` + +When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. + +### Referencing Environment Variables in the HTML + +> Note: this feature is available with `react-scripts@0.9.0` and higher. + +You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: + +```html +<title>%REACT_APP_WEBSITE_NAME% +``` + +Note that the caveats from the above section apply: + +- Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. +- The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). + +### Adding Temporary Environment Variables In Your Shell + +Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the +life of the shell session. + +#### Windows (cmd.exe) + +```cmd +set "REACT_APP_SECRET_CODE=abcdef" && npm start +``` + +(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) + +#### Windows (Powershell) + +```Powershell +($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) +``` + +#### Linux, macOS (Bash) + +```bash +REACT_APP_SECRET_CODE=abcdef npm start +``` + +### Adding Development Environment Variables In `.env` + +> Note: this feature is available with `react-scripts@0.5.0` and higher. + +To define permanent environment variables, create a file called `.env` in the root of your project: + +``` +REACT_APP_SECRET_CODE=abcdef +``` + +> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +`.env` files **should be** checked into source control (with the exclusion of `.env*.local`). + +#### What other `.env` files can be used? + +> Note: this feature is **available with `react-scripts@1.0.0` and higher**. + +- `.env`: Default. +- `.env.local`: Local overrides. **This file is loaded for all environments except test.** +- `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. +- `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. + +Files on the left have more priority than files on the right: + +- `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` +- `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` +- `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) + +These variables will act as the defaults if the machine does not explicitly set them.
+Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. + +> Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need +> these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). + +#### Expanding Environment Variables In `.env` + +> Note: this feature is available with `react-scripts@1.1.0` and higher. + +Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). + +For example, to get the environment variable `npm_package_version`: + +``` +REACT_APP_VERSION=$npm_package_version +# also works: +# REACT_APP_VERSION=${npm_package_version} +``` + +Or expand variables local to the current `.env` file: + +``` +DOMAIN=www.example.com +REACT_APP_FOO=$DOMAIN/foo +REACT_APP_BAR=$DOMAIN/bar +``` + +## Can I Use Decorators? + +Some popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
+Create React App intentionally doesn’t support decorator syntax at the moment because: + +- It is an experimental proposal and is subject to change (in fact, it has already changed once, and will change again). +- Most libraries currently support only the old version of the proposal — which will never be a standard. + +However in many cases you can rewrite decorator-based code without decorators just as fine.
+Please refer to these two threads for reference: + +- [#214](https://github.com/facebook/create-react-app/issues/214) +- [#411](https://github.com/facebook/create-react-app/issues/411) + +Create React App will add decorator support when the specification advances to a stable stage. + +## Fetching Data with AJAX Requests + +React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. + +The global `fetch` function allows you to easily make AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). + +A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. + +Make sure the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) are available in your target audience's browsers. +For example, support in Internet Explorer requires a [polyfill](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). + +You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). + +## Integrating with an API Backend + +These tutorials will help you to integrate your app with an API backend running on another port, +using `fetch()` to access it. + +### Node + +Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). + +### Ruby on Rails + +Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). + +### API Platform (PHP and Symfony) + +[API Platform](https://api-platform.com) is a framework designed to build API-driven projects. +It allows to create hypermedia and GraphQL APIs in minutes. +It is shipped with an official Progressive Web App generator as well as a dynamic administration interface, both built for Create React App. +Check out [this tutorial](https://api-platform.com/docs/distribution). + +## Proxying API Requests in Development + +> Note: this feature is available with `react-scripts@0.2.3` and higher. + +People often serve the front-end React app from the same host and port as their backend implementation.
+For example, a production setup might look like this after the app is deployed: + +``` +/ - static server returns index.html with React app +/todos - static server returns index.html with React app +/api/todos - server handles any /api/* requests using the backend implementation +``` + +Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. + +To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: + +```js + "proxy": "http://localhost:4000", +``` + +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy. + +Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: + +``` +Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. +``` + +Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. + +The `proxy` option supports HTTP, HTTPS and WebSocket connections.
+If the `proxy` option is **not** flexible enough for you, alternatively you can: + +- [Configure the proxy yourself](#configuring-the-proxy-manually) +- Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). +- Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. + +### "Invalid Host Header" Errors After Configuring Proxy + +When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). + +This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebook/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: + +> Invalid Host header + +To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: + +``` +HOST=mypublicdevhost.com +``` + +If you restart the development server now and load the app from the specified host, it should work. + +If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** + +``` +# NOTE: THIS IS DANGEROUS! +# It exposes your machine to attacks from the websites you visit. +DANGEROUSLY_DISABLE_HOST_CHECK=true +``` + +We don’t recommend this approach. + +### Configuring the Proxy Manually + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +If the `proxy` option is **not** flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware. + +You can use this feature in conjunction with the `proxy` property in `package.json`, but it is recommended you consolidate all of your logic into `src/setupProxy.js`. + +First, install `http-proxy-middleware` using npm or Yarn: + +```bash +$ npm install http-proxy-middleware --save +$ # or +$ yarn add http-proxy-middleware +``` + +Next, create `src/setupProxy.js` and place the following contents in it: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = function(app) { + // ... +}; +``` + +You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = function(app) { + app.use(proxy('/api', { target: 'http://localhost:5000/' })); +}; +``` + +> **Note:** You do not need to import this file anywhere. It is automatically registered when you start the development server. + +> **Note:** This file only supports Node's JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc). + +> **Note:** Passing the path to the proxy function allows you to use globbing and/or pattern matching on the path, which is more flexible than the express route matching. + +## Using HTTPS in Development + +> Note: this feature is available with `react-scripts@0.4.0` and higher. + +You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. + +To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: + +#### Windows (cmd.exe) + +```cmd +set HTTPS=true&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Windows (Powershell) + +```Powershell +($env:HTTPS = $true) -and (npm start) +``` + +#### Linux, macOS (Bash) + +```bash +HTTPS=true npm start +``` + +Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. + +## Generating Dynamic `` Tags on the Server + +Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: + +```html + + + + + +``` + +Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! + +If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. + +## Pre-Rendering into Static HTML Files + +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) or [react-snap](https://github.com/stereobooster/react-snap) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydratedâ€, when the JavaScript bundle has loaded. + +There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. + +The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. + +You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). + +## Injecting Data from the Server into the Page + +Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: + +```js + + + + +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +> Note: this feature is available with `react-scripts@0.3.0` and higher.
+ +> [Read the migration guide to learn how to enable it in older projects!](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +- Files with `.js` suffix in `__tests__` folders. +- Files with `.test.js` suffix. +- Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage†note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies†or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test†verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: + +```sh +npm install --save enzyme enzyme-adapter-react-16 react-test-renderer +``` + +Alternatively you may use `yarn`: + +```sh +yarn add enzyme enzyme-adapter-react-16 react-test-renderer +``` + +As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.) + +The adapter will also need to be configured in your [global setup file](#initializing-test-environment): + +#### `src/setupTests.js` + +```js +import { configure } from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; + +configure({ adapter: new Adapter() }); +``` + +> Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. + +Now you can write a smoke test with it: + +```js +import React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a ` + + ); + } +} +export default CategoryPost; diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/src/component/RestController.jsx b/APPLICATIONS/springboot-react-restcall/react-webapp/src/component/RestController.jsx new file mode 100644 index 00000000..6d39422d --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/src/component/RestController.jsx @@ -0,0 +1,55 @@ +import React from "react"; + +class RestController extends React.Component { + constructor(props) { + super(props); + this.state = { users: [] }; + this.headers = [ + { key: "catId", label: "Cat ID" }, + { key: "catName", label: "Cat Name" }, + { key: "catPath", label: "Cat Path" }, + { key: "level", label: "Level" }, + { key: "parentCatId", label: "Parent Id" } + ]; + } + + componentDidMount() { + fetch("http://localhost:9090/api/category") + .then(response => { + return response.json(); + }) + .then(result => { + this.setState({ + users: result + }); + }); + } + render() { + return ( +
+ + + {this.headers.map(function(h) { + return ; + })} + + + + {this.state.users.map(function(item, key) { + return ( + + + + + + + + ); + })} + +
{h.label}
{item.catId}{item.catName}{item.catPath}{item.level}{item.parentCatId}
+ ); + } +} + +export default RestController; diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.css b/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.css new file mode 100644 index 00000000..cee5f348 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.css @@ -0,0 +1,14 @@ +body { + margin: 0; + padding: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", + "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", + monospace; +} diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.js b/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.js new file mode 100644 index 00000000..f30469cd --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/src/index.js @@ -0,0 +1,15 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import "./index.css"; +import App from "./App"; +import RestController from "./component/RestController"; +import CategoryPost from "./component/CategoryPost"; +import * as serviceWorker from "./serviceWorker"; + +ReactDOM.render(, document.getElementById("root1")); +ReactDOM.render(, document.getElementById("root2")); + +// If you want your app to work offline and load faster, you can change +// unregister() to register() below. Note this comes with some pitfalls. +// Learn more about service workers: http://bit.ly/CRA-PWA +serviceWorker.unregister(); diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/src/logo.svg b/APPLICATIONS/springboot-react-restcall/react-webapp/src/logo.svg new file mode 100644 index 00000000..6b60c104 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/src/logo.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/APPLICATIONS/springboot-react-restcall/react-webapp/src/serviceWorker.js b/APPLICATIONS/springboot-react-restcall/react-webapp/src/serviceWorker.js new file mode 100644 index 00000000..8859a0c6 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/react-webapp/src/serviceWorker.js @@ -0,0 +1,127 @@ +// In production, we register a service worker to serve assets from local cache. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on the "N+1" visit to a page, since previously +// cached resources are updated in the background. + +// To learn more about the benefits of this model, read https://goo.gl/KwvDNy. +// This link also includes instructions on opting out of this behavior. + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +export function register(config) { + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://goo.gl/SC7cgQ' + ); + }); + } else { + // Is not local host. Just register service worker + registerValidSW(swUrl, config); + } + }); + } +} + +function registerValidSW(swUrl, config) { + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and + // the fresh content will have been added to the cache. + // It's the perfect time to display a "New content is + // available; please refresh." message in your web app. + console.log('New content is available; please refresh.'); + + // Execute callback + if (config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + + // Execute callback + if (config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch(error => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl, config) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + if ( + response.status === 404 || + response.headers.get('content-type').indexOf('javascript') === -1 + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log( + 'No internet connection found. App is running in offline mode.' + ); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/ApplicationMain.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/ApplicationMain.java new file mode 100644 index 00000000..4993310f --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/ApplicationMain.java @@ -0,0 +1,12 @@ +package com.espark.adarsh; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationMain { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/ApplicationController.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/ApplicationController.java new file mode 100644 index 00000000..d1222304 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/ApplicationController.java @@ -0,0 +1,9 @@ +package com.espark.adarsh.api; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class ApplicationController { + +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/CategoryController.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/CategoryController.java new file mode 100644 index 00000000..868ef83f --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/api/CategoryController.java @@ -0,0 +1,69 @@ +package com.espark.adarsh.api; + +import com.espark.adarsh.bean.CategoryBean; +import com.espark.adarsh.exception.ResourceNotFound; +import com.espark.adarsh.service.CategoryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.xml.bind.ValidationException; +import java.util.List; + +@RestController +@RequestMapping("/api") +public class CategoryController { + + @Autowired + private CategoryService categoryService; + + @GetMapping(value = "/category/{id}") + public com.espark.adarsh.bean.CategoryBean getCategory(@PathVariable("id") Long id) + throws ResourceNotFound { + return this.categoryService.getCategory(id); + } + + @GetMapping(value = "/category") + public List getCategory() throws ResourceNotFound { + return this.categoryService.getCategory(); + } + + @GetMapping(value = "/category-tree/{id}") + public CategoryBean getCategoryTree(@PathVariable("id") Long id) { + return this.categoryService.getCategoryTree(id); + } + + @GetMapping(value = "/category-tree") + public CategoryBean getCategoryTree() { + return this.categoryService.getCategoryTree(); + } + + @PostMapping(value = "/category") + public CategoryBean saveCategory(@RequestBody CategoryBean categoryBean) + throws ResourceNotFound, ValidationException { + return this.categoryService.saveCategory(categoryBean); + } + + @PutMapping(value = "/category/{id}") + public CategoryBean updateCategory(@PathVariable("id") Long id, + @RequestBody CategoryBean categoryBean) + throws ResourceNotFound, ValidationException { + return this.categoryService.updateCategory(id, categoryBean); + } + + + @DeleteMapping(value = "/category/{id}") + public CategoryBean deleteCategory(@PathVariable("id") Long id) + throws ResourceNotFound { + return this.categoryService.deleteCategory(id); + } + + + +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/bean/CategoryBean.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/bean/CategoryBean.java new file mode 100644 index 00000000..90cb9207 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/bean/CategoryBean.java @@ -0,0 +1,119 @@ +package com.espark.adarsh.bean; + +import com.espark.adarsh.entity.Category; +import com.fasterxml.jackson.annotation.*; +import java.io.Serializable; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CategoryBean implements Serializable { + + private Long catId; + + private String catName; + + private Long parentCatId; + + private List childCategory = new LinkedList<>(); + + private String catPath; + + private Integer level; + + private java.util.Date createdDate; + + private java.util.Date updatedDate; + + public CategoryBean() { + } + + public CategoryBean(Category category) { + this.catId = category.getCatId(); + this.catName = category.getCatName(); + this.catPath = category.getCatPath(); + this.level = category.getLevel(); + this.parentCatId = category.getParentCatId(); + this.createdDate = category.getCreatedDate(); + this.updatedDate = category.getUpdatedDate(); + } + + + + + @JsonIgnore + public Category getCategory() { + return new Category(catId, catName, catPath, level, parentCatId, createdDate, updatedDate); + } + + + public Long getCatId() { + return catId; + } + + public void setCatId(Long catId) { + this.catId = catId; + } + + public String getCatName() { + return catName; + } + + public void setCatName(String catName) { + this.catName = catName; + } + + public Long getParentCatId() { + return parentCatId; + } + + public void setParentCatId(Long parentCatId) { + this.parentCatId = parentCatId; + } + + public List getChildCategory() { + return childCategory; + } + + public void setChildCategoryBean(List childCategory) { + this.childCategory = childCategory; + } + + @JsonIgnore + public void setChildCategoryBean(CategoryBean childCategoryBean) { + this.childCategory.add(childCategoryBean); + } + + public String getCatPath() { + return catPath; + } + + public void setCatPath(String catPath) { + this.catPath = catPath; + } + + public Integer getLevel() { + return level; + } + + public void setLevel(Integer level) { + this.level = level; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getUpdatedDate() { + return updatedDate; + } + + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/content/ContentInitializer.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/content/ContentInitializer.java new file mode 100644 index 00000000..3beb270c --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/content/ContentInitializer.java @@ -0,0 +1,210 @@ +package com.espark.adarsh.content; + +import com.espark.adarsh.entity.Category; + +@org.springframework.stereotype.Component +public class ContentInitializer { + + @org.springframework.beans.factory.annotation.Autowired + private com.espark.adarsh.repostiory.CategoryRepository categoryRepository; + + @javax.annotation.PostConstruct + @javax.transaction.Transactional + public void init(){ + /* + -- Category -- + + Department + |--Home + | |--Furniture + | | |-Living Room + | | | |-Sofa + | | | |-Almira + | | | + | | |-Bed Room + | | | |-Bed + | | | |-Matres + | | | + | | |-Kitchen + | | | |-Containers + | | | |-Crockery + | | | + | |-Electronic + | |-TV + | |-Fridge + | |-Washing Machine + | + |-- Mens + | |-Shirt + | | |-FullShirt + | | |-HalfShirt + | | + | |-Pant + | | |-FullPant + | | |-HalfPant + | |-Watch + | | |-AnalogWatch + | | |-DigitalWatch + | | + |-- Womens + | |-Shirt + | | |-FullShirt + | | |-HalfShirt + | | + | |-Pant + | | |-FullPant + | | |-HalfPant + | |-Watch + | | |-AnalogWatch + | | |-DigitalWatch + | + |-- Kid + | |-Shirt + | | |-FullShirt + | | |-HalfShirt + | | + | |-Pant + | | |-FullPant + | | |-HalfPant + | | + | |-Watch + | | |-AnalogWatch + | | |-DigitalWatch + */ + + Category department=new Category(com.espark.adarsh.util.ApplicationUtil.HOME,null); + department.setCatId(1L); + department=saveOrUpdate(department); + + Category home=new Category("home",department); + home=saveOrUpdate(home); + + Category furniture=new Category("furniture",home); + furniture=saveOrUpdate(furniture); + + Category livingRoom=new Category("living-room",furniture); + livingRoom=saveOrUpdate(livingRoom); + + Category sofa=new Category("sofa",livingRoom); + sofa=saveOrUpdate(sofa); + + Category almira=new Category("almira",livingRoom); + almira=saveOrUpdate(almira); + + + Category bedRoom=new Category("bed-room",furniture); + bedRoom=saveOrUpdate(bedRoom); + + Category bedFrame=new Category("bed-frame",bedRoom); + bedFrame=saveOrUpdate(bedFrame); + + Category matress=new Category("matress",bedRoom); + matress=saveOrUpdate(matress); + + Category kitchen=new Category("kitchen",furniture); + kitchen=saveOrUpdate(kitchen); + + + + Category electronic=new Category("electronic",home); + electronic=saveOrUpdate(electronic); + + + Category men=new Category("men",department); + men=saveOrUpdate(men); + + Category menShirt=new Category("mens-shirt",men); + menShirt=saveOrUpdate(menShirt); + Category menFullShirt=new Category("mens-full-shirt",menShirt); + menFullShirt=saveOrUpdate(menFullShirt); + Category menHalfShirt=new Category("mens-half-shirt",menShirt); + menHalfShirt=saveOrUpdate(menHalfShirt); + + Category menPant=new Category("mens-pant",men); + menPant=saveOrUpdate(menPant); + Category menFullPant=new Category("mens-full-pant",menPant); + menFullPant=saveOrUpdate(menFullPant); + Category menHalfPant=new Category("mens-half-pant",menPant); + menHalfPant=saveOrUpdate(menHalfPant); + + Category menWatch=new Category("mens-watch",men); + menWatch=saveOrUpdate(menWatch); + Category menDigitalWatch=new Category("mens-digital-watch",menWatch); + menDigitalWatch=saveOrUpdate(menDigitalWatch); + Category menAnalogWatch=new Category("mens-analog-watch",menWatch); + menAnalogWatch=saveOrUpdate(menAnalogWatch); + + Category women=new Category("women",department); + women=saveOrUpdate(women); + + Category womenShirt=new Category("womens-shirt",women); + womenShirt=saveOrUpdate(womenShirt); + Category womenFullShirt=new Category("womens-full-shirt",womenShirt); + womenFullShirt=saveOrUpdate(womenFullShirt); + Category womenHalfShirt=new Category("womens-half-shirt",womenShirt); + womenHalfShirt=saveOrUpdate(womenHalfShirt); + + Category womenPant=new Category("womens-pant",women); + womenPant=saveOrUpdate(womenPant); + Category womenFullPant=new Category("womens-full-pant",womenPant); + womenFullPant=saveOrUpdate(womenFullPant); + Category womenHalfPant=new Category("womens-half-pant",womenPant); + womenHalfPant=saveOrUpdate(womenHalfPant); + + Category womenWatch=new Category("womens-watch",women); + womenWatch=saveOrUpdate(womenWatch); + Category womenDigitalWatch=new Category("womens-digital-watch",womenWatch); + womenDigitalWatch=saveOrUpdate(womenDigitalWatch); + Category womenAnalogWatch=new Category("womens-analog-watch",womenWatch); + womenAnalogWatch=saveOrUpdate(womenAnalogWatch); + + Category kid=new Category("kid",department); + kid=saveOrUpdate(kid); + + Category kidShirt=new Category("kid-shirt",kid); + kidShirt=saveOrUpdate(kidShirt); + Category kidFullShirt=new Category("kid-full-shirt",kidShirt); + kidFullShirt=saveOrUpdate(kidFullShirt); + Category kidHalfShirt=new Category("kid-half-shirt",kidShirt); + kidHalfShirt=saveOrUpdate(kidHalfShirt); + + Category kidPant=new Category("kid-pant",kid); + kidPant=saveOrUpdate(kidPant); + Category kidFullPant=new Category("kid-full-pant",kidPant); + kidFullPant=saveOrUpdate(kidFullPant); + Category kidHalfPant=new Category("kid-half-pant",kidPant); + kidHalfPant=saveOrUpdate(kidHalfPant); + + Category kidWatch=new Category("kid-watch",kid); + kidWatch=saveOrUpdate(kidWatch); + Category kidDigitalWatch=new Category("kid-digital-watch",kidWatch); + kidDigitalWatch=saveOrUpdate(kidDigitalWatch); + Category kidAnalogWatch=new Category("kid-analog-watch",kidWatch); + kidAnalogWatch=saveOrUpdate(kidAnalogWatch); + + + Category office=new Category("office",department); + office=saveOrUpdate(office); + + Category stationary=new Category("stationary",office); + stationary=saveOrUpdate(stationary); + + Category books=new Category("books",stationary); + books=saveOrUpdate(books); + + Category pen=new Category("pen",stationary); + pen=saveOrUpdate(pen); + + Category pencil=new Category("pencil",stationary); + pencil=saveOrUpdate(pencil); + + } + + private Category saveOrUpdate(Category category){ + Category currentCategory = this.categoryRepository.findByCatName(category.getCatName()); + if(currentCategory==null){ + currentCategory=this.categoryRepository.save(category); + } + return currentCategory; + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/entity/Category.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/entity/Category.java new file mode 100644 index 00000000..6a66de48 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/entity/Category.java @@ -0,0 +1,121 @@ +package com.espark.adarsh.entity; + + +import javax.validation.constraints.NotBlank; +import java.util.Date; + +@javax.persistence.Entity +@javax.persistence.Table(name = "category") +public class Category { + + @javax.persistence.Id + @javax.persistence.GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY) + private Long catId; + + @javax.validation.constraints.NotBlank + private String catName; + + @javax.validation.constraints.NotBlank + private String catPath; + + private Integer level; + + private Long parentCatId; + + @javax.persistence.Column(nullable = false, updatable = false) + @javax.persistence.Temporal(javax.persistence.TemporalType.TIMESTAMP) + @org.springframework.data.annotation.CreatedDate + private java.util.Date createdDate; + + @javax.persistence.Column(nullable = false) + @javax.persistence.Temporal(javax.persistence.TemporalType.TIMESTAMP) + @org.springframework.data.annotation.LastModifiedDate + private java.util.Date updatedDate; + + public Category() { + } + + public Category(@javax.validation.constraints.NotBlank String catName, + Category parentCat) { + this.catName = catName; + if (parentCat != null) { + this.parentCatId = parentCat.getCatId(); + this.catPath = parentCat.getCatPath() + "/" + catName; + this.level = parentCat.getLevel() + 1; + } else { + this.parentCatId = 0L; + this.catPath = "/" + this.catName; + this.level = 0; + } + this.createdDate = new Date(); + this.updatedDate = new Date(); + } + + public Category(Long catId, @NotBlank String catName + , @NotBlank String catPath, Integer level + , Long parentCatId, Date createdDate, Date updatedDate) { + this.catId = catId; + this.catName = catName; + this.catPath = catPath; + this.level = level; + this.parentCatId = parentCatId; + this.createdDate = createdDate; + this.updatedDate = updatedDate; + } + + public Long getCatId() { + return catId; + } + + public void setCatId(Long catId) { + this.catId = catId; + } + + public String getCatName() { + return catName; + } + + public void setCatName(String catName) { + this.catName = catName; + } + + public Long getParentCatId() { + return parentCatId; + } + + public void setParentCatId(Long parentCatId) { + this.parentCatId = parentCatId; + } + + public java.util.Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(java.util.Date createdDate) { + this.createdDate = createdDate; + } + + public java.util.Date getUpdatedDate() { + return updatedDate; + } + + public void setUpdatedDate(java.util.Date updatedDate) { + this.updatedDate = updatedDate; + } + + public String getCatPath() { + return catPath; + } + + public void setCatPath(String catPath) { + this.catPath = catPath; + } + + public Integer getLevel() { + return level; + } + + public void setLevel(Integer level) { + this.level = level; + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java new file mode 100644 index 00000000..0892fc33 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ApplicationExceptionHandler.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.exception; + +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@org.springframework.web.bind.annotation.ControllerAdvice +public class ApplicationExceptionHandler + extends ResponseEntityExceptionHandler { + + @org.springframework.web.bind.annotation.ExceptionHandler(value + = { IllegalArgumentException.class, IllegalStateException.class }) + protected org.springframework.http.ResponseEntity handleConflict( + RuntimeException ex, org.springframework.web.context.request.WebRequest request) { + String bodyOfResponse = "This should be application specific"; + return handleExceptionInternal(ex, bodyOfResponse, + new org.springframework.http.HttpHeaders(), org.springframework.http.HttpStatus.CONFLICT, request); + } + + @org.springframework.web.bind.annotation.ExceptionHandler(value + = { ResourceNotFound.class }) + protected org.springframework.http.ResponseEntity handleResourceNotFound(ResourceNotFound resourceNotFound,org.springframework.web.context.request.WebRequest request) { + return handleExceptionInternal(resourceNotFound, "Request Resource Not Found ", + new org.springframework.http.HttpHeaders(), org.springframework.http.HttpStatus.NOT_FOUND, request); + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ResourceNotFound.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ResourceNotFound.java new file mode 100644 index 00000000..027e8ca6 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/exception/ResourceNotFound.java @@ -0,0 +1,12 @@ +package com.espark.adarsh.exception; + +public class ResourceNotFound extends Exception{ + + public ResourceNotFound() { + super("Resource Not Found"); + } + + public ResourceNotFound(String message) { + super(message); + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/repostiory/CategoryRepository.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/repostiory/CategoryRepository.java new file mode 100644 index 00000000..f79025f5 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/repostiory/CategoryRepository.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.repostiory; + +import com.espark.adarsh.entity.Category; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface CategoryRepository extends CrudRepository { + + public Category findByCatName(String catName); + + @Query(value = "Select c From Category c where c.catPath LIKE :catPath%") + List findByCatPathStartingWith(@Param("catPath") String catPath); + +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryService.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryService.java new file mode 100644 index 00000000..03f5b419 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryService.java @@ -0,0 +1,24 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.CategoryBean; +import com.espark.adarsh.exception.ResourceNotFound; + +import javax.xml.bind.ValidationException; +import java.util.List; + +public interface CategoryService { + + CategoryBean saveCategory(CategoryBean category) throws ValidationException; + + List getCategory() throws ResourceNotFound; + + CategoryBean updateCategory(Long categoryId,CategoryBean category) throws ResourceNotFound, ValidationException; + + CategoryBean getCategory(Long categoryId) throws ResourceNotFound; + + CategoryBean deleteCategory(Long CategoryId) throws ResourceNotFound; + + CategoryBean getCategoryTree(); + + CategoryBean getCategoryTree(Long categoryId); +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryServiceImpl.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryServiceImpl.java new file mode 100644 index 00000000..01608a23 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/service/CategoryServiceImpl.java @@ -0,0 +1,138 @@ +package com.espark.adarsh.service; + +import com.espark.adarsh.bean.CategoryBean; +import com.espark.adarsh.entity.Category; +import com.espark.adarsh.exception.ResourceNotFound; +import com.espark.adarsh.repostiory.CategoryRepository; +import com.espark.adarsh.util.ApplicationUtil; +import com.espark.adarsh.util.TreeUtilService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import javax.xml.bind.ValidationException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +@Service("categoryService") +public class CategoryServiceImpl implements CategoryService { + + @Autowired + private CategoryRepository categoryRepository; + + @Autowired + TreeUtilService treeUtilService; + + @Override + @Transactional + public CategoryBean saveCategory(CategoryBean categoryBean) throws ValidationException { + Category category = categoryBean.getCategory(); + Category parentCategory = this.getParent(categoryBean); + category.setCatPath(parentCategory.getCatPath() + "/" + category.getCatName()); + category.setLevel(parentCategory.getLevel() + 1); + category.setCreatedDate(new Date()); + category.setUpdatedDate(new Date()); + category = this.categoryRepository.save(category); + return new CategoryBean(category); + } + + @Override + @Transactional + public List getCategory() throws ResourceNotFound { + Iterable iterable = this.categoryRepository.findAll(); + List categoryBeanList = new ArrayList<>(); + iterable.forEach(category -> { + categoryBeanList.add(new CategoryBean(category)); + }); + return categoryBeanList; + } + + @Override + @Transactional + public CategoryBean updateCategory(Long categoryId, CategoryBean categoryBean) + throws ResourceNotFound, ValidationException { + if (this.categoryRepository.existsById(categoryId)) { + Optional categoryOptional = this.categoryRepository.findById(categoryId); + Category currentCategory = categoryOptional.get(); + Category category = categoryBean.getCategory(); + category.setCatId(currentCategory.getCatId()); + category.setUpdatedDate(new Date()); + Category parentCategory = this.getParent(categoryBean); + category.setCatPath(parentCategory.getCatPath() + "/" + currentCategory.getCatName()); + category.setLevel(parentCategory.getLevel() + 1); + category = this.categoryRepository.save(category); + return new CategoryBean(category); + } else { + throw new ResourceNotFound("Category Not Found For " + categoryId); + } + } + + @Override + @Transactional + public CategoryBean getCategory(Long categoryId) throws ResourceNotFound { + com.espark.adarsh.entity.Category category = null; + if (this.categoryRepository.existsById(categoryId)) { + Optional categoryOptional = this.categoryRepository.findById(categoryId); + category = categoryOptional.get(); + } else { + throw new ResourceNotFound("Category Not Found For " + categoryId); + } + return new CategoryBean(category); + } + + @Override + @Transactional + public CategoryBean deleteCategory(Long categoryId) throws ResourceNotFound { + com.espark.adarsh.entity.Category category = null; + if (this.categoryRepository.existsById(categoryId)) { + Optional categoryOptional = this.categoryRepository.findById(categoryId); + category = categoryOptional.get(); + this.categoryRepository.deleteById(categoryId); + } else { + throw new ResourceNotFound("Category Not Found For " + categoryId); + } + return new CategoryBean(category); + } + + + @Override + @Transactional + public CategoryBean getCategoryTree() { + Category rootCategory = this.categoryRepository.findByCatName(ApplicationUtil.HOME); + List childCategory = this.categoryRepository.findByCatPathStartingWith(rootCategory.getCatPath()); + return this.treeUtilService.getTree(rootCategory, childCategory); + } + + @Override + @Transactional + public CategoryBean getCategoryTree(Long categoryId) { + Optional categoryOptional = this.categoryRepository.findById(categoryId); + if (categoryOptional.isPresent()) { + Category rootCategory = categoryOptional.get(); + //fetch all child node + List childCategory = this.categoryRepository.findByCatPathStartingWith(rootCategory.getCatPath()); + //construct a tree from them + return this.treeUtilService.getTree(rootCategory, childCategory); + } + return null; + } + + @Transactional + private Category getParent(CategoryBean categoryBean) throws ValidationException { + Category category = categoryBean.getCategory(); + try { + Long parentCatId = category.getParentCatId(); + Optional categoryOptional= this.categoryRepository.findById(parentCatId); + if (!categoryOptional.isPresent()) { + throw new ResourceNotFound("Parent Category Not Found For " + parentCatId); + }else{ + category=categoryOptional.get(); + } + } catch (Exception e) { + throw new ValidationException("Parent Category Not Found "); + } + return category; + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/ApplicationUtil.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/ApplicationUtil.java new file mode 100644 index 00000000..bc9f238b --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/ApplicationUtil.java @@ -0,0 +1,19 @@ +package com.espark.adarsh.util; + +public interface ApplicationUtil { + + public static final String HOME="department"; + + public default String getJsonString(Object object) throws java.io.IOException { + final com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(object); + } + + public default Object jsonToObject(String jsonString) throws java.io.IOException { + final com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL); + return mapper.readValue(jsonString, new com.fasterxml.jackson.core.type.TypeReference() { }); + } + +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/TreeUtilService.java b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/TreeUtilService.java new file mode 100644 index 00000000..4141530e --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/java/com/espark/adarsh/util/TreeUtilService.java @@ -0,0 +1,49 @@ +package com.espark.adarsh.util; + +import com.espark.adarsh.bean.CategoryBean; +import com.espark.adarsh.entity.Category; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class TreeUtilService { + + public CategoryBean getTree(Category rootCategory, List childCategory){ + return this.getTreeInternal(rootCategory,childCategory); + } + + private CategoryBean getTreeInternal(Category rootCategory, List childCategory){ + CategoryBean categoryBean= new CategoryBean(); + if(childCategory!=null && !childCategory.isEmpty()){ + Map> groupedChild = + childCategory.stream() + .filter(category -> category!=null) + .collect(Collectors.groupingBy(category -> category.getParentCatId())); + List child = groupedChild.get(rootCategory.getParentCatId()); + groupedChild.remove(rootCategory.getParentCatId()); + categoryBean= getTreeHierarchy(null,child,groupedChild); + } + return categoryBean; + } + + private CategoryBean getTreeHierarchy(CategoryBean categoryBean,List directChild + ,Map> groupedTotalChild ){ + if(directChild!=null && !directChild.isEmpty()){ + for(Category childCategory :directChild){ + CategoryBean childCategoryBean = new CategoryBean(childCategory); + if(categoryBean!=null) { + categoryBean.setChildCategoryBean(childCategoryBean); + }else{ + categoryBean=childCategoryBean; + } + List child = groupedTotalChild.get(childCategory.getCatId()); + groupedTotalChild.remove(childCategory.getCatId()); + this.getTreeHierarchy(childCategoryBean,child,groupedTotalChild); + } + } + return categoryBean; + } +} diff --git a/APPLICATIONS/springboot-react-restcall/src/main/resources/application.properties b/APPLICATIONS/springboot-react-restcall/src/main/resources/application.properties new file mode 100644 index 00000000..7f5508a1 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/resources/application.properties @@ -0,0 +1,16 @@ +server.port=9090 + +spring.jpa.hibernate.ddl-auto = update +spring.datasource.platform=mysql +spring.datasource.driverClassName=com.mysql.jdbc.Driver + + +#spring.datasource.url= jdbc:mysql://espark-mysql:3306/espark?useSSL=false +spring.datasource.url= jdbc:mysql://localhost:3306/espark?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +spring.datasource.username = root +spring.datasource.password = root +spring.datasource.testWhileIdle = true +spring.datasource.validationQuery = SELECT 1 +spring.jpa.show-sql = true +spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect \ No newline at end of file diff --git a/APPLICATIONS/springboot-react-restcall/src/main/resources/banner.txt b/APPLICATIONS/springboot-react-restcall/src/main/resources/banner.txt new file mode 100644 index 00000000..99eab8d7 --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/main/resources/banner.txt @@ -0,0 +1,10 @@ + ____ _ _ _ ____ _ _ + / ___| _ __ _ __ (_) _ __ __ _ | |__ ___ ___ | |_ | _ \ ___ __ _ ___ | |_ (_) ___ + \___ \ | '_ \ | '__| | | | '_ \ / _` | | '_ \ / _ \ / _ \ | __| | |_) | / _ \ / _` | / __| | __| | | / __| + ___) | | |_) | | | | | | | | | | (_| | | |_) | | (_) | | (_) | | |_ | _ < | __/ | (_| | | (__ | |_ | | \__ \ + |____/ | .__/ |_| |_| |_| |_| \__, | |_.__/ \___/ \___/ \__| |_| \_\ \___| \__,_| \___| \__| _/ | |___/ + |_| |___/ |__/ + + Espark Adarsh kumar + ============================================================================================================================ + diff --git a/APPLICATIONS/springboot-react-restcall/src/test/java/com/espark/adarsh/ApplicationTests.java b/APPLICATIONS/springboot-react-restcall/src/test/java/com/espark/adarsh/ApplicationTests.java new file mode 100644 index 00000000..699e238c --- /dev/null +++ b/APPLICATIONS/springboot-react-restcall/src/test/java/com/espark/adarsh/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.espark.adarsh; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/APPLICATIONS/springboot-react/.gitignore b/APPLICATIONS/springboot-react/.gitignore new file mode 100644 index 00000000..82eca336 --- /dev/null +++ b/APPLICATIONS/springboot-react/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.jar b/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..9cc84ea9 Binary files /dev/null and b/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.jar differ diff --git a/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.properties b/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..6c8c0e08 --- /dev/null +++ b/APPLICATIONS/springboot-react/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/APPLICATIONS/springboot-react/document/help.txt b/APPLICATIONS/springboot-react/document/help.txt new file mode 100644 index 00000000..6c09aab0 --- /dev/null +++ b/APPLICATIONS/springboot-react/document/help.txt @@ -0,0 +1,107 @@ +#create a webapp from spring io + +#add the maven plugin in pom for react js +--------------------------------------------------- + + com.github.eirslett + frontend-maven-plugin + 1.6 + + react-webapp + target + + + + install node and npm + + install-node-and-npm + + + v8.9.4 + 5.6.0 + + + + npm install + + npm + + + install + + + + npm run build + + npm + + + run build + + + + +--------------------------------------------------- + + maven-antrun-plugin + + + generate-resources + + + + + + + + + run + + + + +--------------------------------------------------- +# create a react application under the main project + +a)install the react package for creating a application in react + $ npm i -g create-react-app@1.5.2 + +b)this will create a react application inside the spring boot application + $ create-react-app + +#build the application using mvn cmd + $mvn clean package + +#execute the application +$java -jar target/springboot-react-0.0.1-SNAPSHOT.jar + +api url +http://localhost:9090/api/messge + +--------------------------------------------------- + + +======================================================= +EXECUTION PROCESS +======================================================= +1.Steps +to start the process for ui build first +------------------------------------------ +#to install the ui application dependency +$ npm install + +#to build the ui application +$ sudo npm run build + +#to start only ui application +$ npm start + +2.Step +build the application backend and ui app +------------------------------------------ +#build using maven cmd +$ mvn clean package + +#execute the application +$java -jar target/springboot-react-0.0.1-SNAPSHOT.jar +======================================================= \ No newline at end of file diff --git a/APPLICATIONS/springboot-react/mvnw b/APPLICATIONS/springboot-react/mvnw new file mode 100644 index 00000000..5bf251c0 --- /dev/null +++ b/APPLICATIONS/springboot-react/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/APPLICATIONS/springboot-react/mvnw.cmd b/APPLICATIONS/springboot-react/mvnw.cmd new file mode 100644 index 00000000..019bd74d --- /dev/null +++ b/APPLICATIONS/springboot-react/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/APPLICATIONS/springboot-react/package-lock.json b/APPLICATIONS/springboot-react/package-lock.json new file mode 100644 index 00000000..48e341a0 --- /dev/null +++ b/APPLICATIONS/springboot-react/package-lock.json @@ -0,0 +1,3 @@ +{ + "lockfileVersion": 1 +} diff --git a/APPLICATIONS/springboot-react/pom.xml b/APPLICATIONS/springboot-react/pom.xml new file mode 100644 index 00000000..8b43b990 --- /dev/null +++ b/APPLICATIONS/springboot-react/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + springboot-react + springboot-react + 0.0.1-SNAPSHOT + jar + + springboot-react + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + com.github.eirslett + frontend-maven-plugin + 1.6 + + react-webapp + target + + + + install node and npm + + install-node-and-npm + + + v8.9.4 + 5.6.0 + + + + npm install + + npm + + + install + + + + npm run build + + npm + + + run build + + + + + + + maven-antrun-plugin + + + generate-resources + + + + + + + + + run + + + + + + + + + + + diff --git a/APPLICATIONS/springboot-react/react-webapp/.gitignore b/APPLICATIONS/springboot-react/react-webapp/.gitignore new file mode 100644 index 00000000..f4917854 --- /dev/null +++ b/APPLICATIONS/springboot-react/react-webapp/.gitignore @@ -0,0 +1,21 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/APPLICATIONS/springboot-react/react-webapp/README.md b/APPLICATIONS/springboot-react/react-webapp/README.md new file mode 100644 index 00000000..2dab1ec2 --- /dev/null +++ b/APPLICATIONS/springboot-react/react-webapp/README.md @@ -0,0 +1,2510 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +Below you will find some information on how to perform common tasks.
+You can find the most recent version of this guide [here](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md). + +## Table of Contents + +- [Updating to New Releases](#updating-to-new-releases) +- [Sending Feedback](#sending-feedback) +- [Folder Structure](#folder-structure) +- [Available Scripts](#available-scripts) + - [npm start](#npm-start) + - [npm test](#npm-test) + - [npm run build](#npm-run-build) + - [npm run eject](#npm-run-eject) +- [Supported Browsers](#supported-browsers) +- [Supported Language Features](#supported-language-features) +- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) +- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) +- [Debugging in the Editor](#debugging-in-the-editor) +- [Formatting Code Automatically](#formatting-code-automatically) +- [Changing the Page ``](#changing-the-page-title) +- [Installing a Dependency](#installing-a-dependency) +- [Importing a Component](#importing-a-component) +- [Code Splitting](#code-splitting) +- [Adding a Stylesheet](#adding-a-stylesheet) +- [Adding a CSS Modules Stylesheet](#adding-a-css-modules-stylesheet) +- [Adding a Sass Stylesheet](#adding-a-sass-stylesheet) +- [Post-Processing CSS](#post-processing-css) +- [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) +- [Adding SVGs](#adding-svgs) +- [Using the `public` Folder](#using-the-public-folder) + - [Changing the HTML](#changing-the-html) + - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + - [When to Use the `public` Folder](#when-to-use-the-public-folder) +- [Using Global Variables](#using-global-variables) +- [Adding Bootstrap](#adding-bootstrap) + - [Using a Custom Theme](#using-a-custom-theme) +- [Adding Flow](#adding-flow) +- [Adding Relay](#adding-relay) +- [Adding a Router](#adding-a-router) +- [Adding Custom Environment Variables](#adding-custom-environment-variables) + - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) + - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) + - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) +- [Can I Use Decorators?](#can-i-use-decorators) +- [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) +- [Integrating with an API Backend](#integrating-with-an-api-backend) + - [Node](#node) + - [Ruby on Rails](#ruby-on-rails) +- [Proxying API Requests in Development](#proxying-api-requests-in-development) + - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) + - [Configuring the Proxy Manually](#configuring-the-proxy-manually) +- [Using HTTPS in Development](#using-https-in-development) +- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) +- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) +- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) +- [Running Tests](#running-tests) + - [Filename Conventions](#filename-conventions) + - [Command Line Interface](#command-line-interface) + - [Version Control Integration](#version-control-integration) + - [Writing Tests](#writing-tests) + - [Testing Components](#testing-components) + - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) + - [Initializing Test Environment](#initializing-test-environment) + - [Focusing and Excluding Tests](#focusing-and-excluding-tests) + - [Coverage Reporting](#coverage-reporting) + - [Continuous Integration](#continuous-integration) + - [Disabling jsdom](#disabling-jsdom) + - [Snapshot Testing](#snapshot-testing) + - [Editor Integration](#editor-integration) +- [Debugging Tests](#debugging-tests) + - [Debugging Tests in Chrome](#debugging-tests-in-chrome) + - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) +- [Developing Components in Isolation](#developing-components-in-isolation) + - [Getting Started with Storybook](#getting-started-with-storybook) + - [Getting Started with Styleguidist](#getting-started-with-styleguidist) +- [Publishing Components to npm](#publishing-components-to-npm) +- [Making a Progressive Web App](#making-a-progressive-web-app) + - [Why Opt-in?](#why-opt-in) + - [Offline-First Considerations](#offline-first-considerations) + - [Progressive Web App Metadata](#progressive-web-app-metadata) +- [Analyzing the Bundle Size](#analyzing-the-bundle-size) +- [Deployment](#deployment) + - [Static Server](#static-server) + - [Other Solutions](#other-solutions) + - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) + - [Building for Relative Paths](#building-for-relative-paths) + - [Customizing Environment Variables for Arbitrary Build Environments](#customizing-environment-variables-for-arbitrary-build-environments) + - [Azure](#azure) + - [Firebase](#firebase) + - [GitHub Pages](#github-pages) + - [Heroku](#heroku) + - [Netlify](#netlify) + - [Now](#now) + - [S3 and CloudFront](#s3-and-cloudfront) + - [Surge](#surge) +- [Advanced Configuration](#advanced-configuration) +- [Troubleshooting](#troubleshooting) + - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) + - [`npm test` hangs or crashes on macOS Sierra](#npm-test-hangs-or-crashes-on-macos-sierra) + - [`npm run build` exits too early](#npm-run-build-exits-too-early) + - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) + - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) + - [Moment.js locales are missing](#momentjs-locales-are-missing) +- [Alternatives to Ejecting](#alternatives-to-ejecting) +- [Something Missing?](#something-missing) + +## Updating to New Releases + +Create React App is divided into two packages: + +- `create-react-app` is a global command-line utility that you use to create new projects. +- `react-scripts` is a development dependency in the generated projects (including this one). + +You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. + +When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. + +To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. + +In most cases bumping the `react-scripts` version in `package.json` and running `npm install` (or `yarn install`) in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. + +We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. + +## Sending Feedback + +We are always open to [your feedback](https://github.com/facebook/create-react-app/issues). + +## Folder Structure + +After creation, your project should look like this: + +``` +my-app/ + README.md + node_modules/ + package.json + public/ + index.html + favicon.ico + src/ + App.css + App.js + App.test.js + index.css + index.js + logo.svg +``` + +For the project to build, **these files must exist with exact filenames**: + +- `public/index.html` is the page template; +- `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> +You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. + +Only files inside `public` can be used from `public/index.html`.<br> +Read instructions below for using assets from JavaScript and HTML. + +You can, however, create more top-level directories.<br> +They will not be included in the production build so you can use them for things like documentation. + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.<br> +See the section about [running tests](#running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.<br> +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.<br> +Your app is ready to be deployed! + +See the section about [deployment](#deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Supported Browsers + +By default, the generated project supports all modern browsers.<br> +Support for Internet Explorer 9, 10, and 11 requires [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). + +### Supported Language Features + +This project supports a superset of the latest JavaScript standard.<br> +In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: + +- [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). +- [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). +- [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018). +- [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) +- [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). +- [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flow.org/) syntax. + +Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). + +While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. + +Note that **this project includes no [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)** by default. + +If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are [including the appropriate polyfills manually](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md), or that the browsers you are targeting already support them. + +## Syntax Highlighting in the Editor + +To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. + +## Displaying Lint Output in the Editor + +> Note: this feature is available with `react-scripts@0.2.0` and higher.<br> +> It also only works with npm 3 or higher. + +Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. + +They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. + +You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: + +```js +{ + "extends": "react-app" +} +``` + +Now your editor should report the linting warnings. + +Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. + +If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. + +## Debugging in the Editor + +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** + +Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. + +### Visual Studio Code + +You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. + +Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceRoot}/src", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + } + ] +} +``` + +> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. + +Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). + +### WebStorm + +You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. + +In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration. + +> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm. + +The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. + +## Formatting Code Automatically + +Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). + +To format our code whenever we make a commit in git, we need to install the following dependencies: + +```sh +npm install --save husky lint-staged prettier +``` + +Alternatively you may use `yarn`: + +```sh +yarn add husky lint-staged prettier +``` + +- `husky` makes it easy to use githooks as if they are npm scripts. +- `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). +- `prettier` is the JavaScript formatter we will run before commits. + +Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. + +Add the following field to the `package.json` section: + +```diff ++ "husky": { ++ "hooks": { ++ "pre-commit": "lint-staged" ++ } ++ } +``` + +Next we add a 'lint-staged' field to the `package.json`, for example: + +```diff + "dependencies": { + // ... + }, ++ "lint-staged": { ++ "src/**/*.{js,jsx,json,css}": [ ++ "prettier --single-quote --write", ++ "git add" ++ ] ++ }, + "scripts": { +``` + +Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. + +Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App†to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. + +If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). + +## Installing a Dependency + +The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +This works for any library, not just `react-router-dom`. + +## Importing a Component + +This project setup supports ES6 modules thanks to Webpack.<br> +While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. + +For example: + +### `Button.js` + +```js +import React, { Component } from 'react'; + +class Button extends Component { + render() { + // ... + } +} + +export default Button; // Don’t forget to use export default! +``` + +### `DangerButton.js` + +```js +import React, { Component } from 'react'; +import Button from './Button'; // Import a component from another file + +class DangerButton extends Component { + render() { + return <Button color="red" />; + } +} + +export default DangerButton; +``` + +Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. + +We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. + +Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. + +Learn more about ES6 modules: + +- [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) +- [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) +- [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) + +## Code Splitting + +Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. + +This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. + +Here is an example: + +### `moduleA.js` + +```js +const moduleA = 'Hello'; + +export { moduleA }; +``` + +### `App.js` + +```js +import React, { Component } from 'react'; + +class App extends Component { + handleClick = () => { + import('./moduleA') + .then(({ moduleA }) => { + // Use moduleA + }) + .catch(err => { + // Handle failure + }); + }; + + render() { + return ( + <div> + <button onClick={this.handleClick}>Load</button> + </div> + ); + } +} + +export default App; +``` + +This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. + +You can also use it with `async` / `await` syntax if you prefer it. + +### With React Router + +If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). + +Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending†the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `Button.css` + +```css +.Button { + padding: 20px; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import './Button.css'; // Tell Webpack that Button.js uses these styles + +class Button extends Component { + render() { + // You can use them as regular CSS styles + return <div className="Button" />; + } +} +``` + +**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-blog/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Adding a CSS Modules Stylesheet + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +This project supports [CSS Modules](https://github.com/css-modules/css-modules) alongside regular stylesheets using the `[name].module.css` file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format `[filename]\_[classname]\_\_[hash]`. + +> **Tip:** Should you want to preprocess a stylesheet with Sass then make sure to [follow the installation instructions](#adding-a-sass-stylesheet) and then change the stylesheet file extension as follows: `[name].module.scss` or `[name].module.sass`. + +CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules [here](https://css-tricks.com/css-modules-part-1-need/). + +### `Button.module.css` + +```css +.error { + background-color: red; +} +``` + +### `another-stylesheet.css` + +```css +.error { + color: red; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import styles from './Button.module.css'; // Import css modules stylesheet as styles +import './another-stylesheet.css'; // Import regular stylesheet + +class Button extends Component { + render() { + // reference as a js object + return <button className={styles.error}>Error Button</button>; + } +} +``` + +### Result + +No clashes from other `.error` class names + +```html +<!-- This button has red background but not red text --> +<button class="Button_error_ax7yz"></div> +``` + +**This is an optional feature.** Regular `<link>` stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the `.module.css` extension. + +## Adding a Sass Stylesheet + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). + +Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. + +To use Sass, first install `node-sass`: + +```bash +$ npm install node-sass --save +$ # or +$ yarn add node-sass +``` + +Now you can rename `src/App.css` to `src/App.scss` and update `src/App.js` to import `src/App.scss`. +This file and any other file will be automatically compiled if imported with the extension `.scss` or `.sass`. + +To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +This will allow you to do imports like + +```scss +@import 'styles/_colors.scss'; // assuming a styles directory under src/ +@import '~nprogress/nprogress'; // importing a css file from the nprogress node module +``` + +> **Tip:** You can opt into using this feature with [CSS modules](#adding-a-css-modules-stylesheet) too! + +> **Note:** You must prefix imports from `node_modules` with `~` as displayed above. + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. + +Support for new CSS features like the [`all` property](https://developer.mozilla.org/en-US/docs/Web/CSS/all), [`break` properties](https://www.w3.org/TR/css-break-3/#breaking-controls), [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), and [media query ranges](https://www.w3.org/TR/mediaqueries-4/#range-context) are automatically polyfilled to add support for older browsers. + +You can customize your target support browsers by adjusting the `browserslist` key in `package.json` accoring to the [Browserslist specification](https://github.com/browserslist/browserslist#readme). + +For example, this: + +```css +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +becomes this: + +```css +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). + +[CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) prefixing is disabled by default, but it will **not** strip manual prefixing. +If you'd like to opt-in to CSS Grid prefixing, [first familiarize yourself about its limitations](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie).<br> +To enable CSS Grid prefixing, add `/* autoprefixer grid: on */` to the top of your CSS file. + +## Adding Images, Fonts, and Files + +With Webpack, using static assets like images and fonts works similarly to CSS. + +You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. + +To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebook/create-react-app/issues/1153). + +Here is an example: + +```js +import React from 'react'; +import logo from './logo.png'; // Tell Webpack this JS file uses this image + +console.log(logo); // /logo.84287d09.png + +function Header() { + // Import result is the URL of your image + return <img src={logo} alt="Logo" />; +} + +export default Header; +``` + +This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. + +This works in CSS too: + +```css +.Logo { + background-image: url(./logo.png); +} +``` + +Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. + +Please be advised that this is also a custom feature of Webpack. + +**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> +An alternative way of handling static assets is described in the next section. + +### Adding SVGs + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this: + +```js +import { ReactComponent as Logo } from './logo.svg'; +const App = () => ( + <div> + {/* Logo is an actual React component */} + <Logo /> + </div> +); +``` + +This is handy if you don't want to load SVG as a separate file. Don't forget the curly braces in the import! The `ReactComponent` import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename. + +## Using the `public` Folder + +> Note: this feature is available with `react-scripts@0.5.0` and higher. + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). +This mechanism provides a number of benefits: + +- Scripts and stylesheets get minified and bundled together to avoid extra network requests. +- Missing files cause compilation errors instead of 404 errors for your users. +- Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. + +However there is an **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally we recommend using `import` for getting asset URLs + // as described in “Adding Images and Fonts†above this section. + return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; +} +``` + +Keep in mind the downsides of this approach: + +- None of the files in `public` folder get post-processed or minified. +- Missing files will not be called at compilation time, and will cause 404 errors for your users. +- Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. +The `public` folder is useful as a workaround for a number of less common cases: + +- You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +- You have thousands of images and need to dynamically reference their paths. +- You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +- Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using Global Variables + +When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. + +You can avoid this by reading the global variable explicitly from the `window` object, for example: + +```js +const $ = window.$; +``` + +This makes it obvious you are using a global variable intentionally rather than because of a typo. + +Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. + +## Adding Bootstrap + +You don’t have to use [reactstrap](https://reactstrap.github.io/) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: + +Install reactstrap and Bootstrap from npm. reactstrap does not include Bootstrap CSS so this needs to be installed as well: + +```sh +npm install --save reactstrap bootstrap@4 +``` + +Alternatively you may use `yarn`: + +```sh +yarn add bootstrap@4 reactstrap +``` + +Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file: + +```js +import 'bootstrap/dist/css/bootstrap.css'; +// Put any other imports below so that CSS from your +// components takes precedence over default styles. +``` + +Import required reactstrap components within `src/App.js` file or your custom component files: + +```js +import { Button } from 'reactstrap'; +``` + +Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/zx6658/d9f128cd57ca69e583ea2b5fea074238/raw/a56701c142d0c622eb6c20a457fbc01d708cb485/App.js) redone using reactstrap. + +### Using a Custom Theme + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> +As of `react-scripts@2.0.0` you can import `.scss` files. This makes it possible to use a package's built-in Sass variables for global style preferences. + +To customize Bootstrap, create a file called `src/custom.scss` (or similar) and import the Bootstrap source stylesheet. Add any overrides _before_ the imported file(s). You can reference [Bootstrap's documentation](http://getbootstrap.com/docs/4.1/getting-started/theming/#css-variables) for the names of the available variables. + +```scss +// Override default variables before the import +$body-bg: #000; + +// Import Bootstrap and its default variables +@import '~bootstrap/scss/bootstrap.scss'; +``` + +> **Note:** You must prefix imports from `node_modules` with `~` as displayed above. + +Finally, import the newly created `.scss` file instead of the default Bootstrap `.css` in the beginning of your `src/index.js` file, for example: + +```javascript +import './custom.scss'; +``` + +## Adding Flow + +Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. + +Recent versions of [Flow](https://flow.org/) work with Create React App projects out of the box. + +To add Flow to a Create React App project, follow these steps: + +1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). +2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. +3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flow.org/en/docs/config/) in the root directory. +4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). + +Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. +You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. +In the future we plan to integrate it into Create React App even more closely. + +To learn more about Flow, check out [its documentation](https://flow.org/). + +## Adding Relay + +Relay is a framework for building data-driven React applications powered by GraphQL. The current release candidate of Relay works with Create React App projects out of the box using Babel Macros. Simply set up your project as laid out in the [Relay documentation](https://facebook.github.io/relay/), then make sure you have a version of the babel plugin providing the macro. + +To add it, run: + +```sh +npm install --save --dev babel-plugin-relay@dev +``` + +Alternatively you may use `yarn`: + +```sh +yarn upgrade babel-plugin-relay@dev +``` + +Then, wherever you use the `graphql` template tag, import the macro: + +```js +import graphql from 'babel-plugin-relay/macro'; +// instead of: +// import { graphql } from "babel-plugin-relay" + +graphql` + query UserQuery { + viewer { + id + } + } +`; +``` + +To learn more about Relay, check out [its documentation](https://facebook.github.io/relay/). + +## Adding a Router + +Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/web/) is the most popular one. + +To add it, run: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. + +Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. + +## Adding Custom Environment Variables + +> Note: this feature is available with `react-scripts@0.2.3` and higher. + +Your project can consume variables declared in your environment as if they were declared locally in your JS files. By +default you will have `NODE_ENV` defined for you, and any other environment variables starting with +`REACT_APP_`. + +**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. + +> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +These environment variables will be defined for you on `process.env`. For example, having an environment +variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. + +There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. + +These environment variables can be useful for displaying information conditionally based on where the project is +deployed or consuming sensitive data that lives outside of version control. + +First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined +in the environment inside a `<form>`: + +```jsx +render() { + return ( + <div> + <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> + <form> + <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> + </form> + </div> + ); +} +``` + +During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. + +When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: + +```html +<div> + <small>You are running this application in <b>development</b> mode.</small> + <form> + <input type="hidden" value="abcdef" /> + </form> +</div> +``` + +The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this +value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in +a `.env` file. Both of these ways are described in the next few sections. + +Having access to the `NODE_ENV` is also useful for performing actions conditionally: + +```js +if (process.env.NODE_ENV !== 'production') { + analytics.disable(); +} +``` + +When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. + +### Referencing Environment Variables in the HTML + +> Note: this feature is available with `react-scripts@0.9.0` and higher. + +You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: + +```html +<title>%REACT_APP_WEBSITE_NAME% +``` + +Note that the caveats from the above section apply: + +- Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. +- The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). + +### Adding Temporary Environment Variables In Your Shell + +Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the +life of the shell session. + +#### Windows (cmd.exe) + +```cmd +set "REACT_APP_SECRET_CODE=abcdef" && npm start +``` + +(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) + +#### Windows (Powershell) + +```Powershell +($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) +``` + +#### Linux, macOS (Bash) + +```bash +REACT_APP_SECRET_CODE=abcdef npm start +``` + +### Adding Development Environment Variables In `.env` + +> Note: this feature is available with `react-scripts@0.5.0` and higher. + +To define permanent environment variables, create a file called `.env` in the root of your project: + +``` +REACT_APP_SECRET_CODE=abcdef +``` + +> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +`.env` files **should be** checked into source control (with the exclusion of `.env*.local`). + +#### What other `.env` files can be used? + +> Note: this feature is **available with `react-scripts@1.0.0` and higher**. + +- `.env`: Default. +- `.env.local`: Local overrides. **This file is loaded for all environments except test.** +- `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. +- `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. + +Files on the left have more priority than files on the right: + +- `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` +- `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` +- `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) + +These variables will act as the defaults if the machine does not explicitly set them.
+Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. + +> Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need +> these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). + +#### Expanding Environment Variables In `.env` + +> Note: this feature is available with `react-scripts@1.1.0` and higher. + +Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). + +For example, to get the environment variable `npm_package_version`: + +``` +REACT_APP_VERSION=$npm_package_version +# also works: +# REACT_APP_VERSION=${npm_package_version} +``` + +Or expand variables local to the current `.env` file: + +``` +DOMAIN=www.example.com +REACT_APP_FOO=$DOMAIN/foo +REACT_APP_BAR=$DOMAIN/bar +``` + +## Can I Use Decorators? + +Some popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
+Create React App intentionally doesn’t support decorator syntax at the moment because: + +- It is an experimental proposal and is subject to change (in fact, it has already changed once, and will change again). +- Most libraries currently support only the old version of the proposal — which will never be a standard. + +However in many cases you can rewrite decorator-based code without decorators just as fine.
+Please refer to these two threads for reference: + +- [#214](https://github.com/facebook/create-react-app/issues/214) +- [#411](https://github.com/facebook/create-react-app/issues/411) + +Create React App will add decorator support when the specification advances to a stable stage. + +## Fetching Data with AJAX Requests + +React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. + +The global `fetch` function allows you to easily make AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). + +A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. + +Make sure the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) are available in your target audience's browsers. +For example, support in Internet Explorer requires a [polyfill](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). + +You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). + +## Integrating with an API Backend + +These tutorials will help you to integrate your app with an API backend running on another port, +using `fetch()` to access it. + +### Node + +Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). + +### Ruby on Rails + +Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). + +### API Platform (PHP and Symfony) + +[API Platform](https://api-platform.com) is a framework designed to build API-driven projects. +It allows to create hypermedia and GraphQL APIs in minutes. +It is shipped with an official Progressive Web App generator as well as a dynamic administration interface, both built for Create React App. +Check out [this tutorial](https://api-platform.com/docs/distribution). + +## Proxying API Requests in Development + +> Note: this feature is available with `react-scripts@0.2.3` and higher. + +People often serve the front-end React app from the same host and port as their backend implementation.
+For example, a production setup might look like this after the app is deployed: + +``` +/ - static server returns index.html with React app +/todos - static server returns index.html with React app +/api/todos - server handles any /api/* requests using the backend implementation +``` + +Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. + +To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: + +```js + "proxy": "http://localhost:4000", +``` + +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy. + +Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: + +``` +Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. +``` + +Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. + +The `proxy` option supports HTTP, HTTPS and WebSocket connections.
+If the `proxy` option is **not** flexible enough for you, alternatively you can: + +- [Configure the proxy yourself](#configuring-the-proxy-manually) +- Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). +- Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. + +### "Invalid Host Header" Errors After Configuring Proxy + +When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). + +This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebook/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: + +> Invalid Host header + +To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: + +``` +HOST=mypublicdevhost.com +``` + +If you restart the development server now and load the app from the specified host, it should work. + +If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** + +``` +# NOTE: THIS IS DANGEROUS! +# It exposes your machine to attacks from the websites you visit. +DANGEROUSLY_DISABLE_HOST_CHECK=true +``` + +We don’t recommend this approach. + +### Configuring the Proxy Manually + +> Note: this feature is available with `react-scripts@2.0.0` and higher. + +If the `proxy` option is **not** flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware. + +You can use this feature in conjunction with the `proxy` property in `package.json`, but it is recommended you consolidate all of your logic into `src/setupProxy.js`. + +First, install `http-proxy-middleware` using npm or Yarn: + +```bash +$ npm install http-proxy-middleware --save +$ # or +$ yarn add http-proxy-middleware +``` + +Next, create `src/setupProxy.js` and place the following contents in it: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = function(app) { + // ... +}; +``` + +You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = function(app) { + app.use(proxy('/api', { target: 'http://localhost:5000/' })); +}; +``` + +> **Note:** You do not need to import this file anywhere. It is automatically registered when you start the development server. + +> **Note:** This file only supports Node's JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc). + +> **Note:** Passing the path to the proxy function allows you to use globbing and/or pattern matching on the path, which is more flexible than the express route matching. + +## Using HTTPS in Development + +> Note: this feature is available with `react-scripts@0.4.0` and higher. + +You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. + +To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: + +#### Windows (cmd.exe) + +```cmd +set HTTPS=true&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Windows (Powershell) + +```Powershell +($env:HTTPS = $true) -and (npm start) +``` + +#### Linux, macOS (Bash) + +```bash +HTTPS=true npm start +``` + +Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. + +## Generating Dynamic `` Tags on the Server + +Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: + +```html + + + + + +``` + +Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! + +If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. + +## Pre-Rendering into Static HTML Files + +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) or [react-snap](https://github.com/stereobooster/react-snap) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydratedâ€, when the JavaScript bundle has loaded. + +There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. + +The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. + +You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). + +## Injecting Data from the Server into the Page + +Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: + +```js + + + + +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +> Note: this feature is available with `react-scripts@0.3.0` and higher.
+ +> [Read the migration guide to learn how to enable it in older projects!](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +- Files with `.js` suffix in `__tests__` folders. +- Files with `.test.js` suffix. +- Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage†note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies†or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test†verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: + +```sh +npm install --save enzyme enzyme-adapter-react-16 react-test-renderer +``` + +Alternatively you may use `yarn`: + +```sh +yarn add enzyme enzyme-adapter-react-16 react-test-renderer +``` + +As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.) + +The adapter will also need to be configured in your [global setup file](#initializing-test-environment): + +#### `src/setupTests.js` + +```js +import { configure } from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; + +configure({ adapter: new Adapter() }); +``` + +> Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. + +Now you can write a smoke test with it: + +```js +import React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `