Using MongoDB with Spring Boot

Spring Boot is a powerful framework for building microservices. It comes ready to work with almost every type of database, including the newer NoSQL variety. This guide shows you how to quickly integrate MongoDB with your Spring Boot Application

Dependency

Spring Boot has hundreds of starter packages that allow you to avoid writing code. They have a starter for mongodb as well. Include the following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Configuration

Add your database connection string in the your configuration file:

spring.data.mongodb.uri= mongodb://localhost:27017/mongodb

Model

Setup your entity model, just like you would for a traditional SQL entity


@Entity
@Data
public class Permit {
    @Id
    public String id;
    public String permitNum;
    public String revisionNum;
    public String permitType;
    public String structureType;
    public String work;
    public String streetNum;
    public String streetName;
    public String streetType;
    public String streetDirection;
    public String postal;
}

Setup Repository


public interface PermitRepository extends MongoRepository {
    List findAll();
}

That’s it! you can start using your Model to GET or POST data from your MongoDB Database

Menace of Unicode Domains

Spoofing is the age old method of tricking people to provide their information to malicious actors. Hackers have been spoofing email messages and domains by pretending to be someone else in hopes of gaining access to someones personal information. When ICANN decided to implement a new class of top-level domains, allowing the usage of ASCII in domains, it opened a whole new can of worms. Special characters like the Latin letter р are indistinguishable from the English letter p, allowing hackers to buy domains like “рayрal.com”. Although to the naked eye, this looks exactly the same as the payment processor PayPal.com, the Latin р in the domain make it a completely different domain, with different DNS point to a different resource. These special characters are encoded into what’s called Punycode1. The encoded version of the invalid paypal domain translates to http://xn--ayal-f6dc.com.

As of April 2017, all modern browsers automatically translate these unicode domains to their encoded punycodes, making it easier for users to avoid being the victims of spoofing attacks. However, a few months ago, some browsers left the unicode in the address bar, making it almost impossible for novice users (and most tech savvy users who were not paying attention) from recognising spoofing attempts. The Tech community raised this issue on twitter in March, forcing Chrome to release a fix that translates the Unicode domains in address bar.

 

  1. Punycode is a way to represent Unicode within the limited character set of ASCII used for internet host names.

Using H2 Database with Spring Boot

H2 is one of the more popular embedded databases out there today. Although there are 16-20 embedded databases out in the market, there are only 3 that work well with Spring (H2, Derby and HSQL).
Out of the three, H2 is considered the most matured and supported product. Although not recommended to use in production environment, H2 is robust enough to handle small scale production applications.

Using embedded H2 in Spring Boot is pretty simple. First you add the appropriate connection details in your configuration file, and then you can start using it in Spring like any other SQL database.

You need to add H2 as a maven dependency, there is no installs or setups required!

Dependency

<dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>1.4.195</version>
</dependency>

Configuration

spring.datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:bootexample;MODE=MySQL

Data Model

Once you have your database setup, you can use it the same way you would use any other database in Spring. You create a model for your database entity

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue
    private Long id;
    @NotNull
    @NotEmpty
    private String firstName;
    @NotNull
    @NotEmpty
    private String lastName;
    @NotNull
    @NotEmpty
    private String password;
    @ValidEmail
    private String email;
    @NotNull
    @NotEmpty
    private String phoneNumber;
    private String lastOnline;
    private Boolean enabled;
    public String getLastOnline() {
        return lastOnline;

    }

    public void setLastOnline(String lastOnline) {
        this.lastOnline = lastOnline;
    }

    public Boolean getEnabled() {
        return enabled;
    }

    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Long getId() {
        return id;
    }


    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

Repository

Finally, you can use Spring’s JpaRepositoryto manipulate your data

package com.fullstacktrace.domain;

import com.fullstacktrace.domain.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {
    public User findByEmail(String email);
}

Alternative to Github

GitHub came into existence in early 2008 and radically changed the way source code management is handled. GitHub is a web-based version control repository that uses the Git system of source control management, giving the developers a user-friendly interface to manage their code. Today, GitHub is one of the top Git products, being used by both open source developers, to development teams in large corporations.

GitHub allows anyone to host their code, as long as it’s public. If you want to have private repositories, you must sign up for a paid plan. Students can take advantage of their student plans to get free private repositories, amongst other goodies.

However, there are good alternatives to GitHub that offer the same features, but allow for free repositories. Some of the big ones are described below:

  1. Bit Bucket (By Atlassian)

    Atlassian, the creator of one of the widely used scrum management tool – Jira, have their own Git based source management product. Bit Bucket is a great alternative to GitHub as it provides most of the features provided by GitHub, but also allows for private repos under the free plan. The UI is not as appealing as GitHub’s and the search functionality can use more work. But for a free product, Bit Bucket is great!

  2. GitLab

    Not to be confused by the similar sounding name, GitLab is a completely separate project, managed by a completely different team. GitLab provides more features than GitHub, and like Bit Bucket allow for unlimited private repositories. However the performance is no where near GitHub.

  3. Beanstalk

    BeanStalk is another code management tool that doesn’t require downloading any tool. It is being run by the software company Wildbit. BeanStalk advertises themselves as more than just source management, as it comes packaged with a few deployment tools and processes lacking in GitHub and Bit Bucket.

  4. Apache Allura

    Apache Allura has the benefit of being an Apache Foundation project, but it is a relatively new project. Apache  Allura supports Git, SVN and Hg for code management. The search functionality is more powerful than that of GitLab, but the UI could use more work. It is a free and open source, however it is not hosted. You get the software, and require setting it up on your own server. This is a big disadvantage compared to the other.

References
  1. Git – Wikipedia
  2. GitHub
  3. GitHub Student Plans
  4. BeanStalk

Hibernate Database Creation properties

Hibernate is a powerful open source java persistence framework. One of it’s feature is that it can automatically create your databases for you based on your code.
When you set the hibernate.hbm2dll.auto property, it allows you to either update, create, create-drop or validate your schema.

From the community documentation:

hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop

The legal options are :

    • validate: validate the schema, makes no changes to the database.
    • update: update the schema.
    • create: creates the schema, destroying previous data.
    • create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.

Testing your APIs with POSTMAN

Anyone who develops anything knows that they need tools to test their product. Developing APIs is no different. In order to ensure that you are releasing something that actually works, you need to test your APIs by hitting the endpoints and validating the responses.

I’ve been using POSTMAN to do this task for me. It is a clean, free tool that lets you send requests to your API, with full control on what’s sent (headers, content) and shows the full responses. It also saves your history so you can test an endpoint without having to retype the parameters over and over again.

 

Give POSTMAN a try, and let me know if you are using something else.

Creating Temporary Files in C#

Many programs create temporary files on your computer while they’re running. Temporary files are used to save data that’s either too large to be stored in memory, or need to be accessed by different resources, or needs to be persisted to allow smoother running of the application (almost like a cache).

Temporary files are stored under AppData/Local/Temp. The path is usually set in environment variables, and can be changed. If you go to %tmp% you’ll see a whole bunch of folders and files generated by various programs running on your machine.

If you need to create temporary files in your application, you can leverage the powerful System.IO.Path class.

Using Path.GetTempPath() will create a temporary file with a random* name in the temporary folder, and return the name of the newly created file.

It is the developer’s responsbility to either delete the file when it’s done being used, or leave it to the user to run disk cleaner.

If you need to create the temporary file for a specific use case and ensure it’s deleted, you can use FileOptions.DeleteOnClose option when creating your FileStream:


using (FileStream fs = new FileStream(Path.GetTempFileName(), 
       FileMode.Open, FileAccess.ReadWrite, FileShare.None, 4096, 
       FileOptions.DeleteOnClose))
{
    //To Something with the file
}//File no longer exists

References:

  1. MSDN

Create beautiful GIF user guides

A picture is worth a 1000 words. Pictures are very useful in conveying a message to a diverse use base. You often see images in user manuals, explaining some of the more complicated tasks.

Animation and Videos are worth more than static images! Now instead of taking 10 screenshots to show a process, you can capture the screen and record the process. There are a heap of tools available in the market that allow you to record your screen. However, hosting videos are often complicated, and require plugins to view.

With ScreenToGif, you can record the screen and turn it into a high resolution Gif, allowing you to embed the animated pictures to your user guides.

ScreenToGif recorder screenshot

 

ScreenToGif is open source, and free to download.

Next time you find yourself looking for tools to download to capture your screen, try ScreenToGif and create pictures instead of videos!

References:

https://github.com/NickeManarin/ScreenToGif