Convert currentTimeMillis to a datetime in JAVA(Spring Boot)

Spring Boot

In this tutorial I’ll show how to save Time Stamp in Database in currentTimeMillis and retrieve in Spring Boot

Want precise time for some purpose? Normally, we can save Time Stamp in Database but what if the data need to be converted into several formats?

Let’s say we need to save “2019-6-27 00:59:59” and then convert it to several formats like ’27/2019/6 00:59:59′ and ’20-JUN-1990 08:03:00′. Though “2019-6-27 00:59:59” can be converted but that’s a little bit tough. The ideal solution is to save the data in millisecond format. In millisecond format “2019-6-27 00:59:59” would be “1564167599000”

I assume you already have the datetime picker data in controller, here’s the conversion code:

String expireTime = model.attribute; //your model attribute or request parameter name
Date date = formatter.parse(expireTime);
Timestamp timestamp = new Timestamp(date.getTime());
String expireTime2 = String.valueOf(timestamp.getTime());
//That's it! We've converted '2019-6-27 00:59:59' to '1564167599000'
//Add your save logic

Now the reading part. User can’t read ‘1564167599000’, right? Let’s convert this to readable format:

String convertedExpireTime = "1564167599000";
//Create a calendar instance
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(convertedExpireTime));
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
int mMin = calendar.get(Calendar.MINUTE);
int mSec = calendar.get(Calendar.SECOND);
String readableFormat = mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":"+ mMin + ":"+ mSec; // The value is now converted to 2019-6-27 0:59:59
//Add some logic

That’s all! We’re done!

If you’ve any confusion please let me know 🙂

How to query data out of the box using Spring data JPA by both Sort and Pageable

Spring Boot

Developing REST API? Clients wants both sort & pagination?

That’s quite simple btw!

Since last few hours was trying to add this simple feature my Spring Boot project. In my project pagination was done using pageable

In this tutorial I’m gonna show how to achieve this.

Let’s copy the code from below:

public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       return models;
   }
//Model = Your Model where you want to implement this feature. 

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

spring boot thymeleaf bootstrap 4

Let’s say you want to display multiple table contents in Spring Boot project using Thymeleaf, JPA Entity and Model.

In my project I have mapped a relationship between the two entities I need to retrieve data from and am wondering how to display data from the two tables on list page. I’ve ‘category’ table and ‘product’ table like below:

Spring Boot, Thymeleaf Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

And in my controller I’ve list of both category and product in respective model. Here is the snippet:

model.addAttribute("products", productService.findAll());
model.addAttribute("categories", categoryService.findAll());

So, I’ve all the required data in the model and I can access them from Thymeleaf. Let’s copy the table code from below (N.B: I’ve used bootstrap table):

<table class="table table-striped table-bordered table-responsive" role="grid">
   <thead>
      <th>Category</th>
      <th>Product</th>
   </thead>
   <tbody>
      <tr role="row" class="odd" th:each="product:${products}">
         <td>
            <p th:each="category : ${categories}" th:if="(${category.id} == ${product.id})" th:text="${category.name}"></p>
         </td>
         <td th:text="${product.name}">
      </tr>
   </tbody>
</table>

It’ll produce something like this:

Spring Boot, Thymeleaf: Display data from two JPA entity tables on same page

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

Thymeleaf select required not working?

thymeleaf

Since last few days trying to add select “required” attribute in my Thymeleaf project.  Neither of these works in Thymeleaf:

  • <select required=”required”>
  • <select required=’required’>
  • <select required=required>
  • <select required=””>
  • <select required=”>
  • <select required>

In this tutorial I’m gonna show how to achieve this.

Let’s copy the code from below:

<select th:name="someName" class="form-control" id="someID" th:required="true">
    <option value="">Select Category</option>
    <option th:each="model: ${someModel}" th:value="${model.id}"
            th:text="${model.Title}"></option>
</select>

Please note that, first/default option value must be set to “” if you put “0” it won’t work!

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

Bootstrap Dynamic Modal with Spring Boot and Thymeleaf

spring boot thymeleaf bootstrap 4

Let’s say you want to dynamically create modal popup in your Spring Boot project using Twitter Bootstrap 4 to show the user a ‘warning popup’ before deleting a data or edit the contents on the fly in same page. Not to mention I’ve used Thymeleaf as my template engine.

In this tutorial I’m gonna show how to achieve this.

I assume you have already included required Bootstrap resources and necessary jQuery library in your project and are ready to implement modal popup. Let’s copy the modal code from below:

<div class="modal modal-warning fade in" id="myModal">
 <div class="modal-dialog">
 <div class="modal-content">
 <div class="modal-header">
 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
 <span aria-hidden="true">×</span></button>
 <h5 class="modal-title">Delete User</h5>
 </div>
 <div class="modal-body">
 <h3>Are you sure want to delete this user?</h3>
 </div>
 <div class="modal-footer">
 <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
 <a type="button" class="btn btn-danger"><i class="fa fa-check"></i>&nbsp;Yes</a>
 </div>
 </div>
 </div>
 </div>

It’ll produce something like this:

Bootstrap Dynamic Modal with Spring Boot and Thymeleaf

Now, the next step actually the final step. Make the modal dynamically generate for all the data in table.

I’ve some data in the table like below now I want to delete a user but before that I want that modal to generate dynamically for all data.

Bootstrap Table in Spring boot

On the ‘Red’ delete button the popup will generate.

<a data-toggle="modal" data-target="#modal-warning" th:attr="data-target='#modal-warning'+${user.id }"><span class="glyphicon glyphicon-trash"></span></a>

Here “${user.id}” is my thymeleaf object.

Now, let’s make the modal dynamic with the id:

<div class="modal modal-warning fade in" th:id="modal-warning+${user.id }" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h5 class="modal-title">Delete User</h5>
            </div>
            <div class="modal-body">
                <h3>Are you sure want to delete this user?</h3>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
                <a type="button" class="btn btn-outline" th:href="@{/user/delete/{id}(id=${user.id})}"><i class="fa fa-check"></i>&nbsp;Yes</a>
            </div>
        </div>
    </div>
</div>

Here “th:href=”@{/user/delete/{id}(id=${user.id})}” is your POST URL.
You can also edit any data inside the modal by adding a form.

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

Few Best Alternatives to Github

Being into software development we frequently find ourselves in need to host our code. For the purpose, crowds are blindly following one single medium for this, Github. It can’t be denied that Github users have their choice to use either Git or Subversion for version control. Conjointly there is a facility of unlimited public code repository for all users of Github. Another fascinating feature of Github is that allows to create ‘organizations’, which at its own is a normal account but at least one user account is required to be listed as the owner of the organization.

Apart from providing desktop application for Windows and OSX, Github also offers the facility to its users and organizations to host one website and unlimited project pages for free on the Github’s website.

Choosing a code repository hugely depends on what you require for a repository and how much can it cater to, if not all. Choosing a repository hosting service might not seem like a big deal. But the repo host you choose can have serious consequences for your developers’ productivity and ability to build great products.

1. Bitbucket

Bitbucket

The Bitbucket comes just next to it in terms of usage and global popularity. Bitbucket also provides a free account for the users and organizations as well with limit for five users. Also, it provides access to unlimited private and public repos. One of the features which is noteworthy is its allowance for the users to puch their files using any of the Git client/Git command line.

The domain for your hosted website on Bitbucket will look something like: accountname.bitbucket.org and domain for that of project pages will be like: accountname.bitbucket.org/project. On the other hand Bitbucket also allows its users to use their own domain name for their website.

2. GitLab

GitLab

GitLab’s sub-motto seems to be “Better than GitHub”, ironic for a project that is itself hosted on Github. One if its unique features is that you can install GitLab onto your own server. This gives you the option of using GitLab on a custom domain as well as with a custom host. GitLab also claims to handle large files and repositories better than GitHub. GitLab also lets users have unlimited public AND private repos for free. Also GitLab facilitates its users by providing automated testing and code delivery so that a user can do more work in lesser time without waiting for the tests to pass manually.

3. Beanstalk

Beanstalk

Beanstalk as another good Github alternative but it is not free. It lets you try it out for 2 weeks free of cost, after which you need to pay. Its cheapest package “Bronze” costs $15 and allows up to 5 users, 3 GB storage and a maximum of 10 repositories. Subversion and Git Version Control Systems are supported by Beanstalk.

4. Kiln

Klin

Kiln is a paid source code host developed by Fog Creek, unlike Github Kiln is not a free source to host your software or website. You can try Kiln (with all the bells and whistles) for 30 days trial period, after that users need to upgrade to the premium version (minimum $18 a month) in order to continue working with Kiln. You will need to pay separately for the Code Review Module. Overall, Kiln is more suited for medium to large organizations of 100 -500 people. You will need to pay separately for the Code Review Module. Overall, Kiln is more suited for medium to large organizations of 100 -500 people.
Kiln makes a domain for your company at companyname.kilnhg.com

5. Codeplane


Codeplane is again a paid service, which offers a 30 day free trial.

Codeplane’s VCS -of choice is Git. It allocates 2 GB for your repositories with no limits on users or number of repositories at $9 a month. Suitable for small companies and freelancing teams. Codeplane also automatically takes a backup of your repositories and stores them in the Amazon S3.

 

Comparison Table
Here is a complete comparison of all the features across all 8 source code hosts discussed in this article:

Features Github Bitbucket Gitlab Beanstalk Kiln Codeplane
Pricing* Free Free Free $15/mo $18/mo $9/mo
Private Repo Paid Unlimited, Free Unlimited, Free 10 Paid Unlimited, Paid
Public Repo Unlimited, Free Unlimited, Free Unlimited, Free 10 Paid Unlimited, Paid
Storage Limit 1GB per repo 2GB None 3GB None 2GB
Users Unlimited 5 & Unlimited if public Unlimited 5 5 Unlimited
VCS Git, SVN Git, Hg Git Git, SVN Git, Hg Git
Graphs Yes No Yes No No No
Web Hosting Static sites. Page generator Static sites Static No Yes No
Code Review Yes Yes Yes Yes No No
Wiki Yes Yes Yes No Yes No
Bug Tracking Yes (Login Required) Yes Yes Yes Yes Yes
Discussion Forum No No No $15/mo No No

Scope and this in JavaScript

Today I want to talk a little about “scope” in JavaScript and the this variable. The idea of “scope” is that it’s where certain variables or functions are accessible from in our code, & the context in which they exist & are executed in.

Have you ever seen something like this?

function someFunction() {
	var _this = this;
	something.on("click", function() {
		console.log(_this);
	});
}; And wondered what the var _this=this; is all about, hopefully this article should clear it all up. The first scope is Global Scope. This is very easy to define. If a variable or function is global, it can be got at from anywhere. In a browser, the global scope is the window object. So if in your code you simply have:
var x = 9; You’re actually assigning the property window.x to 9 (when working in a browser). You could type window.x = 9; if you like, but because it’s the global object you don’t have to. Properties on the global object can be accessed from anyplace in our code.

The only other scope we can have is the Local Scope. JavaScript scopes at a function level. For example:

function myFunction() {
	var x = 5;
};
console.log(x); //nothing will show in console

Since x was initialized within myFunction(), it is only accessible within myFunction().

Caution!

If you declare a variable & forget to use var keyword, that variable is automatically made global. So this code will work:

function myFunction() {
	x = 5;
});
console.log(x); //5

This is really a very bad idea. It’s considered bad practice to clutter the global scope. You should add as fewer properties as you possibly can to the global object. That’s why libraries such as jQuery often do this:

(function() {
	var jQuery = { /* all methods go here */ };
	window.jQuery = jQuery.
})();

Wrapping the whole thing in a function which is then immediately invoked means all the variables within that function are bound to the local scope. At the very end you can then expose all your methods by binding the jQuery object to the window, the global object. Although I’ve simplified it hugely, this is in essence however the jQuery source works.

That’s pretty much all there is too it at a basic level. Things get a bit complex once we take a look at the this keyword in JavaScript and how it works. I’m sure we’ve all come across this issue:

$("someLink").on("click", function() {
	console.log(this); //points to someLink(as expected)
	$.ajax({
		//ajax set up
		success: function() {
			console.log(this); //points to the global object. Huh?
		}
	});
});

this is a variable that is automatically set for you once a function is invoked. The value it’s given depends on how a function is invoked. In JavaScript we have limited main ways of invoking functions. I don’t wanna talk about them all today, but just the three ways most people use them; either when a function is called as a method, or on it’s own, or as an event handler. Depending on how a function is invoked, this is set differently:

function bar() {
	console.log(this); //global object
};

myapp = {};
myapp.bar = function() {
	console.log(this); //points to myapp object
}

var link = document.getElementById("someId");
link.addEventListener("click", function() {
	console.log(this); //points to link
}, false);

Those are all fairly obvious. The MDN has a nice explanation for the third & why this happens. Go through!

There are few other ways in which we can invoke functions by explicitly defining what the value of this should be, but as this has already ended up as a quite long article, I’m leaving those for another day. If you have any questions, please do leave a comment & I will get back to you.

 

Programming Languages To Study In 2018

Software development is a dynamic field. New and in-demand programming languages, frameworks and technologies will emerge, rise to fame, then change state within the course of many years.

Staying on top is one among the key factors for business and technological innovation. And with over 600 unique programming languages, choosing the best programing language for your project could also be difficult, and might be the toughest part in the initial development part.

Here’s the list, in order from most to least in-demand. (Source: Indeed.com)

Top Programming Languages To Learn In 2017

A lot of people  search over the internet or ask me about what programming languages they must learn. I found myself in a troublesome scenario because this is often a very hard question to answer o to decide.There are a lot of things that need to be taken under consideration before making a choice, particularly when it involves that programming language you should learn.

banner2d

When it comes to tech, staying ahead of the curve is a pretty good idea. In such an innovative and fast-paced industry, new technologies are emerging every week, every day… basically all the time!

The future of coding requires stability and good practices so our innovations will work. In fact, our projects are often so much bigger now, we need the innovation more than ever.
According to my research, these are the programming languages you should be focusing in 2017:
-CoffeeScript
-D
-Go
-Hack
-JAVA
-JavaScript
Less.js
-Python

-Ruby
-Rust
-SQL
-Swift
Don’t worry about the serial! I’ve just ordered alphabetically ?  

CoffeeScript
Somewhere along the line, some JavaScript programmers grew tired of typing all those semicolons and curly brackets. So they created CoffeeScript, a preprocessing tool that turns their syntactic shorthand back into regular JavaScript. It’s not as much a language as a way to save time hitting all those semicolons and curly bracket keys.

D
Hearing this for the first time? Any good programmer already knows plenty about D. It has been around for well over a decade, has been utilized by web giants such as Facebook, and has built up a consistent and loyal following.

‘D’ is an object oriented multi-paradigm system programming language. ‘D’ is actually developed by re-engineering C++ programming language but it is distinct programming language that not only takes in some features of C++ but also some features of other programming languages such as Java, C#, Python and Ruby.

Let’s start learning D!

Go
Google’s Go programming language (Golang) has been ‘up and coming’ for a few years now. In 2016 its popularity skyrocketed, so 2017 is guaranteed to be the year when everybody – and we mean everybody – starts using Go. It’s the epitome of all of the biggest programming trends of late; it emphasizes simplicity, high performance, efficiency and in-built support. And most significantly, it’s easy to learn.

In the last 12 months in particular start-ups have made it their language of choice. Proving a very dangerous rival to the likes of Ruby and Node.

Want to start learning Go? Let’s start!

Hack
Hack is a programming language for the HipHop Virtual Machine (HHVM), created by Facebook as a dialect of PHP. The language implementation is open-source.

So you do not know about Hack? This programming language is brought by Facebook. Basically, it is holding up a feature on one of the most popular and successful websites. See why you need to learn this language? Just like Google, Facebook is not going anywhere. If you want to be part of the programming future, learn this language!

Java
Most common programming language as on the day. Used for Android development and most of the financial systems around the world. Java is prominently preferred for its speed and performance. Rated best programming language to learn for years, it’s always good to keep your skills updated.

JavaScript
JavaScript isn’t exactly new, but it is ubiquitous and that’s not going to change any time soon. It has uses in anything web-related and a lot more besides, and the amount of activities the general population is conducting over the web is forever increasing. Java has held the top spot on the TIOBE index for the last few years, and its percentage share increases year on year too.

So why is JavaScript so popular? For a start, it’s ‘the’ language of the web – no JavaScript, no web. Secondly, the mere fact that it’s so popular continues to boost its popularity! There are endless other reasons too; it’s supported by every browser, it can be run as a server side language, it’s not all that difficult to learn and has a huge open source community…. we could go on and on. Basically as long as the web is around, JavaScript will be around.

Less.js
Just like CoffeeScript, Less.js is really just a preprocessor for your files, one that makes it easier to create elaborate CSS files. Anyone who has tried to build a list of layout rules for even the simplest website knows that creating basic CSS requires plenty of repetition; Less.jshandles all this repetition with loops, variables, and other basic programming constructs. You can, for instance, create a variable to hold that shade of green used as both a background and a highlight color. If the boss wants to change it, you only need to update one spot.

Python
This open source language has been popular for 30 years and on the rise for 10 years. An ideal first language with which to learn programming. The most taught language in US universities including M.I.T. and Stanford. This dynamic type language is used for robotic, mathematical and basic gaming applications.

Ruby
Ruby is already a firm favorite with start-ups and has been for quite some time. Even with some competitive rival languages joining its ranks, its popularity doesn’t seem to be waning. But should we just expect more of the same in 2017? Well, yes and no. Ruby is particularly suited to solo programmers and niche projects (hence why it was so popular with start-ups). And more and more programmers are choosing to make their living by freelancing or taking on… you guessed it, niche projects.

So if you’re planning a code-as-you-go career, want to set up your own programming or development business, or just want to take on some freelance work on the side, look no further than Ruby and join the ever-growing club.

Thinking why you should learn Ruby? Have a look here.

Rust
Rust is a general-purpose, multi-paradigm, compiled programming language sponsored by Mozilla Research. It is designed to be a “safe, concurrent, and practical language”, supporting functional and imperative-procedural paradigms.

Mozilla launched this programming language in 2014 and the number of users has increased significantly in 2016. It is believed that it will do just as exponentially in 2017 as well. If you are planning to learn programming for the first time, this is definitely one of the languages to learn.

SQL
As more and more people are getting on-board technology, the database has been increasing exponentially.If you are interested in managing the database, SQL is made for you. Termed Special purpose language, SQL is made for a special purpose, unlike general purpose language. Used almost everywhere where database management is required. SQL is a great skill to learn.

Swift
Apple saw an opportunity when programming newbies complained about the endless mess of writing in Objective C. So they introduced Swift and strongly implied that it would replace Objective C for writing for the Mac or the iPhone. They recognized that creating header files and juggling pointers was antiquated. Swift hides this information, making it much more like writing in a modern language like Java or Python. Finally, the language is doing all the scut work, just like the modern code.

Check the swift tutorial hereWant to learn more?