Posts

Showing posts from April, 2020

Hibernate JPA @Where Example

@Where Sometimes, you want to filter out entities or collections using custom SQL criteria. This can be achieved using the @Where annotation, which can be applied to entities and collections. @Where mapping usage public enum AccountType { DEBIT, CREDIT } @Entity(name = "Client") public static class Client { @Id private Long id; private String name; @Where( clause = "account_type = 'DEBIT'") @OneToMany(mappedBy = "client") private List<Account> debitAccounts = new ArrayList<>( ); @Where( clause = "account_type = 'CREDIT'") @OneToMany(mappedBy = "client") private List<Account> creditAccounts = new ArrayList<>( ); //Getters and setters omitted for brevity } @Entity(name = "Account") @Where( clause = "active = true" ) public static class Account { @Id private Long id; @ManyToOne private Client client; @Column(name = "ac...

Hibernate HPA @Columns Example

@Columns The @Columns annotation is used to group multiple JPA @Column annotations. Columns Support an array of columns. Useful for component user types mappings.

Hibernate JPA @ColumnDefault Example

@ColumnDefault The @ColumnDefault annotation is used to specify the DEFAULT DDL value to apply when using the automated schema generator. ColumnDefault Identifies the DEFAULT value to apply to the associated column via DDL. The same behavior can be achieved using the definition attribute of the JPA @Column annotation.

Hibernate JPA @CollectionType Example

@CollectionType The @CollectionType annotation is used to specify a custom collection type. The collection can also name a @Type, which defines the Hibernate Type of the collection elements. CollectionType Names a custom collection type for a persistent collection. The collection can also name a @Type, which defines the Hibernate Type of the collection elements. Custom collection mapping example @Entity(name = "Person") public static class Person { @Id private Long id; @OneToMany(cascade = CascadeType.ALL) @CollectionType( type = "org.hibernate.userguide.collections.type.QueueType") private Collection<Phone> phones = new LinkedList<>(); //Constructors are omitted for brevity public Queue<Phone> getPhones() { return (Queue<Phone>) phones; } } @Entity(name = "Phone") public static class Phone implements Comparable<Phone> { @Id private Long id; private String type; @NaturalId @C...

Java Directories example

Java Directories example DirectoryStream • To iterate over the entries in a directory • Scales to large directories • Optional filter to decide if entries should be accepted or filtered • Built-in filters to match file names using glob or regular expression Path dir = Path.get("mydir"); DirectoryStream stream = dir.newDirectoryStream("*.java"); try { for (DirectoryEntry entry: stream) { System.out.println(entry.getName()); } } finally { stream.close(); } Path dir = Path.get("mydir"); Files.withDirectory(dir, "*.java", new DirectoryAction() { public void invoke(DirectoryEntry entry) { System.out.println(entry.getName()); } }); DirectoryStreamFilters • Factory methods for useful filters • newContentTypeFilter • Accept entry based on its MIME type • Use installed file type detectors • Combine filters into simple expressions Files.walkFileTree utility method • Recursively descends directory hierarchy rooted at s...

Java Copying and Moving Files using path

Java Copying and Moving Files using path copyTo method to copy file to target location • Options to replace existing file, copy file attributes... moveTo method to move file to target location • Option to replace existing file • Option to require operation to be atomic import static java.nio.file.StandardCopyOption.*; Path source = Path.get("C:\\My Documents\\Stuff.odp"); Path target = Path.get("D:\\Backup\\MyStuff.odp"); source.copyTo(target); source.copyTo(target, REPLACE_EXISTING, COPY_ATTRIBUTES);

Java - File Change Notification (WatchService)

Java - File Change Notification (WatchService) • Improve performance of applications that are forced to poll the file system today • WatchService – Watch registered objects for events and changes – Makes use of native event facility where available – Supports concurrent processing of events • Path implements Watchable – Register directory to get events when entries are created, deleted, or modified WatchService API • WatchKey represents registration of a watchable object with a WatchService. // register WatchKey key = file.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); // cancel registration key.cancel(); WatchKey represents registration of a watchable object with a WatchService. • WatchKey signalled and queued when event detected • WatchService poll or take methods used to retrieve signalled key. class WatchService {  WatchKey take();  WatchKey poll();  WatchKey poll(long timeout, TimeUnit unit); WatchKey represents registration of a watchabl...

Java AsynchronousSocketChannel

Java AsynchronousSocketChannel Using Future Example: AsynchronousSocketChannel ch = ... ByteBuffer buf = ... Future<Integer> result = ch.read(buf); Example: AsynchronousSocketChannel ch = ... ByteBuffer buf = ... Future<Integer> result = ch.read(buf); // check if I/O operation has completed boolean isDone = result.isDone(); Example: AsynchronousSocketChannel ch = ... ByteBuffer buf = ... Future<Integer> result = ch.read(buf); // wait for I/O operation to complete int nread = result.get(); Example: AsynchronousSocketChannel ch = ... ByteBuffer buf = ... Future<Integer> result = ch.read(buf); // wait for I/O operation to complete with timeout int nread = result.get(5, TimeUnit.SECONDS); CompletionHandler > V = type of result value > A = type of object attached to I/O operation ● Used to pass context ● Typically encapsulates connection context > completed method invoked if success > failed method invoked if I/O oper...

Durga Sir Core Java SCJP/OCJP Notes

Durga Sir is one of the best teacher in hyderabad not only for learning and attitude wise also. Core java and Advanced java notes by durga Soft.

Java Predicate Example – Predicate Filter

In mathematics, predicateUsually understood asboolean-valued function 'P: X? {true, false}' 'P: X? {true, false}', Called the predicate on X. You can think of it as an operator or function that returns trueor falsevalues. Java 8 Predicates Usage In Java 8, PredicateYesfunctional interface , So it can be used aslambda expressionOr the allocation target referenced by the method. So, what do you think, we can use these true / false return functions in daily programming? I will say that you can use predicates anywhere you need to evaluate conditions on groups / collections of similar objects so that evaluation can lead to true or false. For example, you canrealtime usecasesUse caserealtime usecases Find all children born after a certain date Pizza set a specific time Employees over a certain age, etc. Java Predicate Class therefore, java predicatesIt seems to be an interesting thing. Let's go deeper. As I said, Predicateyesfunctional interface. This means ...

Difference between @Controller and @RestController

It is obvious from the previous section that it @RestControlleris a convenient comment, which only adds @Controller and@ResponseBodyNotes . The main difference between traditional MVC @Controllerand RESTful Web services @RestControlleris the way in which the HTTP response body is created. The rest controller does not rely on view technology to perform the rendering of server-side data to HTML, but simply fills and returns the domain object itself. Object data will be written directly to the HTTP response in the form of JSON or XML, and parsed by the client to further process it to modify the existing view or for any other purpose. Using @Controller in spring mvc application @Controller example without @ResponseBody @Controller @RequestMapping("employees") public class EmployeeController {     @RequestMapping(value = "/{name}", method = RequestMethod.GET)     public Employee getEmployeeByName(@PathVariable String name, Model model) {     ...

ELK tutorial

Image
What is ELK? ELK is a combination of 3 open source products: Elasticsearch Logstash Kibana All developed and maintained by Elastic . Elasticsearch is a NoSQL database based on the Lucene search engine. Logstash is a log pipeline tool that accepts data input, performs data conversion, and then outputs data. Kibana is an interface layer that works on top of Elasticsearch. In addition, the ELK stack also contains a series of log collector tools called Beats. The most common usage scenario of ELK is as a log system for Internet products. Of course, the ELK stack can also be used in other aspects, such as: business intelligence, big data analysis, etc. Why use ELK? The ELK stack is very popular, because it is powerful, open source and free. For smaller companies such as SaaS companies and startups, using ELK to build a log system is very cost-effective. Netflix, Facebook, Microsoft, LinkedIn and Cisco also use ELK to monitor logs. Why use a logging system? The log sys...

Tomcat startup memory settings

Tomcat startup memory settings   The startup of Tomcat is divided into startupo.bat startup and registration as the startup of the windows service, which are explained one by one below. 1.startup.bat start Find catalina.bat in the tomcat_home / bin directory, open it with a text editor, and add the following line: set JAVA_OPTS = -Xms1024M -Xmx1024M -XX: PermSize = 256M -XX: MaxNewSize = 256M -XX: MaxPermSize = 256M Explain the parameters: -Xms1024M: Initialize the heap memory size (note that if M is not added, the unit is KB) -Xmx1029M: Maximum heap memory size -XX: PermSize = 256M: Initialize class loading memory pool size -XX: MaxPermSize = 256M: Maximum class loading memory pool size -XX: MaxNewSize = 256M: This is unclear, there is a saying There is also a -server parameter, which means that the server starts when the jvm is started, which is slower than the client, but the performance is better. You can choose it yourself. 2. The windows servic...

Setting up Swagger in Spring REST API

Setting Up Swagger with a Spring REST API 1. Overview Overview Good documentation is important when creating REST APIs. Moreover, whenever you change the API, you must specify the same in the reference documentation. It is very tedious to reflect this manually, so automating it is essential. In this tutorial we will  look at Swagger 2 for a Spring REST web service . In this document, we will use Springfox, the implementation of the Swager 2 specification. If you are not familiar with Swagger, we recommend that you visit the official webpage before reading this article  . 2.  Target Project REST service creation is not a category of this document, so users should already have a project that can be easily applied. If not already there, the following link would be a good starting point: Build a REST API with Spring 4 and Java Config article Building a RESTful Web Service . 3. Adding the Maven Dependency As mentioned above, we will use the Spring Fox imp...

Asynchronous processing with @Async in Spring

Asynchronous processing with @Async in Spring 1.Overview Overview In this article, we will look at asynchronous execution support and @Async annotation in Spring . Simply put, if you put the @Async annotation in an empty bean , it will be executed in a separate thread. For example, the caller does not have to wait for the called method to complete. 2. Turn on Async function  Enable Async Support Java settings Java configuration asynchronous processing by enabling asynchronous processing Just add the @EnableAsync to simply set the class to write : @Configuration @EnableAsync public class SpringAsyncConfig { ... } The above annotation is sufficient, but you can also set some options you need: annotation  – default, @EnableAsync  detectsSpring's Async annotations and EJB 3.1 javax.ejb.Asynchronous ; Other annotations customized with this option can also be detected. mode  – indicatesthe type of advice to use-based on JDK proxy or AspectJ weaving. proxyT...

Spring @Async and @EnableAsync annotation Example

Spring @Async and @EnableAsync annotation example @EnableAsync annotation Make the Application Executable, The @EnableAsync annotation switches on Spring’s ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Spring’s @Async annotation works with web applications, but you need not set up a web container to see its benefits. The following listing (from src/main/java/com/example/asyncmethod/AsyncMethodApplication.java) shows how to do so: package com.example.asyncmethod; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; @SpringBootApplication @EnableAsync public class AsyncMethodApplication {   public...

Spring @JsonIgnoreProperties annotation Example

Spring @JsonIgnoreProperties annotation The @ JsonIgnoreProperties annotation tells Spring to ignore any attributes not listed in the class. This makes it easy to make REST calls and produce domain objects. package com.example.asyncmethod; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown=true) public class User {   private String name;   private String blog;   public String getName() {     return name;   }   public void setName(String name) {     this.name = name;   }   public String getBlog() {     return blog;   }   public void setBlog(String blog) {     this.blog = blog;   }   @Override   public String toString() {     return "User [name=" + name + ", blog=" + blog + "]";   } }

Python - http — HTTP modules

http — HTTP modules http is a package that collects several modules for working with the HyperText Transfer Protocol: http.client is a low-level HTTP protocol client; for high-level URL opening use urllib.request http.server contains basic HTTP server classes based on socketserver http.cookies has utilities for implementing state management with cookies http.cookiejar provides persistence of cookies http.client — HTTP protocol client This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib.request uses it to handle URLs that use HTTP and HTTPS. class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192) class http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None, blocksize=8192) For example, the following calls all create instances that connect to th...

Python - concurrent.futures — Launching parallel tasks

Python - concurrent.futures — Launching parallel tasks The concurrent.futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class. Executor Objects class concurrent.futures.Executor An abstract class that provides methods to execute calls asynchronously. It should not be used directly, but through its concrete subclasses. submit(fn, /, *args, **kwargs) Schedules the callable, fn, to be executed as fn(*args **kwargs) and returns a Future object representing the execution of the callable. with ThreadPoolExecutor(max_workers=1) as executor:     future = executor.submit(pow, 323, 1235)     print(future.result()) map(func, *iterables, timeout=None, chunksize=1) Similar to map(func, *iterables) except: the itera...