|
Suraj Verma Oodles

Suraj Verma (Backend-Sr. Associate Consultant L2 - Development)

Experience:5+ yrs

Suraj is having more than 4+ years of experience as a Backend developer, he has a solid background in developing applications using Spring Boot and Microservices, with a strong focus on Java, multithreading, and various messaging protocols like MQTT, AMQP, and Kafka. He also has experience with popular databases like MySQL and Postgres, as well as distributed caching technologies like Redis. In addition, he has experience working with cloud-based services like AWS S3 and messaging platforms like RabbitMQ and has worked on projects such as Kairos, Genesis, Iron System, Rain Rock, and DCX.

Suraj Verma Oodles
Suraj Verma
(Sr. Associate Consultant L2 - Development)

Suraj is having more than 4+ years of experience as a Backend developer, he has a solid background in developing applications using Spring Boot and Microservices, with a strong focus on Java, multithreading, and various messaging protocols like MQTT, AMQP, and Kafka. He also has experience with popular databases like MySQL and Postgres, as well as distributed caching technologies like Redis. In addition, he has experience working with cloud-based services like AWS S3 and messaging platforms like RabbitMQ and has worked on projects such as Kairos, Genesis, Iron System, Rain Rock, and DCX.

LanguageLanguages

DotEnglish

Conversational

DotHindi

Fluent

Skills
Skills

DotGusto and ADP

60%

DotKafka

80%

DotTimefold

80%

DotPower BI

80%

DotJavascript

80%

DotDatabase Management

60%

DotPostgres

80%

DotSensors/IoT

80%

DotNo SQL/Mongo DB

80%

DotJava

80%

DotMachine Learning

80%

DotOptaplanner

80%

DotMQTT

60%

DotSpring Boot

80%

DotMySQL

80%

DotTax Compliance Automation

60%
ExpWork Experience / Trainings / Internship

Jun 2019-Present

Seniou Associate Consultant - Development

Gurgaon


Oodles Technologies

Gurgaon

Jun 2019-Present

EducationEducation

2015-2018

Dot

Maharaja Agrasen Institute Of Technology

B.TECH-Computer Science Engineering

Top Blog Posts
How To Get Metadata Of Video URL In Spring Boot Application

 

 

In this blog, we are going to create a simple spring boot project to extract metadata of the video URL. To extract the metadata of the video URL we are using Java 8 and Spring Boot 2.0 framework. To get the metadata of a video URL, We are using the Ws.Schild library of Java. In this library, we have many classes and services like multimedia object class, Multimedia info class, Through which we are able to get video URL metadata without downloading that video.

 

Step 1: Add Ws.Schild library in .pomx file :

<dependency>

   <groupId>ws.schild</groupId>

   <artifactId>jave-core</artifactId>

   <version>3.2.0</version>

</dependency>

<dependency>

   <groupId>ws.schild</groupId>

   <artifactId>jave-all-deps</artifactId>

   <version>3.2.0</version>

</dependency>

 

Step 2: Write Java code to extract metadata of a video URL :

package com.video;

 

import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import ws.schild.jave.EncoderException;

import ws.schild.jave.InputFormatException;

import ws.schild.jave.MultimediaObject;

import ws.schild.jave.info.MultimediaInfo;

import java.net.MalformedURLException;

import java.net.URL;

@SpringBootApplication

public class VideoApplication {

 

   public static void main(String[] args) throws MalformedURLException, EncoderException {

      SpringApplication.run(VideoApplication.class, args);

      MultimediaInfo multimediaInfo = getInfo("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");

      long minutes = (multimediaInfo.getDuration() / 1000) / 60;

      long seconds = (multimediaInfo.getDuration() / 1000) % 60;

      System.out.println(multimediaInfo.getDuration() + " Milliseconds = " + minutes + " minutes and "+ seconds + " seconds.");

 

   }

 

   public static MultimediaInfo getInfo(String videoUrl) throws MalformedURLException, EncoderException {

      URL url = new URL(videoUrl);

      try {

         MultimediaObject multimediaObject = new MultimediaObject(url);

         MultimediaInfo multimediaInfo = multimediaObject.getInfo();

         return multimediaInfo;

      }catch (InputFormatException e){

         e.printStackTrace();

         return null;

      }

   }

}

 

 

 

Step 3: Run the video application and check the output in the console :

2021-12-25 17:26:25.534  INFO 10693 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8094 (http) with context path ''

2021-12-25 17:26:25.536  INFO 10693 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed

2021-12-25 17:26:25.605  INFO 10693 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)

2021-12-25 17:26:25.737  INFO 10693 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references

2021-12-25 17:26:25.764  INFO 10693 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…

2021-12-25 17:26:32.841  INFO 10693 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!

2021-12-25 17:26:32.860  INFO 10693 --- [           main] com.nowcast.NowcastVideoApplication      : Started VideoApplication in 39.095 seconds (JVM running for 41.309)

653800 Milliseconds = 10 minutes and 53 seconds.

 

Summary :

In this blog, we have learned how to extract metadata from the video URL without downloading that video by using the WS.Schild java library.

 

At Oodles, we excel in building custom enterprise solutions for the diverse industries-specific needs of our clients. Our seasoned developers specialize in using open-source software platforms like Odoo, OFBiz, ERPNext, and Opentaps to build custom ERP applications from the ground up. To learn more about our custom ERP software development services, contact us at [email protected].

 

 

 




 

An Introduction To 9 New Features In Java 11

 

 

 

Java 11, free in Gregorian calendar month 2018, could be a major novelty of the Java language therein it's associate degree LTS version (Long Time support) that may be supported by Oracle till 2023 – and on the far side if we would like to profit from extended support. As a result, Java eleven seems an associate degree ineluctable version on the horizon of the approaching years. In this article, you will get yourself acquainted with a variety of nine new options contained within the JDK eleven.

 

1. SORT ILLATION FOR THE ARGUMENTS OF LAMBDA EXPRESSIONS

 This evolution could be a continuation of the variable sort illation side with Java ten. It's currently attainable to not expressly specify the kind of lambda parameters just by mistreatment the power unit keyword.

 

This can represent each a gain in clarity, brevity, and time once mistreatment bound sorts that area unit significant to write down. Of course, it was not obligatory to specify a sort for lambda parameters that the declaration is also correct.

 

What is the aim of sort illation during this case? It's helpful if we would like to annotate our parameters, that is not possible while not a sort declaration. 

 

2. SIMPLIFIED LAUNCH OF FILE PROGRAMS

Before Java 11, to launch the normal HelloWorld.java, we had the tendency to executed. From now on, with Java 11, one will directly launch applications contained during a single file.

 

This feature, additionally to JShell, enhances the tools offered to novice developers and additionally permits Oracle to upgrade Java to a lighter running language. This could illustrate its disposition to bring Java into the scripting language course within the future. Let’s wait and see!

 

3. EVOLUTION OF THE COMMUNICATION PROTOCOL SHOPPER  API 

For users of the communications protocol shopper API introduced by Java nine and updated by Java ten, bear in mind that its implementation has been nearly entirely revised by Java eleven. Oracle ensures that these revisions don't have an effect on the API from a high-level posture, whereas up a variety of technical points as a result of community feedback.

 

The implementation is currently fully asynchronous. the info flow will currently be simply half-track, from user requests to sockets. this could greatly cut back the complexness of the code and maximize the likelihood to utilize communications protocol / one.1 and communications protocol / a pair of.

 

The name of the API module and the package is currently java.net.http.

 

4. GENUS API'S ENHANCEMENT

 JDK eleven embeds a variety of latest categories and ways designed into already existing modules. The list below could be a non-exhaustive summary, lightness the additions seem} appear to be, in my opinion, the foremost necessary.

 

java.lang.String:

  • boolean isBlank (): Returns true if the string is empty or composed solely of whitespaces, otherwise false.
  • stream lines (): Returns a stream of lines extracted from the String.
  • string repeat (int): returns a String that's the first String concatenated with itself n times.
  • String strip (): returns a String freed from trailing and leading whitespaces. to place it merely, strip () is that the « Unicode-aware » version of trim () whose definition of whitespace dates back from the primary versions of Java.
  • String stripLeading (): Returns a String freed from its leading whitespaces.
  • String stripTrailing (): returns a String freed from trailing whitespaces.
     

java.util.function.Predicate:

 

  • Predicate not (Predicate). Returns a Predicate that is that the negation of the Predicate passed as associate degree argument. Example to filter a list:

 

java.lang.CharSequence:

  • int compare (CharSequence, CharSequence): compares 2 instances of CharSequence in writing order. Returns a negative, null, or positive worth.

 

java.lang.StringBuffer / java.lang.StrinBuilder:

  • Both categories currently have access to a replacement compareTo () technique that takes a StringBuffer / StringBuilder argument to associate degreed returns an int. The comparison logic follows identical writing order as for the new technique of the CharSequence category.

 

5. VISIBILITY MANAGEMENT OF NESTED CATEGORIES ATTRIBUTES

 Java permits multiple categories to be declared during a single supply file, like nested categories. From the user’s purpose of reading, however, they're usually thought of to belong to the « same category ». And, therefore, users expect them to share a typical access regime relative to their attributes.

 

To preserve these expectations, compilers should extend non-public attribute access to categories within the same package by adding access bridges. associate degree invocation of a personal member is compiled into a decision of a compiler-generated technique (getter) within the target category, that successively accesses the meant non-public member.

 

For example, within the case of a NestedClass category, nested within a NestingClass category, that has to access one in every one of the non-public attributes of the host class.

 

The compiler separates the 2 categories and creates a public access technique to nestingInt used by the NestedClass class.

 

These bridges subvert the encapsulation (private not has the precise same meaning) and might confuse users and tools. a proper notion of a gaggle of nesting category files (or nest), wherever nest partners share a typical access management mechanism, makes it attainable to directly acquire the specified lead to a less complicated, safer, and additional clear means.

 

To easily connect nested categories and hosts in JDK eleven, 2 new attributes are side to the classes: NestHost (new host) and NestMembers (nest members).

3 ways also are side to jave.lang.Class:

  • Class getNestHost ()
  • Class [] getNestMembers ()
  • boolean isNestmateof (Class)

 

6. DYNAMIC CLASS-FILE CONSTANTS

 This change is an associate degree extension of the category file format to support a replacement constants pool: CONSTANT_Dynamic.

 

It looks contradictory for a worth to be each constant and dynamic. However, you'll be able to primarily contemplate it as a final worth in Java. The worth of the constant isn't outlined at compile time (unlike alternative constants), however uses a bootstrap technique to work out the worth at the run time. The worth is thus dynamic, however since its worth is simply outlined once, it's additionally constant. This feature introduces a replacement category, java.lang.invoke.ConstantBootstraps, with 9 new ways.

 

7. THE LETTER EMPLOYEE

 The letter employee may be a very little uncommon within the sense that it doesn't collect waste! It'll portion memory, as needed, once instantiating new objects however won't recover any house occupied by unreferenced objects. This can be a very passive, brazenly experimental, « no-op » gigacycle per the second implementation. It's associate degree isolated amendment, doesn't {affect|have associate degree effect on} different GCs a makes lowest changes to the remainder of the JVM. This gigacycle per second is mainly helpful once doing performance or memory allocation tests as well as tasks with an awfully short lifecycle.

 

8. UNICODE 10 

The JDK eleven has taken note of the arrival of Unicode ten, and so supports the remake of this normal. This version includes eight,518 new symbols (from Bitcoin to emojis through ancient Chinese, Arabic, or Buddhist signs) that you just will use with Java eleven.

 

9.DELETED MODULES

The Java applied science and CORBA modules, once being deprecated in JAVA SE nine, were faraway from JAVA SE Platform and JDK eleven. The wedged modules are:

  • Corba
  • transaction
  • activation
  • xml.bind
  • xml.ws
  • xml.ws.annotation

 

JavaFX modules were additionally faraway from JDK eleven. These modules were a part of previous Oracle JDKs, however absent from the newest OpenJDKs. However, don't panic! These modules square measure continuously accessible outside of the JDK.

 

 

We provide end-to-end ERP development and integration services to streamline enterprise processes and enhance workflow efficiency. Our team uses open-source tools and ERP platforms to custom build feature-rich enterprise applications from the ground up to solve complex business problems.

 

 

 


 

Software Architecture of an Angular based Application

 

 

Here I’m about to justify the design of angular apps. Before {learn regarding|study|find out about} the angular framework we should always be aware of the design of the angular apps.

 

Angular apps design

 

Angular may be a framework styled to create single-page applications (SPAs) and most of its design is targeted towards doing that in a good manner.

 

Single-page application (or SPA) area unit applications that area unit accessed via applications program like different websites however provide a lot of dynamic interactions resembling native mobile and desktop apps. the foremost notable distinction between an everyday web site and SPA is that the reduced quantity of page refreshes.

 

Typically, ninety-five p.c of SPA code runs within the browser; the remainder works within the server once the user wants new information or should perform secured operations like authentication.

 

As a result, the method of page rendering happens totally on the client-side.

 

Angular Modules:

 

Modules facilitate organize associate degree applications into cohesive practicality blocks by wrapping parts, pipes, directives, and services. they're simply all regarding developer engineering.

 

Angular applications area unit standard. each Angular application has a minimum of one module— the foundation module, conventionally named AppModule. the foundation module is often the sole module during a little application, however, most apps have more modules. because the developer, it's up to you to make a decision a way to use the modules. Typically, you map major practicality or a feature to a module. maybe you've got four major areas in your system. each can have its own module added to the foundation module, for a complete of 5 modules.

 

Any angular module may be a category with the @NgModule decorator. Decorators area unit functions that modify JavaScript categories. they're primarily used for attaching information to categories so it is aware of the configuration of these categories and the way they ought to work. The @NgModule decorator properties that describe the module are:

  • declarations: The categories that belong to the present module and area unit associated with views. There area unit 3 categories in Angular which will contain views: parts, directives, and pipes.
  • exports: The categories that ought to be accessible to different modules parts.
  • imports: Modules whose categories area unit required by the parts of this module.
  • providers: Services gift in one in every one of the modules that area unit about to be utilized in the opposite modules or parts. Once a service is enclosed within the suppliers, it becomes accessible altogether components of that application.
  • bootstrap: the foundation element is that the main read of the appliance. solely the foundation module has this property and it indicates the element that is gonna be bootstrapped.
  • Entry components: associate degree entry element is any element that Angular hundreds peremptorily, (which means that you are not referencing it within the template), by type.

Angular Components:

 

Components area unit the foremost basic building block of associate degree UI and Angular applications. An element controls one or a lot of sections on the screen (what we tend to decision views). as an example, during this example, we've parts like AppComponent (the bootstrapped component), CategoriesComponent, CategoryQuestionsComponent, QuestionAnswersComponent, etc.

 

An element is self-contained and represents a reusable piece of UI that's typically deep-seated by 3 vital things:

 

A piece of markup language code that's called the read

 

 

A class that encapsulates all obtainable information associate degreed interactions to it read through an API of properties and ways architectured by Angular. Here's wherever we tend to outline the appliance logic 

And the same markup language component conjointly called the selector.

Using the Angular @Component decorator we offer further information that determines however the element ought to be processed, instantiated, and used at runtime. as an example we tend to set the markup language template associated with the reading, then, we tend to set the markup language selector that we tend to area unit about to use for that element, we tend to set stylesheets for that element.

 

The element passes information to the read employing a method known as information Binding. this can be done by Binding the DOM components to element properties. Binding is often accustomed to show property values to the user, modification component designs, reply to associate degree user event, etc.

 

An element should belong to associate degree NgModule so as for it to be usable by another element or application. To specify that an element may be a member of associate degree NgModule, you ought to list it within the declarations property of that NgModule.

 

One facet note on the importance of the part from some extent of package design principles: It's super vital and suggested to own separate parts, and here's why. Imagine we've 2 totally different UI blocks within the same element and within the same file. At the start, they'll be little however every may grow. we tend to area unit absolute to receive new necessities for one and not the opposite. Nonetheless, each modification puts each part in danger and doubles the testing burden with no edges. If we tend to had to apply a number of those UI blocks elsewhere in our app, the opposite one would be affixed on.

 

That situation violates the one Responsibility Principle. you will suppose this can be solely a tutorial, however, we'd like to try and do things right — particularly if doing them right is simple and that we learn the way to create Angular apps within the method.

 

Angular encourages this principle by having every patch of the page controlled with its own element.

 

A typical Angular application seems like a tree of parts. the subsequent diagram illustrates this idea. Note that the modal parts area unit on the facet of the parent element as a result of their imperative parts that don't seem to be declared on the element markup language template.

 

Angular app tree of parts

 

Angular building blocks: Templates:

 

Templates area unit accustomed outline an element read. A template seems like regular markup language, however, it conjointly has some variations. Code like *ngFor, }, (click), and [hero] uses Angular templet syntax to reinforce markup language markup capabilities. Templates can even embrace custom parts like within the sort of non-regular markup language tags. These parts combine seamlessly with native markup language within the same layouts.

Angular building blocks: Services

 

Almost something is a service, any value, function, or feature that your application desires. Service is usually a category with a slender, well-defined purpose. It ought to do one thing specifically and screw well. the most purpose of Angular Services is sharing resources across parts.

 

Take element categories, they ought to be lean, component's job is to modify the user expertise (mediate between the read and therefore the application logic) and zilch a lot of. they do not fetch information from the server, validate user input, or log on to the console. They delegate such tasks and everything nontrivial to services.

 

Services square measure basic to any Angular application, and parts square measure huge customers of services as they assist them being lean.

 

The situation we've simply delineated includes a heap to try and do with the Separation of considerations principle. Angular does not enforce these principles, however, it helps you follow these principles by creating it straightforward to structure your application logic into services and create those services accessible to parts through dependency injection.

 

In our example app, we've 3 services: AnswersService, QuestionsService, CategoriesService. Every one of them has solely the functions associated with them. during this specific tutorial, we'll solely specialize in CategoriesService and within the following components, we'll discuss the others.

 

CategoriesService has the subsequent methods:

 

//gets all the question classes from a neighborhood json

getCategories()come this.http.get("./assets/categories.json")

.map((res:any) => res.json())

.toPromise();

}

 

//finds a selected class by slug

getCategoryBySlug(slug: string)come this.getCategories()

.then(data =>come information.categories.find((category) => come class.slug == slug;

});

})

}

 

Angular building blocks: alternative resources

 

External resources like Databases, APIs, etc, square measure basic as they're going to modify our app to move with the surface world.

 

There's far more to hide regarding the essential building blocks of Angular applications like Dependency Injection, information Binding, Directives, etc. you'll notice these and far a lot of info in our future post regarding "Angular: the training path".

 

Now, let's go deeper and map the project structure to the app's design thus we are able to perceive higher however all the items move with one another.

 

 We are an ERP software development company that builds performance-driven ERP solutions to overcome complex business challenges. Our ERP application development services enable organizations to efficiently managing their mission-critical business processes and boost productivity. For more information, drop us a line at [email protected]

 

 




 

Deep Copy And Shallow Copy In Java Script

 

Introduction:

 The Lodash library in javascript allows developers to copy/clone objects by value through methods like clone( ), cloneWith( ), and cloneDeepWith( ). In this article, we’ll explain how to perform deep copy of objects and arrays in javascript lodash’s cloneDeep method. We’ll also learn about the types of cloning methods in this blog, starting with the number of types of cloning in javascript. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable whereas a shallow copy means that certain (sub-)values are still connected to the original variable.

 

Types Of cloning : -

 

Deep Copy

 

The Deep copy method copies all fields and makes copies of dynamically allocated memory pointed to the fields. Deep copy method is manifested when an object is copied along with the objects to which it refers.

Let's take an example to understand the deep cloning.

Deep copy makes a copy of all the members of A, allocates different memory locations for B, and then assigns the copied members to B to achieve deep copy. In this way, if A vanishes B is still valid in the memory.

 

Shallow Copy

 

The shallow copy is a bit-wise copy of an object. In the shallow copy, a new object with an exact copy of the values in the original object is created. If any of the fields of the object are references to other objects, just the reference addresses are copied, that is, only the memory address is copied.

Let's take an example to understand the shallow cloning.

Shallow Copy makes a copy of the reference of A into B. Think about it as a copy of A’s Address. So, the addresses of A and B will be the same, i.e. they will be pointing to the same memory location.

 

Difference between deep copy and shallow copy:-

 

Here we are trying  to understand the difference between deep copy and shallow copy using an example:

Cloning is used where you know that they both are totally the same, but yet different as value is stored as two different locations in the memory space.

Consider this example:

 

var employeeDetailsOriginal = {  name: 'Suraj', age: 24, Profession: 'Software Engineer' };

 

Let’s say you want to create a duplicate of this, so that even if you change the values, you can always return to the original.

I can do this:

 

var employeeDetailsDuplicate = employeeDetailsOriginal; //Shallow copy!

 

If we change a value:

 

employeeDetailsDuplicate.name = 'NameChanged';

 

Above statement change name from employeeDetailsOriginal, since we have a shallow copy or a reference to var employeeDetailsOriginal. This means you’re losing the original data as well.

But, creating a new variable by using the properties from the original employeeDetailsOriginal variable, you can create a deep copy.

 

var employeeDetailsDuplicate = {Name: employeeDetailsOriginal.name, Age: employeeDetailsOriginal.age, Profession:

employeeDetailsOriginal.Profession}; //Deep copy!

 

And now if you change employeeDetailsDuplicate.name, it will only affect employeeDetailsDuplicate and not employeeDetailsOriginal

 

Summary : In this blog, we have learned about the deep cloning and shallow cloning method of the javascript as well as the difference between them.

 

The most widely used programming language in web and mobile applications, javaScript is a light-weight clientside scripting language that our developers hold expertise in. We are a Java development company that enables enterprises to streamline operations and drive returns, using next-gen technologies, with our development services. Our services include developing applications for all your ERP needs from CRM, WFM, and HRM to eCommerce, accounting, and wealth management software. We use an extensive tech stack including Javascript, Node.js, angular and more to develop end-to-end customized software for your enterprise. Get in touch with our experts to know more about how you can implement these technologies into your business.

 

 


 

How To Use Pipes In Angular

How To Use Pipes In Angular

 

Introduction :

In this blog, we are going to explain pipes in the Angular. In Angular, a pipe is a way through which we can get the desired output. In other words, a pipe takes data as input and transforms it into the desired output. We will also learn the types of pipes in Angular.

 

To transform data we are using the "|" character. The syntax of transforming the data are given below:-

 

{{ Welcome to Angular 4 | lowercase}}

 

Pipe takes integers, strings, arrays, and date as input, separated with ‘|’ to be converted in the required format and display the same in the browser.

Here we are creating an exaemple to define a pipe. In this exemple we are going to display the given text to uppercase. This can be done using pipes as follows :-

app.component.ts

import { Component } from '@angular/core';

@Component({

   selector: 'app-root',

   templateUrl: './app.component.html',

   styleUrls: ['./app.component.css']

})

export class AppComponent {

   title = 'Pipes In Angular';

}

The line of code goes into the app.component.html file are given below :-

<b>{{title | uppercase}}</b><br/>

<b>{{title | lowercase}}</b>

 

The output shown on the browser is given below:

 

PIPES IN ANGULAR

pipes in angular

 

Angular provides us some built-in pipes. The pipes are listed given below:-

 

  • Lowercasepipe
  • Uppercasepipe
  • Datepipe
  • Currencypipe
  • Jsonpipe
  • Percentpipe
  • Decimalpipe
  • Slicepipe

 

We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work.

The line of code will help us define the required variables in app.component.ts file are given below :-

import { Component } from '@angular/core';

@Component({

   selector: 'app-root',

   templateUrl: './app.component.html',

   styleUrls: ['./app.component.css']

})

export class AppComponent {

   title = 'Pipes In Angular';

   todaydate = new Date();

   jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};

   months = ["Jan", "Feb", "Mar", "April", "May", "Jun",

             "July", "Aug", "Sept", "Oct", "Nov", "Dec"];

}

 

 The pipes in the app.component.html file.

 

<div style = "width:100%;">

   <div style = "width:40%;float:left;border:solid 1px black;">

      <h1>Uppercase Pipe</h1>

      <b>{{title | uppercase}}</b><br/>

      

      <h1>Lowercase Pipe</h1>

      <b>{{title | lowercase}}</b>

      

      <h1>Currency Pipe</h1>

      <b>{{1589.23 | currency:"USD"}}</b><br/>

      <b>{{1589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.

      

      <h1>Date pipe</h1>

      <b>{{todaydate | date:'d/M/y'}}</b><br/>

      <b>{{todaydate | date:'shortTime'}}</b>

      

      <h1>Decimal Pipe</h1>

      <b>{{ 254.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.

   </div>

   

   <div style = "width:40%;float:left;border:solid 1px black;">

      <h1>Json Pipe</h1>

      <b>{{ jsonval | json }}</b>

      <h1>Percent Pipe</h1>

      <b>{{00.54455 | percent}}</b>

      <h1>Slice Pipe</h1>

      <b>{{months | slice:2:6}}</b> 

      // here 2 and 6 refers to the start and the end index

   </div>

</div>

 

OUTPUT :-

 

 

Summery:

In this blog we have learned only basic uses of the pipes in angular using some pipes like lowercase, uppercase, datepipe, currency pipe, decimal pipe, etc. to transform input date to desired output data. 

 

We are an ERP development company that enables enterprises to streamline operations and drive returns, using next-gen technologies, with our development services. Our services include developing applications for all your ERP needs from CRM, WFM, and HRM to eCommerce, accounting, and wealth management software. We use an extensive tech stack including Angular, Java 8, and Spring to develop end to end customized software for your enterprise. Get in touch with our experts to know more about how you can implement these technologies into your business.

 

 

 

 

 

Optional Feature Of Java 8

 

Introduction:

In this blog we are going to observe the use of ‘optional’ feature in java 8. Optional feature of java 8 is a container object used to contain not-null objects. This class has many utility functions to facilitate code that handles values as available or unavailable instead of checking null values. In this blog we will learn about the prevention of null pointer using the optional feature of the java 8.

 

Why should we use of optional feature of java 8?

 

Do you ever get NullPointerException as a Java developer? If you are an experienced Java developer, so you may have got Null Pointer Exception at some point of time while  developing a software.

You may agree that NullPointerException is a pain for both novice and expert core Java developers. You have to put a lot of defensive code to avoid NullPointerException.

So,To avoid null pointer and defensive code we can use optional feature of the java 8.

 

How Can I avoid null pointer exception using optional feature of the java 8?

 

Let’s understand with the help of an example:

package org.arpit.java2blog;

 

public class Employee {

    private String name;

    private int age;

    

    public Employee(String name, int age) {

        super();

        this.name = name;

        this.age = age;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

}

Create a main class named “JavaFindEmployeeMain.java”

package org.arpit.java2blog;

 

import java.util.ArrayList;

import java.util.List;

 

public class JavaFindEmployeeMain {

    

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Employee employee = findEmployee(employeeList,"Suraj");

        System.out.println("Employee name: "+employee.getName());

    }

    

    public static Employee findEmployee(List<Employee> employeeList,String name)

    {

        for(Employee e:employeeList)

        {

            if(e.getName().equalsIgnoreCase(name))

            {

                return e;

            }

        }

        return null;

    }

    public static List<Employee> createEmployeeList()

    {

        List<Employee> employeeList=new ArrayList<>();

        

        Employee e1=new Employee("amit",21);

        Employee e2=new Employee("jai",22);

        Employee e3=new Employee("karan",31);

        Employee e4=new Employee("arjun",18);

        Employee e5=new Employee("anil",26);

        

        employeeList.add(e1);

        employeeList.add(e2);

        employeeList.add(e3);

        employeeList.add(e4);

        employeeList.add(e5);

        

        return employeeList;

        

    }

}

 

Output:

Exception in thread “main” java.lang.NullPointerException

at org.arpit.java2blog.JavaOptionalMain.main(JavaOptionalMain.java:12)

 

As you can see, “Suraj” is not present in employeeList, that’s why we are getting NullPointerException here.

Do you see the issue here? As you see, we forgot to check null when we tried to find employee in the list. This occurs more often when you call library function and it returns null and you forget to check it.

So, to avoid the null pointer and defensive code we can use optional feature which are shown in the below figure.

package org.arpit.java2blog;

 

import java.util.ArrayList;

import java.util.List;

import java.util.Optional;

 

public class JavaOptionalMain {

    

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt = findEmployee(employeeList,"Suraj");

        if(employeeOpt.isPresent())

        {

            Employee employee = employeeOpt.get();

            System.out.println("Employee name: "+employee.getName());

        }

        else

        {

            System.out.println("There is no employee with name Suraj");

        }

    }

    

    public static Optional<Employee> findEmployee(List<Employee> employeeList,String name)

    {

        for(Employee e:employeeList)

        {

            if(e.getName().equalsIgnoreCase(name))

            {

                return Optional.of(e);

            }

        }

return Optional.empty();

    }

    public static List<Employee> createEmployeeList()

    {

        List<Employee> employeeList=new ArrayList<>();

        

        Employee e1=new Employee("amit",21);

        Employee e2=new Employee("arjun",22);

        Employee e3=new Employee("anil",31);

        Employee e4=new Employee("jai",18);

        Employee e5=new Employee("karan",26);

        

        employeeList.add(e1);

        employeeList.add(e2);

        employeeList.add(e3);

        employeeList.add(e4);

        employeeList.add(e5);

        

        return employeeList;

    }

}

 

output:

There is no employee with name Suraj

 

You think that you could have handled null in Java Find Employee Main as well but when you return Optional from method, it means that missing value can be expected from method.

 

Ways to create Optional Feature Of The Java 8:

 

Empty Optional:

 

We can create empty optional object using static factory method empty

Optional<Employee> optCar = Optional.empty();

 

Optional from a non-null value:

We can create Optional from non-null value using static factory method of

 

Optional<Employee> optCar = Optional.of(employee);

 

If employee is null then above function will throw NullPointerException.

Optional from null or non-null value:

We can create Optional from null or non null value using static factory method ofNullable

 

Optional<Employee> optCar = Optional.ofNullable(employee);

 

How we can get value from Optional:

We can use get() method to retrieve value from Optional but it is least safe. If value is not present then it will throw NoSuchElementException,so you need to make sure you call isPresent() method before you call get() method.

 

Check value in Optional:

 

We can check if there is a value wrapped inside Optional using isPresent method.

 

    public static void main(String[] args)

    {

            List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt = findEmployee(employeeList,"Suraj");

        if(employeeOpt.isPresent())

        {

            Employee employee = employeeOpt.get();

            System.out.println("Employee name: "+employee.getName());

        }

        else

        {

            System.out.println("There is no employee with name Suraj");

        }

    }

 

 

Conditional action in Optional:

 

We can use "ifPresent" method to execute action if value is present in Optional.

Change main method in JavaOptionalMain as below

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt1 = findEmployee(employeeList,"Suraj");

        Optional<Employee> employeeOpt2 = findEmployee(employeeList,"Amit");

        

        employeeOpt1.ifPresent((employee)->System.out.println("Employee name: "+employee.getName()+" found in list"));

        employeeOpt2.ifPresent((employee)->System.out.println("Employee name: "+employee.getName()+" found in list"));

 

    }

 

Output:

Employee name: Suraj

Employee name: Amit found in list

As you can see here, if employee name is present in the list, then only we can print the employee name else it does not perform any action.

Default value in Optional using orElse:

We can return default value in case there is no value in Optional using orElse function.

Change main method in JavaOptionalMain as below

 

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt = findEmployee(employeeList,"Suraj");

        Employee employee1 = employeeOpt.orElse(new Employee("Amit",0));

        System.out.println("Employee name: "+employee1.getName());

        

        Optional<Employee> employeeOpt2 = findEmployee(employeeList,"Jai");

        Employee employee2= employeeOpt2.orElse(new Employee("Dummy",0));

        System.out.println("Employee name: "+employee2.getName());

        

    }

 

Output:

Employee name: Amit

Employee name: Jai

 

Default value in Optional using orElseGet

Here "orElseGet" is a lazy counter part of orElse which takes supplier as parameter and will be called only if value is not present in Optional.

Change main method in JavaOptionalMain as below

 

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt = findEmployee(employeeList,"Suraj");

        Employee employee1 = employeeOpt.orElseGet(()->new Employee("Amit",0));

        System.out.println("Employee name: "+employee1.getName());

        

        Optional<Employee> employeeOpt2 = findEmployee(employeeList,"Amit");

        Employee employee2 = employeeOpt2.orElseGet(()->new Employee("Jai",0));

        System.out.println("Employee name: "+employee2.getName());

        

    }

 

Output:

Employee name: Amit

Employee name: Jai

 

Throwing exception from Optional

We can use orElseThrow to throw exception in case Optional is empty. It's a similar to get() method but in this case, we can choose to throw any Exception rather than "NoSuchMethodException".

Change main method in JavaOptionalMain as below

 

    public static void main(String[] args)

    {

        List<Employee> employeeList = createEmployeeList();

        Optional<Employee> employeeOpt = findEmployee(employeeList,"Adam");

        Employee employee = employeeOpt.orElseThrow(() -> new RuntimeException("Employee not found"));

        System.out.println("Employee name: "+employee.getName());

        

        Optional<Employee> employeeOpt2 = findEmployee(employeeList,"Martin");

        Employee employee1 = employeeOpt2.orElseThrow(() -> new RuntimeException("Employee not found"));

        System.out.println("Employee name: "+employee1.getName());

        

    }

Summary:

In this blog we have learned about the optional feature of java 8 and where we can use this feature. We also learned the way of the create optional and how to avoid null pointer exception and defensive code to check null pointer.

 

The most widely used programming language in web and mobile applications, java 8 is a light-weight clientside scripting language that our developers hold expertise in. Are you looking for development services to design web applications and build backend for your server? Look no further! We are an ERP Development company with expertise in developing customized software solutions for our clients. Our custom development services enable businesses to automate, plan, collaborate, and execute their operations methodically.


 

 

 

Deploying a Simple Contract on Hedera Hashgraph Network with Java

INTRODUCTION:

Hashgraph is a distributed ledger technology. It uses the DAG (Directed Acyclic Graph). It has already been used in machine learning, compilers, and statistics. In this case, the data is not stored in blocks, but distributed by events. DAG system is also used to solve the Byzantine General Problems. As a rule, each project developing a distributed registry has its own way of synchronizing nodes, i.e their own consensus algorithm.

 

Hashgraph Consensus Algorithm:

Each validator collects its transactions, randomly chooses the other participant, and transfers the information about the transactions to the participant, as well as the information that the other nodes have informed when they connected to him.

It has simple functionality. Tthe validator “listens”, receives all messages that are coming to him, and afterwards, randomly chooses the other participant and sends him all the transactions along with his own. Hashgraph ensure that with steps' final number (rounds of protocol's work), the same state is achieved by all nodes. Its protocol is fast and easily scalable. In the network, there is no leader. As long as 2/3 honest nodes remain, the protocol secures the high level of security. For nodes to be synchronized and to achieve the agreement between them, there is also an exchange process going between the other participants of the network randomly.

 

Registration (KYC) :

First, you have to register on portal and pass the identity proof. It is important. Registration at the portal is possible as part of the testing phase. Here are instructions for registration and the KYC process. link.

 

Network selection:

First of all you have to choose network, so that the smart contracts functionality is available at the moment only in testnet. Now, let's choose the testnet.

 

Also Read | A Comprehensive Guide to MetaMask Wallet Setup and Usage

Network access

The portal will request that you provide an access code to the network, which can be received via e-mail, by leaving the request at the website.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Upon entering the code, Hedera returns the following information:

 

 

 

This data will needed in the future.

 

Public and private keys:

 

First of all you have to add dependency in you pom.xml file is given below:

<dependency>   <groupId>com.hedera.hashgraph</groupId>   <artifactId>sdk</artifactId>   <version>0.7.0</version> </dependency>

To generate public and private Keys you have to the write of some code in java which is given below:

Ed25519PrivateKey newKey = Ed25519PrivateKey.generate(); Ed25519PublicKey newPublicKey = newKey.getPublicKey();

Deploying of smart contract

To deploy a smart contract, first of all you have to compile your solidity code and get the bin file of that smart contract and your bin  file contain some byte code. You can get bin file of your smart contract with the use of command  and the exemple of byte code which is given below:-

 

solc SimpleToken.sol --allow-paths "." --bin --abi --optimize -o /home/suraj/Downloads/hedera1/

 

Byte code: 302e020100300506032b657004220420d396c78d1d4c31a9f3f5c16eb81eb542803c89beddf30e1e1a583dd2db433704

HelperClass:

package com.suraj.phicoin.service; import com.hedera.hashgraph.sdk.Client; import com.hedera.hashgraph.sdk.account.AccountId; import com.hedera.hashgraph.sdk.crypto.ed25519.Ed25519PrivateKey; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.Objects; @Service public class HederaClient {    @Value("${OPERATOR_ID}")    private String operatorId;    @Value("${OPERATOR_KEY}")    private String operatorKey;    @Value("${Node_Address_1}")    private String nodeAddress1;    @Value("${Node_Address_2}")    private String nodeAddress2;    @Value("${Node_Address_3}")    private String nodeAddress3;    @Value("${Node_Address_4}")    private String nodeAddress4;    @Value("${Node_Id_1}")    private String node1;    @Value("${Node_Id_2}")    private String node2;    @Value("${Node_Id_3}")    private String node3;    @Value("${Node_Id_4}")    private String node4;    public Client hederaClientSetup() {        AccountId operatorId1 = AccountId.fromString(operatorId);        AccountId node_1 = AccountId.fromString(node1);        AccountId node_2 = AccountId.fromString(node2);        AccountId node_3 = AccountId.fromString(node3);        AccountId node_4 = AccountId.fromString(node4);        Map<AccountId,String> nodeAddressMap = new HashMap<>();        nodeAddressMap.put(node_1,nodeAddress1);        nodeAddressMap.put(node_2,nodeAddress2);        nodeAddressMap.put(node_3,nodeAddress3);        nodeAddressMap.put(node_4,nodeAddress4);        System.out.println(nodeAddressMap);        Client hederaClient = new Client(nodeAddressMap);        Ed25519PrivateKey operatorKey1 = Ed25519PrivateKey.fromString(operatorKey);        hederaClient.setOperator(operatorId1,operatorKey1);        return hederaClient;    }    public String getOpreatorKey() {        return operatorKey;    }    public String getOperatorId() {        return operatorId;    } } package com.suraj.phicoin.service; import com.hedera.hashgraph.sdk.*; import com.hedera.hashgraph.sdk.contract.ContractCallQuery; import com.hedera.hashgraph.sdk.contract.ContractCreateTransaction; import com.hedera.hashgraph.sdk.contract.ContractDeleteTransaction; import com.hedera.hashgraph.sdk.contract.ContractId; import com.hedera.hashgraph.sdk.crypto.ed25519.Ed25519PrivateKey; import com.hedera.hashgraph.sdk.file.FileCreateTransaction; import com.hedera.hashgraph.sdk.file.FileId; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import java.io.IOException; import java.time.Duration; import java.time.Instant; public class CreateSimpleContract {    private CreateSimpleContract() { }    public static void main(String[] args) throws HederaException, IOException {        HederaClient hederaClient = new HederaClient();        String byteCodeHex = "608060405234801561001057600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506101cb806100606000396000f3fe608060405260043610610046576000357c01000000000000000000000000000000000000000000000000000000009004806341c0e1b51461004b578063cfae321714610062575b600080fd5b34801561005757600080fd5b506100606100f2565b005b34801561006e57600080fd5b50610077610162565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b757808201518184015260208101905061009c565b50505050905090810190601f1680156100e45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610160573373ffffffffffffffffffffffffffffffffffffffff16ff5b565b60606040805190810160405280600d81526020017f48656c6c6f2c20776f726c64210000000000000000000000000000000000000081525090509056fea165627a7a72305820ae96fb3af7cde9c0abfe365272441894ab717f816f07f41f07b1cbede54e256e0029";        byte[] byteCode = byteCodeHex.getBytes();        Ed25519PrivateKey operatorKey = Ed25519PrivateKey.fromString("302e020100300506032b657004220420d396c78d1d4c31a9f3f5c16eb81eb542803c89beddf30e1e1a583dd2db433704");        Client client = hederaClient.hederaClientSetup();        // create the contract's bytecode file        FileCreateTransaction fileTx = new FileCreateTransaction(client).setExpirationTime(                Instant.now()                        .plus(Duration.ofSeconds(3600)))                // Use the same key as the operator to "own" this file                .addKey(operatorKey.getPublicKey())                .setContents(byteCode);        TransactionReceipt fileReceipt = fileTx.executeForReceipt();        FileId newFileId = fileReceipt.getFileId();        System.out.println("contract bytecode file: " + newFileId);        // create the contract itself        ContractCreateTransaction contractTx = new ContractCreateTransaction(client).setAutoRenewPeriod(Duration.ofHours(1))                .setGas(217000)                .setBytecodeFile(newFileId)                // set an admin key so we can delete the contract later                .setAdminKey(operatorKey.getPublicKey());        TransactionReceipt contractReceipt = contractTx.executeForReceipt();        System.out.println(contractReceipt.toProto());        ContractId newContractId = contractReceipt.getContractId();        System.out.println("new contract ID: " + newContractId);        FunctionResult contractCallResult = new ContractCallQuery(client).setGas(30000)                .setContractId(newContractId)                .setFunctionParameters(CallParams.function("greet"))                .execute();        if (contractCallResult.getErrorMessage() != null) {            System.out.println("error calling contract: " + contractCallResult.getErrorMessage());            return;        }        String message = contractCallResult.getString();        System.out.println("contract message: " + message);        // now delete the contract        TransactionReceipt contractDeleteResult = new ContractDeleteTransaction(client)                .setContractId(newContractId)                .executeForReceipt();        if (contractDeleteResult.getStatus() != ResponseCodeEnum.SUCCESS) {            System.out.println("error deleting contract: " + contractDeleteResult.getStatus());            return;        }        System.out.println("Contract successfully deleted");    } }

 

Also Read | A Comprehensive Guide to Fungible Token Development on Hedera

Category: Blockchain
Banner

Don't just hire talent,
But build your dream team

Our experience in providing the best talents in accordance with diverse industry demands sets us apart from the rest. Hire a dedicated team of experts to build & scale your project, achieve delivery excellence, and maximize your returns. Rest assured, we will help you start and launch your project, your way – with full trust and transparency!