Code Saying http://codesaying.com Let The Code Say Tue, 14 Jan 2020 16:42:50 +0000 en-US hourly 1 https://wordpress.org/?v=5.3.2 Time.deltaTime in Unity3D http://codesaying.com/time-deltatime-in-unity3d/ http://codesaying.com/time-deltatime-in-unity3d/#respond Sat, 11 Jan 2020 17:33:18 +0000 http://codesaying.com/?p=530 It is very important for a Unity Developer to have a sound understanding of Time.deltaTime. Let us learn the basics of Time.deltaTime in Unity3D with some examples. What is Time.deltaTime? Time.deltaTime is the completion time in seconds since the last frame. It is read only. Therefore you cannot modify it! This property provides the time…

The post Time.deltaTime in Unity3D appeared first on Code Saying.

]]>
It is very important for a Unity Developer to have a sound understanding of Time.deltaTime. Let us learn the basics of Time.deltaTime in Unity3D with some examples.

What is Time.deltaTime?

Time.deltaTime is the completion time in seconds since the last frame. It is read only. Therefore you cannot modify it! This property provides the time between the current and previous frame. But what does that mean?

We are aware of the Update method in Unity3D. Time.deltaTime in layman terms would be the time lapse between two update methods. Let’s say there are 10 lines of code in the Update Method. So, Time.deltaTime would determine how much time does it take to execute the lines of code in one frame. This property is a variable value as its value would depend upon how much time one frame takes to execute which further depends upon how much lines of code needs to be executed.

Points to note:

  • FixedUpdate uses fixedDeltaTime instead of deltaTime.
  • Unity can call OnGUI multiple times per frame. Therefore, it is not advisable to rely on Time.deltaTime inside OnGUI method.

Time.deltaTime in relation with fps

FPS is frames per second and the time taken for completion of one frame is Time.deltaTime. In other words, we can say,

fps = 1/Time.delaTime

or

Time.DeltaTime = 1/fps

Therefore, when fps is 60, Time.deltaTime is = 0.0166666 seconds

Usage of Time.deltaTime in Unity3D

Creating a Timer

    private float timer = 0.0f;
    void Update()
    {
        timer += Time.deltaTime;
        //Game Over after 60 seconds
        if(timer > 60){
            //Game Over
        }
    }

Smooth Translation of an object independent of Frame Rate

Let us use static speed for translation of an object for movement in x-axis, lets say speed = 5 as below:

    private int speed = 5;
    void Update()
    {
        transform.Translate(speed , 0 , 0);
    }

Lets test the lines of code on a device with fps equal to 60 (i.e. 60 frames in one second). The object moves 5 units in 1 frame(as speed=5). The distance moved by object in 60 frames or 1 second is 60*5 = 300 units

Now, lets test this code on a device with fps equal to 30. The object still moves 5 units in 1 frame as speed = 5. However, the distance moved by object in 30 frames or 1 second is 30*5 = 150 units.

Therefore, using static value, an object on a device with higher fps moves faster than that on a lower fps device, which is not what is desired.

Lets see what happens when we use Time.deltaTime.

    void Update()
    {
        transform.Translate(Time.deltaTime , 0 , 0);
    }

The above line of code gives a smooth translation in x-axis as the object will always move independent of the Time Frame i.e. if the fps falls low or high, the translation is linear.

Lets say the fps is 60, i.e. 60 frames in one second. Time for each frame is 0.016666666 as explained formerly. The distance moved by object in 1 second is 1 unit(0.0166666*60 frames)

If the fps is 30, i.e. 30 frames in one second, time for each frame is 0.03333. The distance moved by object in 1 second is 1 unit(0.03333*30 frames)

Therefore, the object moves over the same distance irrespective of the device performance.

So, Time.deltaTime is used for actions that need to be independent of frame rate.

Happy Coding!

The post Time.deltaTime in Unity3D appeared first on Code Saying.

]]>
http://codesaying.com/time-deltatime-in-unity3d/feed/ 0
Install latest Node 13/12 on Ubuntu/Debian via apt http://codesaying.com/how-to-install-node-12-13-on-ubuntu-18-or-debian-via-apt/ http://codesaying.com/how-to-install-node-12-13-on-ubuntu-18-or-debian-via-apt/#respond Thu, 09 Jan 2020 14:30:15 +0000 http://codesaying.com/?p=508 This blog guides you to install the latest version of node either be it node 12 or node 13 on the latest ubuntu 18.04 or Debian with help of ppt. Node.js is a popular open-source javascript-based framework that can be used to create server-side applications very quickly. With its help, people are able to create…

The post Install latest Node 13/12 on Ubuntu/Debian via apt appeared first on Code Saying.

]]>
This blog guides you to install the latest version of node either be it node 12 or node 13 on the latest ubuntu 18.04 or Debian with help of ppt.

Node.js is a popular open-source javascript-based framework that can be used to create server-side applications very quickly. With its help, people are able to create server-side applications in javascript. Under are instructions to install node be either node 12 or node 13 on ubuntu either 18.04 or 16.04 or old versions and Debian via ppt

Instructions to install node on Ubuntu or Debian

Node v13.x :

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_13.x | bash -
apt-get install -y nodejs

Node v12.x :

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_12.x | bash -
apt-get install -y nodejs

Node v11.x:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_11.x | bash -
apt-get install -y nodejs

Node v10.x:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_10.x | bash -
apt-get install -y nodejs

Node v8.x:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_8.x | bash -
apt-get install -y nodejs

To compile and install native addons from npm, you may also need to install build tools:

# use `sudo` on Ubuntu or run this as root on debian
apt-get install -y build-essential

The above information is taken from nodesource/distributions .

A Little bit about node

Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser.Node.js was written initially by Ryan Dahl in 2009. In January 2010, a package manager was introduced for the Node.js environment called npm. In June 2011, Microsoft and Joyent implemented a native Windows version of Node.js.
Node.js brings event-driven programming to web servers, enabling the development of fast web servers in JavaScript. A Node.js app is run in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js needs to perform an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

Want to create fat jar in Gradle ?? follow here.

Happy Installing !!!

The post Install latest Node 13/12 on Ubuntu/Debian via apt appeared first on Code Saying.

]]>
http://codesaying.com/how-to-install-node-12-13-on-ubuntu-18-or-debian-via-apt/feed/ 0
Understanding Screen Point, World Point and Viewport Point in Unity3D http://codesaying.com/understanding-screen-point-world-point-and-viewport-point-in-unity3d/ http://codesaying.com/understanding-screen-point-world-point-and-viewport-point-in-unity3d/#respond Wed, 18 Dec 2019 18:29:37 +0000 http://codesaying.com/?p=488 A Camera is a device through which the player views the world. Understanding Screen Point, World Point and Viewport point in Unity3D forms the basics of how camera can be used while determining the position of an object or mouse pointer.  Screen point Screen point is defined in pixels. The bottom-left of the screen is…

The post Understanding Screen Point, World Point and Viewport Point in Unity3D appeared first on Code Saying.

]]>
A Camera is a device through which the player views the world. Understanding Screen Point, World Point and Viewport point in Unity3D forms the basics of how camera can be used while determining the position of an object or mouse pointer. 

Screen point

Screen point is defined in pixels. The bottom-left of the screen is (0,0); bottom-right of the screen is (pixelWidth,0), left-top is (0, pixelHeight) and the right-top is (pixelWidth,pixelHeight). Let’s understand this with an image. 

So, if the screen resolution is 1024×768, 

The bottom-left of the screen is (0,0); bottom-right of the screen is (1024,0), top-left is (0, 768) and the top-right is (1024,768). The centre point will be (512, 384)

This point can be used to find which half of the screen is touched. If 

1.mousePosition < pixelWidth/2, the touch is on the left side of the screen

2. mousePosition >= pixelWidth/2, the touch is on the right side of the screen

Another usage of this point may be to move an object to the point where the screen is clicked. It is illustrated in the coming sections.

Viewport Point

A viewport space point is normalized and relative to the Camera. The points on the screen range between 0 and 1. You can determine the the x-coordinate by dividing the screenPoint.x by pixelWidth and the y-coordinate by dividing the screenPoint.y by pixelHeight. Accordingly, the bottom-left of the Camera is (0,0); bottom-right is (1,0) the top-right is (1,1); top-left is (0, 1). The centre point will be (0.5, 0.5).

An important point to note is that the viewport point is relative to the camera and an object placed according to the view port point stays at the same place on the screen always.

World Space Point

A world space point is defined in global coordinates (for example, Transform.position). It is the position of the object in world or global space. 

Unity in-built functions

Unity offers in-built functions to inter-convert world point, viewport point and space points into each other.

Camera.ScreenToWorldPoint()

Transforms position from screen space into world space.

Camera.ScreenToViewportPoint()

Transforms position from screen space into viewport space.

Camera.ViewportToScreenPoint()

Transforms position from viewport space into screen space.

Camera.ViewportToWorldPoint()

Transforms position from viewport space into world space

Camera.WorldToScreenPoint()

Transforms position from world space into screen space.

Camera.WorldToViewportPoint()

Transforms position from world space into viewport space.

Let’s Learn Better!

Let us see an example on how to move from world to screen point and vice versa.

If there is an object lying in the world space and you want to move it to the position where you click (not changing the z position of the object), you can use the following set of code:

Vector3 myScreenPos = Camera.main.WorldToScreenPoint(transform.position);
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, myScreenPos.z));

myScreenPos gives you the position of the object in the screen Space. This point will help you keep the object in-tact in z-axis.
Input.mousePosition gives you the position of the mouse Pointer in x and y axis.
The new position of the object is fetched by converting the screen position of mousePointer in x and y axis and the screen position of object in z-axis.

You can use the similar concept for other conversions too.

I hope you would now have a better understanding of Screen Point, World Point and Viewport point.

Happy Coding!

The post Understanding Screen Point, World Point and Viewport Point in Unity3D appeared first on Code Saying.

]]>
http://codesaying.com/understanding-screen-point-world-point-and-viewport-point-in-unity3d/feed/ 0
Interfaces In Go and how to use them http://codesaying.com/interfaces-in-go/ http://codesaying.com/interfaces-in-go/#respond Mon, 04 Nov 2019 14:43:30 +0000 http://codesaying.com/?p=398 GoLang provides us a type called Interface type, which specifies a method set called its interface. Any type whose method set is a superset of the interface is said to implement the interface. So lets learn to use interfaces in Go. You must be familiar with the interface keyword from Object-Oriented Language. The concept is…

The post Interfaces In Go and how to use them appeared first on Code Saying.

]]>
GoLang provides us a type called Interface type, which specifies a method set called its interface. Any type whose method set is a superset of the interface is said to implement the interface. So lets learn to use interfaces in Go.

You must be familiar with the interface keyword from Object-Oriented Language. The concept is the same, but its intended use in Go is different from how we have been using interfaces in our Object-Oriented languages like Java, C# and more. So before we deep dive into interfaces, lets clear up some concepts.

Is Go an Object Oriented language?

Yes and No. We can use Object oriented concepts in Go, but it’s not really intended to be used as an Object-Oriented language. From official go docs

Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).
Also, the lack of a type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java.

How’s interfaces in Go are different from other Object Oriented languages?

From offical go lang docs

Object-oriented programming, at least in the best-known languages, involves too much discussion of the relationships between types, relationships that often could be derived automatically. Go takes a different approach.
Rather than requiring the programmer to declare ahead of time that two types are related, in Go a type automatically satisfies any interface that specifies a subset of its methods. Besides reducing the bookkeeping, this approach has real advantages

Enough said, lets start with coding

How to declare interfaces in Go?

An interface is a type just like struct e.g

Above is an example of Closer interface from inbuilt pkg io. Closer is an interface name that has one method Close in it that returns an error. It is usually considered to be a go-idiomatic way to have only one method in an interface. The bigger the interface, the weaker the abstraction

So how’s that different from Object-Oriented languages?

The difference lies in two key things, implementation and how its used.

Let’s see an example of how inbuilt os/file implements the inbuilt Closer interface.

That’s it! We don’t have to explicitly define that File implements Closer interface. So, if any method of a struct has the same name and signature of an interface, in that case, the struct implements the interface. It’s pretty much like Duck Typing(not exactly duck typing) which states If it looks like a duck, and it quacks like a duck, then it is a duck. In the above example, struct File has a method whose signature is just like of method Close in the interface Closer. That’s why File implements the interface Closer.

Okay, that’s fine, but what advantages do interfaces in Go have over Object–oriented interface?

From the top view, it seems like the same thing but Go interface gives us a lot more flexibility. Let’s understand it with an example.

Let’s say we want to close the file and if there is an error, log it

We can write a method like

So, this method closes the file and logs the error. As a general thumb rule in Go, your method should accept an interface and return a struct. In our case, we are not returning anything. We can call this method as

Focus here on defer Close(r). Now, let’s modify this Close method so that it accepts the inbuilt Closer interface.

So without any change, our main function will run since file implements Closer interface. But now lets make this method more interesting.

Let’s say you are establishing a connection to the database and when you are done, you want to close that connection. So we are talking about the package database/sql here. If we look closely, we see type Db has method Close that has the same signature as that of Closer. That means we can pass Db in this method. In source code, we can see

That means I can do something like

Note: defer Close(db) and Close (associated with *DB) both are different methods. defer Close() is a custom method that we created above that accepts Closer interface as an argument

Focus on defer Close(db). From the same method, I am able to close file and SQL con. But now, let’s make it more interesting!

Go provides Flexibility

As these structs were defined before writing out the Close method, let’s create a type that embedded a fake resource in it

Now we want to close this fake Resource also when we are done. So why don’t we take advantage of our Close method. If I write a method like this

Now, out FakeResource type implements Closer. Now I can pass the value of FakeResource in the Close method to close it. So that’s what godocs are saying as quoted above

Rather than requiring the programmer to declare ahead of time that two types are related, in Go a type automatically satisfies any interface that specifies a subset of its methods

This gives us a lot more flexibililty than conventional Object Oriented interfaces.

Difference in thinking philosophy

While using interfaces in Go, the design philosophy is different as that from conventional Object Oriented Languages. In Conventional languages, we first think of interfaces and design our classes around them, but in Go, we don’t need to declare interfaces ahead of time. Let’s break it down with an example.

We have a struct Square, and we have a method area defined.

Now lets say we want to have a method that will double the area of the square as under

We can call the above as

Now lets say we have one more requirement. We have one more struct rectangle and we need to find the double of Area for rectangle also. So we can create one interface here. I have named it Arear

So whole program will be like

Notice how we create interface Arear when needed. We didn’t think before about creating interface, but as when required

You can also run this example in go playground https://play.golang.org/p/pQIpBjzoCXV

That’s it . There are some further readings that I recommend

There are some further readings that I recommend

https://golang.org/doc/effective_go.html#interfaces

https://golang.org/ref/spec#Interface_types

https://gobyexample.com/interfaces

https://tour.golang.org/methods/9

https://golang.org/doc/faq#inheritance

https://www.ardanlabs.com/blog/2013/07/object-oriented-programming-in-go.html

Happy Coding!!!

The post Interfaces In Go and how to use them appeared first on Code Saying.

]]>
http://codesaying.com/interfaces-in-go/feed/ 0
Google Play App Rejection: Violation of Inappropriate Ads Policy http://codesaying.com/google-play-app-rejection-violation-of-inappropriate-ads-policy/ http://codesaying.com/google-play-app-rejection-violation-of-inappropriate-ads-policy/#respond Wed, 30 Oct 2019 14:54:21 +0000 http://codesaying.com/?p=447 Showing ads in the app is the best way for generating revenue. With changes in Google Policies, Google Play has started rejecting apps due to violation of inappropriate ads policy. Violation of the inappropriate ads policy will not reject your previously published app, it will just reject the current update. The ads shown within your…

The post Google Play App Rejection: Violation of Inappropriate Ads Policy appeared first on Code Saying.

]]>
Showing ads in the app is the best way for generating revenue. With changes in Google Policies, Google Play has started rejecting apps due to violation of inappropriate ads policy. Violation of the inappropriate ads policy will not reject your previously published app, it will just reject the current update.

The ads shown within your app must be appropriate for the intended audience of your app, even if the content by itself is otherwise compliant with Google policies. For example, ads that show mature content or services cannot be served in apps that have a content rating for younger audiences. However, if you submitted an update, the previous version of your app is still available on Google Play.

Child Directed Setting

The Children’s Online Privacy Protection Act (COPPA) applies to websites, apps, and services directed to children under the age of 13. It also applies to general audience apps, websites, or services with users known to be under the age of 13. For purposes of the COPPA, there is a setting called “tag for child-directed treatment“. You understand that abuse of this setting may result in termination of your Google account.

Apps in the Designed For Families Program as Primarily child-directed apps and users signed into Google accounts managed with Family Link automatically have all content treated as child-directed for all ad requests.

Setting tag for child-directed treatment fo Admob in Unity

Use the following code snippet to request an ad.

// Returns an ad request with custom ad targeting.
    private AdRequest CreateAdRequest()
    {
        return new AdRequest.Builder()
            .AddKeyword("game")
            .TagForChildDirectedTreatment(true)
            .AddExtra("color_bg", "9B30FF")
            .Build();
    }

Setting the TagForChildDirectedTreatment to true indicates that you want your content treated as child-directed for purposes of COPPA.

Abmob Panel Control

The above code snippet is not enough for controlling or restricting the ads for admob. Make sure that you block sensitive categories in the admob control panel.

  1. Sign in to your AdMob account at https://apps.admob.com.
  2. Click Apps in the sidebar.
  3. Select the name of your app.
  4. Click Blocking controls under Apps in the sidebar.
  5. In particular, you’ll want to look at the “Sensitive Categories”. Block all the categories that might disrupt the ads appropriateness on the basis of your content policy. 

Google Play’s Designed For Families Policy

Apps designed specifically for children must participate in the Designed for Families program. However, if your app targets children as only one of its audiences, participating in the Designed for Families program is still a great way to surface your app to the right users. If you decide not to participate in the program, you still must comply with the Google Play Families Policy requirements.

If your app is targeted towards everyone, including children and families, you’ll need to include code snippet above that calls the tagForChildDirectedTreatment()method for ad requests served to children. 

All apps classified as Designed for Families, and all ad requests with tagForChildDirectedTreatment(true), must use a Google Play certified ad network. Starting October 15, 2019, AdMob will block ad serving from non-certified ad sources and custom events.

No more rejections. Happy publishing!

The post Google Play App Rejection: Violation of Inappropriate Ads Policy appeared first on Code Saying.

]]>
http://codesaying.com/google-play-app-rejection-violation-of-inappropriate-ads-policy/feed/ 0
Parse Excel Sheet in Unity3D http://codesaying.com/unity-parse-excel-in-unity3d/ http://codesaying.com/unity-parse-excel-in-unity3d/#respond Sat, 07 Sep 2019 14:25:44 +0000 http://codesaying.com/?p=383 Have an excel sheet containing all the weapons and their parameters for the game? Want to display or use the data contained in a excel sheet? But, how would you access this excel sheet via code? Confused? Let us learn how to parse excel sheet in Unity3D! The most convenient way to parse an excel…

The post Parse Excel Sheet in Unity3D appeared first on Code Saying.

]]>
Have an excel sheet containing all the weapons and their parameters for the game? Want to display or use the data contained in a excel sheet? But, how would you access this excel sheet via code? Confused? Let us learn how to parse excel sheet in Unity3D!

The most convenient way to parse an excel sheet in Unity3D is to convert it into CSV.

What is CSV?

CSV stands for “comma-separated values”. CSV is a simple file format used to store tabular data, such as a spreadsheet, excel sheet or database. Files in the CSV format can be imported to and exported from programs that store data in tables.

CSV Parsing in Unity3D

Here is a code snippet that would help you parse your CSV in Unity3D:

using UnityEngine;

public class CSVParse : MonoBehaviour
{
    /// <summary>
    /// The csv file can be dragged throughthe inspector.
    /// </summary>
    public TextAsset csvFile;

    /// <summary>
    /// The grid in which the CSV File would be parsed.
    /// </summary>
    string[,] grid;


    void Start()
    {
        grid = getCSVGrid(csvFile.text);
    }

    /// <summary>
    /// splits a CSV file into a 2D string array
    /// </summary>
    /// <returns> 2 day array of the csv file.</returns>
    /// <param name="csvText">the CSV data as string</param>
    static public string[,] getCSVGrid(string csvText)
    {
        //split the data on split line character
        string[] lines = csvText.Split("\n"[0]);

        // find the max number of columns
        int totalColumns = 0;
        for (int i = 0; i < lines.Length; i++)
        {
            string[] row = lines[i].Split(',');
            totalColumns = Mathf.Max(totalColumns, row.Length);
        }

        // creates new 2D string grid to output to
        string[,] outputGrid = new string[totalColumns + 1, lines.Length + 1];
        for (int y = 0; y < lines.Length; y++)
        {
            string[] row = lines[y].Split(',');
            for (int x = 0; x < row.Length; x++)
            {
                outputGrid[x, y] = row[x];
            }
        }

        return outputGrid;
    }

}

Here, the CSV File data is stored in a two-dimensional array. In order to fetch a specific value at a given index, use the following function:


    /// <summary>
    /// Gets the value from the CSV File at index(row,col).
    /// </summary>
    /// <param name="row">Row.</param>
    /// <param name="col">Col.</param>
    void getValueAtIndex(int row, int col){
        Debug.Log(grid[row, col]);
    }

Similarly, use the following function in order to display the contents of the whole grid and to check whether your data has been correctly parsed:

    /// <summary>
    /// outputs the content of a 2D array.
    /// </summary>
    /// <param name="grid">2D array , here the CSV grid.</param>
    static public void DisplayGrid(string[,] grid)
    {
        string textOutput = "";
        for (int y = 0; y < grid.GetUpperBound(1); y++)
        {
            for (int x = 0; x < grid.GetUpperBound(0); x++)
            {

                textOutput += grid[x, y];
                textOutput += ",";
            }
            textOutput += "\n";
        }
        Debug.Log(textOutput);
    }

Happy Coding!

The post Parse Excel Sheet in Unity3D appeared first on Code Saying.

]]>
http://codesaying.com/unity-parse-excel-in-unity3d/feed/ 0
Gradle:Part 3, Java project setup using gradle http://codesaying.com/setup-java-project-using-gradle/ http://codesaying.com/setup-java-project-using-gradle/#comments Sun, 04 Aug 2019 15:33:00 +0000 http://codesaying.com/?p=209 In this part, we will set up a java project using Gradle. We will also be configuring IntelliJ, so we can run or debug a java project based on Gradle in IntelliJ. This part is the continuation of Part 2, Installing Gradle on Local Machine. Have quick look before you start this part. Set up…

The post Gradle:Part 3, Java project setup using gradle appeared first on Code Saying.

]]>
In this part, we will set up a java project using Gradle. We will also be configuring IntelliJ, so we can run or debug a java project based on Gradle in IntelliJ.

This part is the continuation of Part 2, Installing Gradle on Local Machine. Have quick look before you start this part.

Set up Java Project using Gradle

Now, we already have Gradle installed on local machine. If not, have a quick look here Part 2: Installing Gradle on local Machine and do a quick installation. I am using IntelliJ idea IDE. Now let’s get started.

Let’s create a directory with name test-gradle

mkdir test-gradle
cd test-gradle/

Gradle needs to be initialised in this folder.This will setup the gradle structure inside the folder. It can be done using:

gradle init --type java-application

The following output is displayed:

Starting a Gradle Daemon, 2 incompatible and 1 stopped Daemons could not be reused, use --status for details

Select build script DSL:
  1: groovy
  2: kotlin
Enter selection (default: groovy) [1..2] 

Let’s choose groovy (option 1) and move forward. After that it will ask you about the testing-framework

Select test framework:
  1: junit
  2: testng
  3: spock
Enter selection (default: junit) [1..3] 

Let’s choose junit (option 1) for now.

Then it will ask you for Project and package name

Project name (default: test-gradle): 
Source package (default: test.gradle): 

You can change as you like or else default will be test-gradle. Press enter and you can see the following:

BUILD SUCCESSFUL in 3m 21s
2 actionable tasks: 2 executed

So now lets open this folder in intellij or any IDE. On opening in IntelliJ, you will have a pop up as shown below. Enable auto-imports; you can also set custom gradle location as done in under screen shot

After pressing enter, the IntelliJ will open the project as in the screenshot below. Notice build.gradle file; we will be making changes in this file shortly.

Now open your terminal, change directory(cd) to current folder and then run

 gradle run

> Task :run
Hello world.

The output Hello world is written in class App.java. You can change that and run it. Now lets make some more changes so that we can run it by IntelliJ itself.

Configuring IntelliJ idea for Java project

Its pretty simple. Open your build.gradle file and add id 'idea' in the plugins block. So your plugin block will now appear like

plugins {
    // Apply the java plugin to add support for Java
    id 'java'

    // Apply the application plugin to add support for building an application
    id 'application'
    
    id 'idea'
}

Now open Edit configuration and add configuration as

Notice the run in tasks section. Run is a task, we will talk about tasks more in next section, this task is already provided by application plugin . You can check these things as

You can play more around these settings. Now press run button and you can see the output in result

So that’s it! Your IntelliJ is ready for Gradle projects. Now lets add some dependencies to the project

Adding dependencies using Gradle to your project

Let’s add google guice as a dependency to our project. Lets open build.gradle. As you can see in the repositories by default jcenter is the default repository; we can change it to maven, ivy, file as needed. Let’s change it to maven. For that, we need to add mavenCentral() to our repositories block. So our repository block will be like

repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

Now let’s add dependency. We can simply do that by adding compile group: 'com.google.inject', name: 'guice', version: '4.0' to the dependencies block. So our dependencies block will look like

dependencies {
    compile group: 'com.google.inject', name: 'guice', version: '4.0'
    testImplementation 'junit:junit:4.12'
}

Now lets modify our main class to use guice dependencies like

We are calculating the time taken in execution. Now we can run it either by command line using the command gradle run or by ide that we just configured above.

So that’s it for this part; now we know how to add dependencies and set up java project using gradle and also how to set up IDE for Gradle project. In next section, Part 4, Creating executable fat jar using Gradle we will cover how to create executable fat jar using Gradle that can be deployed on production.

The post Gradle:Part 3, Java project setup using gradle appeared first on Code Saying.

]]>
http://codesaying.com/setup-java-project-using-gradle/feed/ 3
Gradle: Part 4, Creating a fat jar using Gradle http://codesaying.com/creating-fat-jar-using-gradle/ http://codesaying.com/creating-fat-jar-using-gradle/#respond Sun, 04 Aug 2019 15:32:57 +0000 http://codesaying.com/?p=232 In this part, we will create an executable fat jar with dependencies using Gradle task or you can say we will create an executable jar which contains all dependencies. This part is a continuation of Java Project set up using gradle. What is Gradle Task In a simple sense, a task is a groovy/koltin function.…

The post Gradle: Part 4, Creating a fat jar using Gradle appeared first on Code Saying.

]]>
In this part, we will create an executable fat jar with dependencies using Gradle task or you can say we will create an executable jar which contains all dependencies. This part is a continuation of Java Project set up using gradle.

What is Gradle Task

In a simple sense, a task is a groovy/koltin function. Let’s start by writing a simple task. Go to build.gradle and write a task as such

task hello {
        println 'Hello world!'
}

and execute it as gradle hello and you can see the output as


> Configure project :
Hello world!

Now, this is a very simple task that only prints but you can create a task to perform any action like copying the file before compiling, etc. We will use the task to create an executable fat jar. Before we create this task, we must know that Gradle supports two types of tasks: a simple task and custom task.

A simple task is basically a default task or a task that is provided by the id in the plugin i.e in our case application plugin provides us the run task. Now we can override this task to add more functionalities, e.g. if you want to pass System properties to your project you can override it as

run {
    systemProperties System.getProperties()
}

Now you can run it using cmd as

gradle -Dconf.path=/xyz/conf.yml run

or passing VM options in IntelliJ run configuration and for testing, you can read it as

System.getProperty("conf.path") in code.

But sometimes default tasks are not enough. We might want to create a custom task; we can do that in gradle e.g

task hello {
        println 'Hello world!'
}

is a custom task. Note that in case of default task we define the task with an action closure, we don’t need to add a task in front of the task, but in case of a custom task, we need to do that.

Creating executable fat jar using Gradle custom task

We will create a custom task to create an executable fat jar with dependencies. In build.gradle add as under

version = '1.1.0'

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': "${mainClassName}"
    }
    baseName = "${rootProject.name}"
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

The mainClassName is already defined in our build.gradle and rootProject.name is already by default defined in settings.gradle. So now run gradle clean fatJar. And now you can see a jar under build/libs in the test-gradle folder.

You can now run it as

java -jar build/libs/{jar_name}.

In my case jar name is test-gradle-1.1.0.jar. So now I can also execute it as

java -Dconf.path=/xyz/conf.yml -jar build/libs/test-gradle-1.1.0.jar

Note: I am passing system variables here

So that’s it! Deploy this jar where it’s needed.

Happy Coding!!!

The post Gradle: Part 4, Creating a fat jar using Gradle appeared first on Code Saying.

]]>
http://codesaying.com/creating-fat-jar-using-gradle/feed/ 0
Gradle: Part 2, Installing Gradle on Linux System http://codesaying.com/installing-gradle-on-local-linux-system/ http://codesaying.com/installing-gradle-on-local-linux-system/#comments Sun, 04 Aug 2019 15:32:53 +0000 http://codesaying.com/?p=176 In this part, we will install Gradle on the Linux system. I am having Ubuntu OS and we will use ppa for installation Installing Gradle on the local Linux machine This part is a continuation of Part 1, Introduction to Gradle. Have a quick look if you have read it. Prerequisite: JDK must be installed…

The post Gradle: Part 2, Installing Gradle on Linux System appeared first on Code Saying.

]]>
In this part, we will install Gradle on the Linux system. I am having Ubuntu OS and we will use ppa for installation

Installing Gradle on the local Linux machine

This part is a continuation of Part 1, Introduction to Gradle. Have a quick look if you have read it.

Prerequisite: JDK must be installed on your system

I am using Ubuntu OS. We will be using this ppa for installation

Open a new terminal and execute the under commands:

sudo add-apt-repository ppa:cwchien/gradle
sudo apt-get update
sudo apt upgrade gradle

and that’s it! To check if the installation is properly done, execute the below-mentioned command on terminal

gradle -version

You will see the following logs on completion.

------------------------------------------------------------
Gradle 5.4.1
------------------------------------------------------------
Build time:   2019-04-26 08:14:42 UTC
Revision:     261d171646b36a6a28d5a19a69676cd098a4c19d

So that completes our installation. Don’t worry about particular versions, we will be using gradlew to manage gradle versions which I am covering in next part. So let’s move to next part PART 3: Set up java project using Gradle.

The post Gradle: Part 2, Installing Gradle on Linux System appeared first on Code Saying.

]]>
http://codesaying.com/installing-gradle-on-local-linux-system/feed/ 1
Gradle:Part 1, Introduction to Gradle http://codesaying.com/introduction-to-gradle/ http://codesaying.com/introduction-to-gradle/#comments Sun, 04 Aug 2019 15:32:42 +0000 http://codesaying.com/?p=145 This tutorial is divided into 4 parts Part 1: Introduction to Gradle, comparison with others and motivation Part 2: Installing Gradle on local Machine. Part 3: Setup Java project using Gradle. Part 4: Creating an executable jar using Gradle task. Introduction Gradle is an open-source build automation tool focused on flexibility and performance. Gradle nicely…

The post Gradle:Part 1, Introduction to Gradle appeared first on Code Saying.

]]>
This tutorial is divided into 4 parts

Part 1: Introduction to Gradle, comparison with others and motivation

Part 2: Installing Gradle on local Machine.

Part 3: Setup Java project using Gradle.

Part 4: Creating an executable jar using Gradle task.

Introduction

Gradle is an open-source build automation tool focused on flexibility and performance. Gradle nicely combines both Ant and Maven, taking the best from both frameworks. It uses domain-specific language based on the programming language Groovy or Kotlin, differentiating it from Apache Maven, which uses XML for its project configuration.

How Gradle compares with Maven or Apache Ant

Google has chosen Gradle as the official build tool for Android. Both Gradle and Maven provide convention over configuration. However, Maven provides a very rigid model that makes customizations tedious and sometimes impossible.

Gradle has better performance as compared to maven .The top 3 features that make Gradle much faster than Maven are:

Incrementality – Gradle avoids work by tracking input and output of tasks and only running what is necessary, and only processing files that changed when possible.

Build Cache – Reuses the build outputs of any other Gradle build with the same inputs, including between machines.

Gradle Daemon – A long-lived process that keeps build information “hot” in memory.

In Gradle you can either use DSL Groovy or Kotlin as compared to XML in Apache Maven. In sense you can do programming and write tasks using Groovy or Kotlin which is comparitively difficult in maven.

Apache Ant is also one more player with maven. Ant is total flexible like gradle and using Ivy gives better dependency management than Maven. But it doesn’t have great support for multi-project builds.

The stack share of Gradle vs others can be seen on stackshare.We can also look upto leaders who use Gradle in open source projects like Elastic Search , Hibernate-Orm,ReactiveX RxJava,libgdx, CrateDB, Many Netflix Open source Projects, and even Andriod SDK and lot more.

So now let’s start with the installation of Gradle on the local machine. We will do the installation in Part 2.

The post Gradle:Part 1, Introduction to Gradle appeared first on Code Saying.

]]>
http://codesaying.com/introduction-to-gradle/feed/ 1