Posts

Showing posts from July, 2020

Spring supplier Example

Non Spring Developers Let us assume for a second that you are not a Spring developer and not familiar with Spring Integration which already provides abstractions for ROME. In that case, we can certainly use ROME directly to produce feed records. For example, this is a valid Supplier for this scenario. public Supplier<SyndEntry> feedSupplier() { return () -> { //Use the ROME framework directly to produce syndicated entries. } } The benefit here is that we can develop the supplier without any knowledge of Spring, and it can be deployed to a serverless environment directly, using the abstractions provided by that environment or by relying on a framework like Spring Cloud Function. This essentially means that if you are a Java developer without much Spring Framework skills, you can still write the functions using just the interfaces defined in the java.util.function package such as Function, Supplier and Consumer, by providing the business logic.  Spring Developers Add ...

Hibernate JPA @Polymorphism Example

The @Polymorphism annotation is used to define the PolymorphismType Hibernate will apply to entity hierarchies. There are two possible PolymorphismType options: EXPLICIT The currently annotated entity is retrieved only if explicitly asked. IMPLICIT The currently annotated entity is retrieved if any of its super entities are retrieved. This is the default option. Implicit and explicit polymorphism By default, when you query a base class entity, the polymorphic query will fetch all subclasses belonging to the base type. However, you can even query interfaces or base classes that don’t belong to the JPA entity inheritance model. For instance, considering the following DomainModelEntity interface: Example : DomainModelEntity interface public interface DomainModelEntity<ID> {     ID getId();     Integer getVersion(); } If we have two entity mappings, a Book and a Blog, and the Blog entity is mapped with the @Polymorphism annotation and taki...

Hibernate JPA @Persister Example

The @Persister annotation is used to specify a custom entity or collection persister. For entities, the custom persister must implement the EntityPersister interface. For collections, the custom persister must implement the CollectionPersister interface. Define a custom entity persister The @Persister annotation is used to specify a custom entity or collection persister. For entities, the custom persister must implement the EntityPersister interface. For collections, the custom persister must implement the CollectionPersister interface. Example : Entity persister mapping @Entity @Persister( impl = EntityPersister.class ) public class Author {     @Id     public Integer id;     @OneToMany( mappedBy = "author" )     @Persister( impl = CollectionPersister.class )     public Set<Book> books = new HashSet<>();     //Getters and setters omitted for brevity     public void addBook(Bo...

Hibernate JPA @Parent Example

The @Parent annotation is used to specify that the currently annotated embeddable attribute references back the owning entity. Parent Reference the property as a pointer back to the owner (generally the owning entity). @Parent mapping The Hibernate-specific @Parent annotation allows you to reference the owner entity from within an embeddable. Example 93. @Parent mapping usage @Embeddable public static class GPS { private double latitude; private double longitude; @Parent private City city; //Getters and setters omitted for brevity } @Entity(name = "City") public static class City { @Id @GeneratedValue private Long id; private String name; @Embedded @Target( GPS.class ) private GPS coordinates; //Getters and setters omitted for brevity }

Hibernate JPA @Parameter Example

The @Parameter annotation is a generic parameter (basically a key/value combination) used to parametrize other annotations, like @CollectionType, @GenericGenerator, and @Type, @TypeDef. Parameter - Generic parameter (basically a key/value combination) used to parametrize other annotations.

Hibernate JPA @ParamDef Example

ParamDef is a parameter definition. The @ParamDef annotation is used in conjunction with @FilterDef so that the Hibernate Filter can be customized with runtime-provided parameter values.

Java - Linear Search Example

Linear search, also called as sequential search, is a very simple method used for searching an array for a particular value. It works by comparing the value to be searched with every element of the array one by one in a sequence until a match is found. Linear search is mostly used to search an unordered list of elements (array in which data elements are not sorted). For example, if an array A[] is declared and initialized as, int A[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5}; and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3 (index starting from 0). Algorithm for linear search: LINEAR_SEARCH(A, N, VAL) Step 1: [INITIALIZE] SET POS=-1 Step 2: [INITIALIZE] SETI=1 Step 3: Repeat Step 4 while I<=N Step 4: IF A[I] = VAL         SET POS=I          PRINT POS         Go to St...

C, C++ (malloc, calloc, free and realloc) different type of Memory allocation/de-allocation functions

malloc()  Allocates memory and returns a pointer to the first byte of allocated space. The general syntax of malloc() is ptr =(cast-type*)malloc(byte-size); Example: arr=(int*)malloc(10*sizeof(int)); calloc()  Allocates space for an array of elements, initializes them to zero and returns a pointer to the memory. The syntax of calloc() can be given as: ptr=(cast-type*) calloc(n,elem-size); free() Frees previously allocated memory. The general syntax of the free()function is, free(ptr); realloc()  Alters the size of previously allocated memory. The general syntax for realloc() can be given as, ptr = realloc(ptr,newsize);

Inserting a Node at the End of a Linked List

Suppose we want to add a new node with data as the last node of the list. Algorithm to insert a new node at the end of a linked list Step 1: IF AVAIL = NULL           Write OVERFLOW           Go to Step 10         [END OF IF] Step 2: SET NEW_NODE = AVAIL Step 3: SET AVAIL = AVAIL.NEXT Step 4: SET NEW_NODE.DATA = VAL Step 5: SET NEW_NODE.NEXT = NULL Step 6: SET PTR = START Step 7: Repeat Step 8 while PTR NEXT != NULL Step 8: SET PTR = PTR.NEXT        [END OF LOOP] Step 9: SET PTR NEXT = NEW_NODE Step 10: EXIT we take a pointer variable PTR and initialize it with START. That is, PTR now points to the first node of the linked list. In the while loop, we traverse through the linked list to reach the last node. Once we reach the last node, in Step 9, we change the NEXT pointer of the last node to store the address of the new node. Remember that the NEXT field of the new node contain...

Angular 10 : Tree View Example

Image
The mat-tree provides a Material Design styled tree that can be used to display hierarchy data. This tree builds on the foundation of the CDK tree and uses a similar interface for its data source input and template, except that its element and attribute selectors will be prefixed with mat- instead of cdk-. There are two types of trees: Flat tree and nested tree. The DOM structures are different for these two types of trees. Flat tree In a flat tree, the hierarchy is flattened; nodes are not rendered inside of each other, but instead are rendered as siblings in sequence. An instance of TreeFlattener is used to generate the flat list of items from hierarchical data. The "level" of each tree node is read through the getLevel method of the TreeControl; this level can be used to style the node such that it is indented to the appropriate level. <mat-tree>   <mat-tree-node> parent node </mat-tree-node>   <mat-tree-node> -- child node1 </mat...

Java - JEP 347: Enable C++14 Language Features

This features added in JDK 16. This includes being able to build with recent versions of various compilers that support C++11/14 language features. Summary: Allow the use of C++14 language features in JDK C++ source code, and give specific guidance about which of those features may be used in HotSpot code. The purpose of this JEP is to formally allow C++ source code changes within the JDK to take advantage of C++14 language features. Lists of new features for C++11 and C++14, along with links to their descriptions, can be found in the online documentation for some of the compilers and libraries: C++ Standards Support in GCC C++ Support in Clang Visual C++ Language Conformance libstdc++ Status libc++ Status

Spring @Bean Annotation Example

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports some of the attributes offered by <bean/>, such as: * init-method * destroy-method * autowiring * name. You can use the @Bean annotation in a @Configuration-annotated or in a @Component-annotated class. Declaring a Bean: To declare a bean, you can annotate a method with the @Bean annotation. You use this method to register a bean definition within an ApplicationContext of the type specified as the method’s return value. By default, the bean name is the same as the method name. The following example shows a @Bean method declaration: @Configuration public class AppConfig {     @Bean     public TransferServiceImpl transferService() {         return new TransferServiceImpl();     } } The preceding configuration is exactly equivalent to the following Spring XML: <beans>     <bean id="tra...

Spring @CrossOrigin Example

Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secured and less powerful hacks like IFRAME or JSONP. As of Spring Framework 4.2, CORS is supported out of the box. CORS requests (including preflight ones with an OPTIONS method) are automatically dispatched to the various registered HandlerMappings. They handle CORS preflight requests and intercept CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (like Access-Control-Allow-Origin) based on the CORS configuration you have provided. [Note] Be aware that cookies are not allowed by default to avoid increasing the surface attack of the web application (for example via exposing sensitive user-specific information like CSRF tokens). Set allowedCredentials property to tr...

Introducing Java Functions for Spring Cloud Stream Applications - Part 1

Last week Spring posted Introducing Java Functions for Spring Cloud Stream Applications - Part 0 to announce the release of Spring Cloud Stream applications 2020.0.0-M2. Here, explore function composition, one of the more powerful features enabled by the function oriented architecture presented in Part 0. If you haven’t had a chance to read Part 0, now would be a great time! Function Composition Function composition has a solid theoretical foundation in mathematics and computer science. In practical terms, it is a way to join a sequence of functions to create a more complex function. Let’s look at a simple example using Java functions. We have two functions, reverse and upper. Each accepts a String as input and produces a String as output. We can compose them using the built-in andThen method. The composite function is itself a Function<String, String>. If you run this, it will print ESREVER. Function<String, String> reverse = s -> new StringBuilder(s).reve...

Using OAuth 2.0 to Access Google APIs | How to generate oauth token ?

Image
All requests to the Google API must be authorized by an authenticated user. To access any of the google product you need oAuth token. Authorizing requests with OAuth 2.0: Setup your appliacation: Go to below link and setup your application, Once application is create get your OAuth client ID https://console.developers.google.com/apis/dashboard Get access Code: To get a code, you need to run a server. Install tomcat and run a simple dynamic application with only homepage. Let think application is running on http://localhost/ Create below url and open it on chrome:  https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/blogger&response_type=code&access_type=offline&redirect_uri=http://localhost&client_id=YourClientID Login With valid google account, Once you are Login successfully. It will redirect to localhost with code. http://localhost/?code=4/2AGswerwyro2KlmBXgXV8A73877482hsjdfhsj7AAtTERUCut7VD_Ty2gVlIlGMyD5xTxBFcYudif...

Spring Boot and Vaadin : Filtering rows in Vaadin Grid

Adding a text field for filtering: Start by adding a text field above the grid. Remember, MainView is a VerticalLayout, so you need to add the text field before the grid. MainView.java public class MainView extends VerticalLayout {   private ContactService contactService;   private Grid<Contact> grid = new Grid<>(Contact.class);   private TextField filterText = new TextField(); ①   public MainView(ContactService contactService) {   this.contactService = contactService;   addClassName("list-view");   setSizeFull();   configureFilter(); ②   configureGrid();   add(filterText, grid); ③   updateList();   }   private void configureFilter() {   filterText.setPlaceholder("Filter by name..."); ④   filterText.setClearButtonVisible(true); ⑤   filterText.setValueChangeMode(ValueChangeMode.LAZY); ⑥   filterText.addValueChangeListener(e -> updateList()); ⑦   }   // Grid...

Spring Boot and Vaadin : Creating a Spring Boot backend: database, JPA repositories, and services

Most real-life applications need to persist and retrieve data from a database. In this tutorial, we use an in-memory H2 database. You can easily adapt the configuration to use another database, like MySQL or Postgres. There are a fair number of classes to copy and paste to set up your backend. You can make your life easier by downloading a project with all the changes, if you prefer. The download link is at the end of this chapter. The code from the previous tutorial chapter can be found here, if you want to jump directly into this chapter. Installing the database dependencies We use Spring Data for data access. Under the hood, it uses Hibernate to map Java objects to database entities through the Java Persistence API. Spring Boot takes care of configuring all these tools for you. To add database dependencies: 1. In the <dependencies> tag in your pom.xml file, add the following dependencies for H2 and Spring Data: pom.xml <dependencies>   <!--all existing de...